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
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
// SPDX-FileCopyrightText: 2026 Sephyi <me@sephy.io>
//
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
use std::collections::HashSet;
use crate::config::Config;
use crate::domain::diff::{ChangeDetail, SymbolDiff};
use crate::domain::{
ChangeIntent, ChangeStatus, CodeSymbol, CommitType, FileCategory, IntentKind, PromptContext,
SpanChangeKind, StagedChanges, SymbolKind,
};
const SYSTEM_PROMPT_RESERVE: usize = 2_000;
const MIN_DIFF_BUDGET: usize = 4_000;
/// Lock files to skip content for (just show that they changed)
const SKIP_CONTENT_FILES: &[&str] = &[
"Cargo.lock",
"package-lock.json",
"yarn.lock",
"pnpm-lock.yaml",
"bun.lockb",
"go.sum",
"Gemfile.lock",
"poetry.lock",
"composer.lock",
"Pipfile.lock",
"uv.lock",
"pubspec.lock",
"flake.lock",
"shrinkwrap.yaml",
"mix.lock",
];
pub struct ContextBuilder;
impl ContextBuilder {
pub fn build(
changes: &StagedChanges,
symbols: &[CodeSymbol],
diffs: &[SymbolDiff],
config: &Config,
) -> PromptContext {
// Build components with budget management
let change_summary = Self::summarize_changes(changes);
let file_breakdown = Self::format_files(changes);
// Calculate remaining budget for symbols and diff
let max_context = config.max_context_chars;
let used = SYSTEM_PROMPT_RESERVE + change_summary.len() + file_breakdown.len();
let remaining = max_context.saturating_sub(used);
// When structural diffs are available, symbols need less budget (diffs carry the detail).
// When only signatures are available, symbols still get 30%.
// Base case without signatures: 20%.
let has_structural_diffs = !diffs.is_empty();
let symbol_pct = if has_structural_diffs {
20
} else if symbols.iter().any(|s| s.signature.is_some()) {
30
} else {
20
};
let diff_budget = remaining
.saturating_sub(remaining * symbol_pct / 100)
.max(MIN_DIFF_BUDGET);
let symbol_budget = remaining.saturating_sub(diff_budget);
// Tri-state symbol classification:
// - AddedOnly: symbol appears only in added set
// - RemovedOnly: symbol appears only in removed set
// - Modified: same name+kind+file in both added and removed (signature changed)
//
// Modified symbols are shown separately (not as both Added and Removed, which
// misleads the LLM). Public modified symbols contribute to breaking risk.
//
// Uses HashSet for O(1) lookup instead of O(N^2) nested iteration (P2).
type SymbolKey<'a> = (&'a SymbolKind, &'a str, &'a std::path::Path);
let added_keys: HashSet<SymbolKey<'_>> = symbols
.iter()
.filter(|s| s.is_added)
.map(|s| (&s.kind, s.name.as_str(), s.file.as_path()))
.collect();
let removed_keys: HashSet<SymbolKey<'_>> = symbols
.iter()
.filter(|s| !s.is_added)
.map(|s| (&s.kind, s.name.as_str(), s.file.as_path()))
.collect();
// Build modified symbols with whitespace classification
let mut modified_symbols: Vec<CodeSymbol> = symbols
.iter()
.filter(|s| {
s.is_added && removed_keys.contains(&(&s.kind, s.name.as_str(), s.file.as_path()))
})
.cloned()
.collect();
// Populate is_whitespace_only by comparing diff content within each symbol's span.
// Uses separate old/new line ranges since the same symbol may be at different
// line numbers in HEAD vs staged (e.g., lines added above it shift everything).
for symbol in &mut modified_symbols {
if let Some(file_change) = changes.files.iter().find(|f| f.path == symbol.file) {
// Find the old-side counterpart for its line range
let old_sym = symbols.iter().find(|s| {
!s.is_added
&& s.name == symbol.name
&& s.kind == symbol.kind
&& s.file == symbol.file
});
let (old_start, old_end) = old_sym
.map(|s| (s.line, s.end_line))
.unwrap_or((symbol.line, symbol.end_line));
symbol.is_whitespace_only = Self::classify_span_change(
&file_change.diff,
symbol.line,
symbol.end_line,
old_start,
old_end,
);
symbol.span_change_kind = Self::classify_span_change_rich(
&file_change.diff,
symbol.line,
symbol.end_line,
old_start,
old_end,
);
}
}
let symbols_deduped: Vec<CodeSymbol> = symbols
.iter()
.filter(|s| {
let key: SymbolKey<'_> = (&s.kind, s.name.as_str(), s.file.as_path());
if s.is_added {
!removed_keys.contains(&key)
} else {
!added_keys.contains(&key)
}
})
.cloned()
.collect();
// Detect change intents from diff patterns
let intents = Self::detect_intents(changes);
// Infer commit type AFTER classification so it can see whitespace-only data
let all_modified_ws = !modified_symbols.is_empty()
&& modified_symbols
.iter()
.all(|s| s.is_whitespace_only == Some(true));
let all_modified_docs = !modified_symbols.is_empty()
&& modified_symbols
.iter()
.all(|s| s.span_change_kind == Some(SpanChangeKind::DocsOnly));
let commit_type = Self::infer_commit_type(
changes,
&symbols_deduped,
all_modified_ws,
all_modified_docs,
);
// Intent-based type refinement (conservative — only for hard-to-detect patterns)
let commit_type = Self::refine_type_with_intents(commit_type, &intents);
let scope = if config.format.include_scope {
Self::infer_scope(changes)
} else {
None
};
let symbols_added =
Self::format_symbols_with_budget(&symbols_deduped, true, symbol_budget / 3);
let symbols_removed =
Self::format_symbols_with_budget(&symbols_deduped, false, symbol_budget / 3);
// Collect the removed-side counterparts for modified symbols (to show old→new signatures)
let modified_old: Vec<&CodeSymbol> = symbols
.iter()
.filter(|s| {
!s.is_added && added_keys.contains(&(&s.kind, s.name.as_str(), s.file.as_path()))
})
.collect();
// Format modified symbols (signature changes), excluding whitespace-only
let semantic_modified: Vec<&CodeSymbol> = modified_symbols
.iter()
.filter(|s| s.is_whitespace_only != Some(true))
.collect();
let symbols_modified =
Self::format_modified_symbols(&semantic_modified, &modified_old, symbol_budget / 3);
// Highlight removed public symbols — strong signal for breaking changes
let public_api_removed = Self::format_public_api_removed(&symbols_deduped);
// Diff gets remaining budget
let actual_diff_budget = max_context
.saturating_sub(used)
.saturating_sub(symbols_added.len())
.saturating_sub(symbols_removed.len())
.saturating_sub(symbols_modified.len())
.saturating_sub(public_api_removed.len());
let truncated_diff = Self::truncate_diff_adaptive(changes, config, actual_diff_budget);
// Evidence flags for constraint-based anti-hallucination
let is_mechanical = Self::detect_mechanical_transform(changes, &symbols_deduped);
let has_bug_evidence = Self::detect_bug_evidence(changes);
// Only genuinely removed public symbols count as "removed API".
// Modified public symbols (same name in old+new) are NOT removals — their
// signatures may have changed but the API still exists. Counting them as
// removed triggers false "breaking_change required" validator violations.
let public_api_removed_count = symbols_deduped
.iter()
.filter(|s| !s.is_added && s.is_public)
.count();
let has_new_public_api = symbols_deduped.iter().any(|s| s.is_added && s.is_public);
let is_dependency_only = Self::detect_dependency_only(changes);
let has_unsafe_addition = diffs.iter().any(|d| {
d.changes
.iter()
.any(|c| matches!(c, ChangeDetail::UnsafeAdded))
});
PromptContext {
change_summary,
file_breakdown,
symbols_added,
symbols_removed,
symbols_modified,
public_api_removed,
suggested_type: commit_type,
suggested_scope: scope,
truncated_diff,
is_mechanical,
has_bug_evidence,
public_api_removed_count,
has_new_public_api,
is_dependency_only,
file_count: changes.files.len(),
primary_change: Self::detect_primary_change(changes, &symbols_deduped),
group_rationale: None, // Set by splitter when generating per-group prompts
metadata_breaking_signals: Self::detect_metadata_breaking(changes),
locale: config.locale.clone(),
history_context: None, // Set by App when learn_from_history is enabled
connections: Self::detect_connections(changes, symbols),
import_changes: Self::detect_import_changes(changes),
test_correlations: Self::detect_test_correlation(changes),
structured_changes: diffs.to_vec(),
intents,
has_unsafe_addition,
}
}
/// Classify whether changes within a symbol span are whitespace-only.
///
/// Tracks old-file and new-file line numbers independently, using separate
/// spans for each: `new_start..new_end` for added lines, `old_start..old_end`
/// for removed lines. This correctly handles cases where the same symbol is
/// at different line numbers in HEAD vs staged (e.g., lines added above it).
///
/// Returns `None` if no changes in span, `Some(true)` if whitespace-only,
/// `Some(false)` if semantic changes detected.
pub(crate) fn classify_span_change(
diff: &str,
new_start: usize,
new_end: usize,
old_start: usize,
old_end: usize,
) -> Option<bool> {
use crate::services::analyzer::DiffHunk;
let hunks = DiffHunk::parse_from_diff(diff);
let mut added_in_span: Vec<&str> = Vec::new();
let mut removed_in_span: Vec<&str> = Vec::new();
let mut current_old_line: usize = 0;
let mut current_new_line: usize = 0;
let mut hunk_idx: usize = 0;
let mut in_hunk = false;
for line in diff.lines() {
if line.starts_with("@@") {
if hunk_idx < hunks.len() {
current_old_line = hunks[hunk_idx].old_start;
current_new_line = hunks[hunk_idx].new_start;
hunk_idx += 1;
in_hunk = true;
}
continue;
}
if !in_hunk || line.starts_with("+++") || line.starts_with("---") {
continue;
}
if let Some(content) = line.strip_prefix('+') {
let in_new_span = current_new_line >= new_start && current_new_line <= new_end;
if in_new_span {
added_in_span.push(content);
}
current_new_line += 1;
} else if let Some(content) = line.strip_prefix('-') {
let in_old_span = current_old_line >= old_start && current_old_line <= old_end;
if in_old_span {
removed_in_span.push(content);
}
current_old_line += 1;
} else {
// Context line — advances both counters
current_old_line += 1;
current_new_line += 1;
}
}
if added_in_span.is_empty() && removed_in_span.is_empty() {
return None;
}
// Compare non-whitespace character streams.
// Correctly handles line wrapping while detecting actual content changes.
let old_text: String = removed_in_span
.iter()
.flat_map(|l| l.chars())
.filter(|c| !c.is_whitespace())
.collect();
let new_text: String = added_in_span
.iter()
.flat_map(|l| l.chars())
.filter(|c| !c.is_whitespace())
.collect();
Some(old_text == new_text)
}
/// Classify changes within a symbol span with doc-vs-code distinction.
///
/// Returns a richer `SpanChangeKind` that distinguishes whitespace-only,
/// doc-only, mixed, and semantic changes. Returns `None` if no changes
/// fall within the symbol span.
pub(crate) fn classify_span_change_rich(
diff: &str,
new_start: usize,
new_end: usize,
old_start: usize,
old_end: usize,
) -> Option<SpanChangeKind> {
use crate::services::analyzer::DiffHunk;
let hunks = DiffHunk::parse_from_diff(diff);
let mut added_in_span: Vec<&str> = Vec::new();
let mut removed_in_span: Vec<&str> = Vec::new();
let mut current_old_line: usize = 0;
let mut current_new_line: usize = 0;
let mut hunk_idx: usize = 0;
let mut in_hunk = false;
for line in diff.lines() {
if line.starts_with("@@") {
if hunk_idx < hunks.len() {
current_old_line = hunks[hunk_idx].old_start;
current_new_line = hunks[hunk_idx].new_start;
hunk_idx += 1;
in_hunk = true;
}
continue;
}
if !in_hunk || line.starts_with("+++") || line.starts_with("---") {
continue;
}
if let Some(content) = line.strip_prefix('+') {
if current_new_line >= new_start && current_new_line <= new_end {
added_in_span.push(content);
}
current_new_line += 1;
} else if let Some(content) = line.strip_prefix('-') {
if current_old_line >= old_start && current_old_line <= old_end {
removed_in_span.push(content);
}
current_old_line += 1;
} else {
current_old_line += 1;
current_new_line += 1;
}
}
if added_in_span.is_empty() && removed_in_span.is_empty() {
return None;
}
// Check whitespace-only first (same logic as classify_span_change)
let old_text: String = removed_in_span
.iter()
.flat_map(|l| l.chars())
.filter(|c| !c.is_whitespace())
.collect();
let new_text: String = added_in_span
.iter()
.flat_map(|l| l.chars())
.filter(|c| !c.is_whitespace())
.collect();
if old_text == new_text {
return Some(SpanChangeKind::WhitespaceOnly);
}
// Classify each changed line as doc or code
let has_doc = added_in_span
.iter()
.chain(removed_in_span.iter())
.any(|l| Self::is_doc_comment(l));
let has_code = added_in_span.iter().chain(removed_in_span.iter()).any(|l| {
let trimmed = l.trim();
!trimmed.is_empty() && !Self::is_doc_comment(l)
});
match (has_doc, has_code) {
(true, false) => Some(SpanChangeKind::DocsOnly),
(true, true) => Some(SpanChangeKind::Mixed),
(false, _) => Some(SpanChangeKind::Semantic),
}
}
/// Check if a line looks like a doc comment or regular comment.
fn is_doc_comment(line: &str) -> bool {
let trimmed = line.trim();
trimmed.starts_with("///")
|| trimmed.starts_with("//!")
|| trimmed.starts_with("/**")
|| trimmed.starts_with("* ") // inside /** */ block
|| trimmed.starts_with("*/")
|| trimmed.starts_with('#') // Python/Ruby comments
|| trimmed.starts_with("\"\"\"") // Python docstrings
|| (trimmed.starts_with("//") && !trimmed.starts_with("///") && !trimmed.starts_with("//!"))
}
pub fn infer_commit_type(
changes: &StagedChanges,
symbols: &[CodeSymbol],
all_modified_whitespace_only: bool,
all_modified_docs_only: bool,
) -> CommitType {
let categories: Vec<_> = changes.files.iter().map(|f| f.category).collect();
// All docs -> docs
if categories.iter().all(|c| *c == FileCategory::Docs) {
return CommitType::Docs;
}
// All tests -> test
if categories.iter().all(|c| *c == FileCategory::Test) {
return CommitType::Test;
}
// Predominantly test additions (>80%) → test type
// Cross-multiply to avoid integer division truncation (F-009):
// test_additions/total_additions > 80/100 ⟹ test_additions * 100 > total_additions * 80
let test_additions: usize = changes
.files
.iter()
.filter(|f| f.category == FileCategory::Test)
.map(|f| f.additions)
.sum();
let total_additions: usize = changes.files.iter().map(|f| f.additions).sum();
if total_additions > 0 && test_additions * 100 > total_additions * 80 {
return CommitType::Test;
}
// All config -> chore
if categories.iter().all(|c| *c == FileCategory::Config) {
return CommitType::Chore;
}
// All build -> build
if categories.iter().all(|c| *c == FileCategory::Build) {
return CommitType::Build;
}
// All modified symbols are whitespace-only and no added/removed symbols → style
// (catches `cargo fmt` where symbols exist but only spacing changed)
if all_modified_whitespace_only && symbols.is_empty() {
return CommitType::Style;
}
// All modified symbols are docs-only and no added/removed symbols → docs
// (catches doc comment edits inside existing functions/structs)
if all_modified_docs_only && symbols.is_empty() {
return CommitType::Docs;
}
// Explicit bug evidence -> fix
if Self::detect_bug_evidence(changes) {
return CommitType::Fix;
}
// Single-pass symbol evidence: compute all flags in one iteration
let (has_new_public, has_removed_public, has_any_new, has_any_removed) =
symbols.iter().fold(
(false, false, false, false),
|(mut np, mut rp, mut an, mut ar), s| {
let is_api_kind = matches!(
s.kind,
SymbolKind::Function | SymbolKind::Struct | SymbolKind::Trait
);
if s.is_added {
an = true;
if s.is_public && is_api_kind {
np = true;
}
} else {
ar = true;
if s.is_public && is_api_kind {
rp = true;
}
}
(np, rp, an, ar)
},
);
// API replacement: adding new public APIs while removing old ones → refactor
if has_new_public && has_removed_public {
return CommitType::Refactor;
}
if has_new_public {
return CommitType::Feat;
}
// New files dominate -> feat
let new_file_count = changes
.files
.iter()
.filter(|f| f.status == ChangeStatus::Added)
.count();
if new_file_count > changes.files.len() / 2 {
return CommitType::Feat;
}
// More deletions than additions -> refactor
if changes.stats.deletions > changes.stats.insertions * 2 {
return CommitType::Refactor;
}
// Balanced small changes (additions ≈ deletions) with no new symbols -> style/refactor
// This catches mechanical transformations like reformatting, collapsing nesting, etc.
if changes.stats.insertions < 20 && changes.stats.deletions < 20 {
let balanced = changes.stats.insertions.abs_diff(changes.stats.deletions) <= 5;
if balanced && !has_any_new && !has_any_removed {
return CommitType::Style;
}
return CommitType::Refactor;
}
CommitType::Refactor
}
pub fn infer_scope(changes: &StagedChanges) -> Option<String> {
let scopes: Vec<_> = changes
.files
.iter()
.filter(|f| f.category == FileCategory::Source)
.filter_map(|f| Self::extract_scope_from_path(&f.path))
.collect();
if scopes.is_empty() {
return None;
}
// If all same scope
let first = &scopes[0];
if scopes.iter().all(|s| s == first) {
return Some(first.clone());
}
None
}
fn extract_scope_from_path(path: &std::path::Path) -> Option<String> {
let components: Vec<_> = path
.components()
.filter_map(|c| c.as_os_str().to_str())
.collect();
for (i, component) in components.iter().enumerate() {
match *component {
"src" | "lib" | "app" | "internal" | "cmd" | "api" | "modules" => {
if let Some(next) = components.get(i + 1)
&& !next.contains('.')
&& *next != "main"
&& *next != "lib"
&& *next != "mod"
&& *next != "index"
{
return Some(next.to_string());
}
}
"packages" | "crates" | "apps" | "services" | "plugins" | "workspaces" => {
if let Some(next) = components.get(i + 1)
&& !next.contains('.')
{
return Some(next.to_string());
}
}
_ => {}
}
}
path.parent()
.and_then(|p| p.file_name())
.and_then(|n| n.to_str())
.filter(|n| !matches!(*n, "src" | "lib" | "." | ""))
.map(|s| s.to_string())
}
fn summarize_changes(changes: &StagedChanges) -> String {
let added = changes
.files
.iter()
.filter(|f| f.status == ChangeStatus::Added)
.count();
let modified = changes
.files
.iter()
.filter(|f| f.status == ChangeStatus::Modified)
.count();
let deleted = changes
.files
.iter()
.filter(|f| f.status == ChangeStatus::Deleted)
.count();
let renamed = changes
.files
.iter()
.filter(|f| f.status == ChangeStatus::Renamed)
.count();
let mut parts = vec![
format!("{} added", added),
format!("{} modified", modified),
format!("{} deleted", deleted),
];
if renamed > 0 {
parts.push(format!("{} renamed", renamed));
}
format!(
"{} files ({}) | +{} -{}",
changes.files.len(),
parts.join(", "),
changes.stats.insertions,
changes.stats.deletions
)
}
fn format_files(changes: &StagedChanges) -> String {
let mut output = String::new();
for file in changes.files_by_priority() {
if file.is_binary {
continue;
}
match file.status {
ChangeStatus::Renamed => {
let old = file
.old_path
.as_ref()
.map(|p| p.display().to_string())
.unwrap_or_else(|| "?".into());
let sim = file.rename_similarity.unwrap_or(0);
output.push_str(&format!(
"[R] {} -> {} ({}% similar, +{} -{})\n",
old,
file.path.display(),
sim,
file.additions,
file.deletions
));
}
_ => {
let status = match file.status {
ChangeStatus::Added => "[+]",
ChangeStatus::Modified => "[M]",
ChangeStatus::Deleted => "[-]",
ChangeStatus::Renamed => unreachable!(),
};
output.push_str(&format!(
"{} {} (+{} -{})\n",
status,
file.path.display(),
file.additions,
file.deletions
));
}
}
}
output
}
fn format_symbols_with_budget(
symbols: &[CodeSymbol],
added: bool,
char_budget: usize,
) -> String {
let filtered: Vec<_> = symbols.iter().filter(|s| s.is_added == added).collect();
if filtered.is_empty() {
return String::new();
}
let mut output = String::new();
let mut count = 0;
for symbol in &filtered {
let line = symbol.to_string();
if output.len() + line.len() + 1 > char_budget {
break;
}
if !output.is_empty() {
output.push('\n');
}
output.push_str(&line);
count += 1;
}
// Indicate if we truncated
let remaining = filtered.len() - count;
if remaining > 0 {
output.push_str(&format!("\n... and {} more symbols", remaining));
}
output
}
/// Format modified symbols (signature changed: same name+kind+file in both added and removed).
///
/// When both old and new signatures are available and differ, shows the transition as
/// `[~] old_sig → new_sig (file:line)`. Falls back to signature-only or kind+name display.
fn format_modified_symbols(
new_symbols: &[&CodeSymbol],
old_symbols: &[&CodeSymbol],
char_budget: usize,
) -> String {
if new_symbols.is_empty() {
return String::new();
}
let mut output = String::new();
let mut count = 0;
for new_sym in new_symbols {
// Match by name+kind+file to support overloaded languages
let old_sym = old_symbols.iter().find(|s| {
s.name == new_sym.name && s.kind == new_sym.kind && s.file == new_sym.file
});
let line = match (
old_sym.and_then(|s| s.signature.as_ref()),
new_sym.signature.as_ref(),
) {
(Some(old_sig), Some(new_sig)) if old_sig != new_sig => {
format!(
"[~] {} \u{2192} {} ({}:{})",
old_sig,
new_sig,
new_sym.file.display(),
new_sym.line
)
}
(_, Some(sig)) => {
format!("[~] {} ({}:{})", sig, new_sym.file.display(), new_sym.line)
}
_ => {
let visibility = if new_sym.is_public { "pub " } else { "" };
format!(
"[~] {}{:?} {} ({}:{})",
visibility,
new_sym.kind,
new_sym.name,
new_sym.file.display(),
new_sym.line
)
}
};
// Append doc-vs-code suffix when span_change_kind is informative
let suffix = match new_sym.span_change_kind {
Some(SpanChangeKind::DocsOnly) => " [docs only]",
Some(SpanChangeKind::Mixed) => " [docs + code]",
_ => "",
};
let line = format!("{}{}", line, suffix);
if output.len() + line.len() + 1 > char_budget {
break;
}
if !output.is_empty() {
output.push('\n');
}
output.push_str(&line);
count += 1;
}
let remaining = new_symbols.len() - count;
if remaining > 0 {
output.push_str(&format!("\n... and {} more modified symbols", remaining));
}
output
}
/// Format removed public symbols as a prominent warning for the LLM.
/// This helps small models detect breaking changes they would otherwise miss.
fn format_public_api_removed(symbols: &[CodeSymbol]) -> String {
let removed_public: Vec<_> = symbols
.iter()
.filter(|s| !s.is_added && s.is_public)
.collect();
if removed_public.is_empty() {
return String::new();
}
let mut output = String::new();
for symbol in &removed_public {
if !output.is_empty() {
output.push('\n');
}
output.push_str(&symbol.to_string());
}
output
}
/// Detect if changes are a mechanical/syntactic transformation with no semantic impact.
///
/// True when: no symbol definitions changed, adds ≈ removes (balanced),
/// and changes are small. Catches reformatting, nesting collapse, import reorder.
fn detect_mechanical_transform(changes: &StagedChanges, symbols: &[CodeSymbol]) -> bool {
// Any symbol added or removed means it's not purely mechanical
if !symbols.is_empty() {
return false;
}
let ins = changes.stats.insertions;
let del = changes.stats.deletions;
let total = ins + del;
// Need actual changes, and they should be small
if total == 0 || total > 80 {
return false;
}
// Must be balanced (adds ≈ removes)
let balance = ins.min(del) as f64 / ins.max(del).max(1) as f64;
balance > 0.5
}
/// Detect if the diff contains evidence of a bug fix.
///
/// Conservative: only flags explicit fix/bug comments in added lines.
/// When false, the model is guided away from using "fix" type.
fn detect_bug_evidence(changes: &StagedChanges) -> bool {
changes.files.iter().any(|f| {
f.diff
.lines()
.filter(|l| l.starts_with('+') && !l.starts_with("+++"))
.any(|l| {
let lower = l[1..].to_lowercase();
lower.contains("// fix")
|| lower.contains("# fix")
|| lower.contains("/* fix")
|| lower.contains("// bug")
|| lower.contains("# bug")
|| lower.contains("fixme")
|| lower.contains("hotfix")
})
})
}
/// Detect if all changes are to dependency/config files only.
fn detect_dependency_only(changes: &StagedChanges) -> bool {
!changes.files.is_empty()
&& changes
.files
.iter()
.all(|f| matches!(f.category, FileCategory::Config | FileCategory::Build))
}
/// Identify the most significant change to anchor the subject line.
///
/// Priority: new public APIs > removed public APIs > largest file by change size > new private symbols.
fn detect_primary_change(changes: &StagedChanges, symbols: &[CodeSymbol]) -> Option<String> {
// 1. New public API (highest signal)
let new_public: Vec<_> = symbols
.iter()
.filter(|s| s.is_added && s.is_public)
.collect();
if let Some(sym) = new_public.first() {
return Some(format!("added {:?} {} (public)", sym.kind, sym.name));
}
// 2. Removed public API (breaking = important)
let removed_public: Vec<_> = symbols
.iter()
.filter(|s| !s.is_added && s.is_public)
.collect();
if let Some(sym) = removed_public.first() {
return Some(format!("removed {:?} {} (public)", sym.kind, sym.name));
}
// 3. File with most lines changed
let biggest = changes
.files
.iter()
.max_by_key(|f| f.additions + f.deletions);
if let Some(f) = biggest {
let stem = f
.path
.file_stem()
.and_then(|s| s.to_str())
.unwrap_or("unknown");
return Some(format!(
"most changes in {} (+{} -{})",
stem, f.additions, f.deletions
));
}
None
}
/// Detect cross-file relationships: added lines that call symbols from other changed files.
fn detect_connections(changes: &StagedChanges, symbols: &[CodeSymbol]) -> Vec<String> {
let mut connections = Vec::new();
let symbol_files: Vec<(&str, &std::path::Path)> = symbols
.iter()
.filter(|s| s.is_added)
.map(|s| (s.name.as_str(), s.file.as_path()))
.collect();
for file in &changes.files {
for (sym_name, sym_file) in &symbol_files {
// Skip self-references and short names that cause false positives
if file.path.as_path() == *sym_file || sym_name.len() < 4 {
continue;
}
let call_pattern = format!("{}(", sym_name);
let has_call = file.diff.lines().any(|line| {
line.starts_with('+')
&& !line.starts_with("+++")
&& line.contains(&call_pattern)
});
if has_call {
let caller = file
.path
.file_stem()
.and_then(|s| s.to_str())
.unwrap_or("?");
connections.push(format!("{} calls {}() — both changed", caller, sym_name));
}
if connections.len() >= 5 {
break;
}
}
if connections.len() >= 5 {
break;
}
}
connections.sort();
connections.dedup();
connections.truncate(5);
connections
}
/// Detect added/removed import statements from diff lines.
fn detect_import_changes(changes: &StagedChanges) -> Vec<String> {
let mut imports = Vec::new();
for file in &changes.files {
for line in file.diff.lines() {
// Skip diff headers
if line.starts_with("+++") || line.starts_with("---") {
continue;
}
// Detect added/removed import lines
if (line.starts_with('+') && Self::is_import_line(&line[1..]))
|| (line.starts_with('-') && Self::is_import_line(&line[1..]))
{
let action = if line.starts_with('+') {
"added"
} else {
"removed"
};
let stem = file
.path
.file_stem()
.and_then(|s| s.to_str())
.unwrap_or("?");
let content = line[1..].trim();
imports.push(format!("{}: {} {}", stem, action, content));
}
}
}
imports.truncate(10); // Cap to avoid prompt bloat
imports
}
/// Detect source-to-test file relationships among staged changes.
fn detect_test_correlation(changes: &StagedChanges) -> Vec<String> {
let mut correlations = Vec::new();
let source_files: Vec<_> = changes
.files
.iter()
.filter(|f| f.category == FileCategory::Source)
.collect();
let test_files: Vec<_> = changes
.files
.iter()
.filter(|f| f.category == FileCategory::Test)
.collect();
for src in &source_files {
let src_stem = src.path.file_stem().and_then(|s| s.to_str()).unwrap_or("");
for test in &test_files {
let test_stem = test.path.file_stem().and_then(|s| s.to_str()).unwrap_or("");
if test_stem == src_stem || test_stem.starts_with(src_stem) {
correlations.push(format!(
"{} <-> {} (test file)",
src.path.display(),
test.path.display()
));
}
}
}
correlations.truncate(5);
correlations
}
/// Detect change intent patterns from diff content.
///
/// Scans added lines for common patterns (error handling, tests, logging,
/// dependency updates) and emits intents with confidence scores based on
/// frequency relative to total added lines. Capped at 3 intents.
fn detect_intents(changes: &StagedChanges) -> Vec<ChangeIntent> {
let mut intents = Vec::new();
let mut error_handling_count: usize = 0;
let mut test_count: usize = 0;
let mut logging_count: usize = 0;
let mut dep_update = false;
let mut total_added: usize = 0;
for file in &changes.files {
let filename = file.path.file_name().and_then(|n| n.to_str()).unwrap_or("");
for line in file.diff.lines() {
if !line.starts_with('+') || line.starts_with("+++") {
continue;
}
total_added += 1;
let content = &line[1..];
let trimmed = content.trim();
// Error handling patterns
if trimmed.contains("Result<")
|| trimmed.contains("Result::")
|| trimmed.ends_with('?')
|| trimmed.contains("Err(")
|| trimmed.contains(".expect(")
|| trimmed.contains("try {")
|| trimmed.contains("catch ")
|| trimmed.contains(".unwrap_or(")
|| trimmed.contains(".map_err(")
{
error_handling_count += 1;
}
// Test patterns
if trimmed.contains("#[test]")
|| trimmed.contains("#[tokio::test]")
|| trimmed.starts_with("fn test_")
|| trimmed.starts_with("async fn test_")
|| trimmed.contains("assert!")
|| trimmed.contains("assert_eq!")
{
test_count += 1;
}
// Logging patterns
if trimmed.contains("tracing::")
|| trimmed.contains("log::")
|| trimmed.contains("debug!(")
|| trimmed.contains("info!(")
|| trimmed.contains("warn!(")
|| trimmed.contains("error!(")
|| trimmed.contains("console.log")
|| trimmed.contains("println!(")
|| trimmed.contains("eprintln!(")
{
logging_count += 1;
}
}
// Dependency update detection
if matches!(
filename,
"Cargo.toml" | "package.json" | "pyproject.toml" | "go.mod"
) {
let has_version_change = file.diff.lines().any(|l| {
l.starts_with('+')
&& !l.starts_with("+++")
&& (l.contains("version") || l.contains("\"^") || l.contains("\"~"))
});
if has_version_change {
dep_update = true;
}
}
}
// Emit intents with confidence based on frequency
if total_added > 0 {
if error_handling_count > 2 {
let confidence = (error_handling_count as f32 / total_added as f32).min(1.0);
intents.push(ChangeIntent {
kind: IntentKind::ErrorHandlingAdded,
confidence,
evidence: format!(
"{error_handling_count} error handling patterns in added lines"
),
});
}
if test_count > 2 {
let confidence = (test_count as f32 / total_added as f32).min(1.0);
intents.push(ChangeIntent {
kind: IntentKind::TestAdded,
confidence,
evidence: format!("{test_count} test patterns in added lines"),
});
}
if logging_count > 2 {
let confidence = (logging_count as f32 / total_added as f32).min(1.0);
intents.push(ChangeIntent {
kind: IntentKind::LoggingAdded,
confidence,
evidence: format!("{logging_count} logging statements added"),
});
}
}
if dep_update {
intents.push(ChangeIntent {
kind: IntentKind::DependencyUpdate,
confidence: 0.9,
evidence: "version changes in dependency manifest".into(),
});
}
intents.truncate(3); // Cap to avoid prompt bloat
intents
}
/// Refine the inferred commit type based on high-confidence intent signals.
///
/// Conservative: only overrides for patterns that are hard to detect from
/// file categories or symbols alone (e.g., performance optimization).
/// Other intents inform the LLM via the prompt, not override the heuristic.
fn refine_type_with_intents(base_type: CommitType, intents: &[ChangeIntent]) -> CommitType {
for intent in intents {
if intent.confidence >= 0.5 && intent.kind == IntentKind::PerformanceOptimization {
return CommitType::Perf;
}
}
base_type
}
fn is_import_line(line: &str) -> bool {
let trimmed = line.trim();
trimmed.starts_with("use ")
|| trimmed.starts_with("import ")
|| trimmed.starts_with("from ")
|| trimmed.starts_with("require(")
|| trimmed.starts_with("#include") // C/C++
}
/// Scan diff content for metadata changes that indicate breaking changes.
///
/// Detects: MSRV bumps, minimum engine/runtime version raises, removed features/exports.
fn detect_metadata_breaking(changes: &StagedChanges) -> Vec<String> {
let mut signals = Vec::new();
for file in &changes.files {
let name = file.path.file_name().and_then(|n| n.to_str()).unwrap_or("");
for line in file.diff.lines() {
let is_removed = line.starts_with('-') && !line.starts_with("---");
let is_added = line.starts_with('+') && !line.starts_with("+++");
let content = if is_removed || is_added {
&line[1..]
} else {
continue;
};
match name {
"Cargo.toml" => {
// rust-version (MSRV) changed
if content.contains("rust-version") && is_added {
signals.push(format!("MSRV changed in Cargo.toml: {}", content.trim()));
}
}
"package.json" => {
// engines.node minimum raised
if content.contains("\"node\"") && is_added && content.contains("engines") {
signals.push(format!(
"Node engine requirement changed: {}",
content.trim()
));
}
}
"pyproject.toml" => {
// requires-python minimum raised
if content.contains("requires-python") && is_added {
signals.push(format!(
"Python version requirement changed: {}",
content.trim()
));
}
}
_ => {}
}
// Cross-file: removed feature flags
if is_removed
&& name == "Cargo.toml"
&& content.trim_start().starts_with('[')
&& content.contains("features")
{
signals.push("Cargo.toml [features] section modified".to_string());
}
// Removed public exports
if is_removed {
let trimmed = content.trim();
if trimmed.starts_with("pub use ") || trimmed.starts_with("pub mod ") {
signals.push(format!("Removed public re-export: {}", trimmed));
}
if trimmed.starts_with("export {") || trimmed.starts_with("export default") {
signals.push(format!("Removed JS/TS export: {}", trimmed));
}
}
}
}
signals.dedup();
signals
}
/// Check if a file should have its content skipped (lock files, etc.)
fn should_skip_content(path: &std::path::Path) -> bool {
let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
SKIP_CONTENT_FILES.contains(&name)
}
/// Calculate adaptive per-file line budget based on file count and priority
fn calculate_file_budget(
file_count: usize,
category: FileCategory,
max_diff_lines: usize,
) -> usize {
// Weight by category: source gets more, config/lock gets less
let weight = match category {
FileCategory::Source => 3,
FileCategory::Test => 2,
FileCategory::Docs => 1,
FileCategory::Config => 1,
FileCategory::Build => 1,
FileCategory::Other => 1,
};
// Base budget per file, adjusted by count
let base_per_file = match file_count {
1 => max_diff_lines, // Single file gets full budget
2..=3 => max_diff_lines / 2, // 2-3 files: split evenly
4..=6 => max_diff_lines / file_count, // 4-6 files: proportional
_ => (max_diff_lines / file_count).max(30), // Many files: minimum 30 lines
};
// Apply category weight (source files get more)
(base_per_file * weight / 2).max(20)
}
/// Adaptive diff truncation: smarter budget allocation per file
fn truncate_diff_adaptive(
changes: &StagedChanges,
config: &Config,
char_budget: usize,
) -> String {
let mut output = String::with_capacity(char_budget);
let mut files_included = 0;
let total_files = changes.files.len();
let files = changes.files_by_priority();
// Count non-binary, non-skip files for budget calculation
let content_files: Vec<_> = files
.iter()
.filter(|f| !f.is_binary && !Self::should_skip_content(&f.path))
.collect();
for file in &files {
if file.is_binary {
continue;
}
// Check character budget
if output.len() >= char_budget {
break;
}
let header = format!("\n--- {} ---\n", file.path.display());
// Estimate if we have room for at least some content
if output.len() + header.len() + 50 > char_budget {
break;
}
output.push_str(&header);
files_included += 1;
// Skip content for lock files
if Self::should_skip_content(&file.path) {
output.push_str("(lock file - content skipped)\n");
continue;
}
// Calculate adaptive line budget for this file
let file_line_budget = Self::calculate_file_budget(
content_files.len(),
file.category,
config.max_diff_lines,
)
.min(config.max_file_lines);
let lines: Vec<_> = file.diff.lines().collect();
let take = lines.len().min(file_line_budget);
for line in &lines[..take] {
// Check char budget before each line
if output.len() + line.len() + 1 > char_budget {
output.push_str("... (budget exceeded)\n");
break;
}
output.push_str(line);
output.push('\n');
}
if lines.len() > take {
output.push_str(&format!("... ({} lines truncated)\n", lines.len() - take));
}
}
// Indicate if files were skipped
let skipped = total_files - files_included;
if skipped > 0 {
output.push_str(&format!(
"\n... ({} files not shown due to budget)\n",
skipped
));
}
output
}
}