Skip to main content

llm_git/
map_reduce.rs

1//! Map-reduce pattern for large diff analysis
2//!
3//! When diffs exceed the token threshold, this module splits analysis across
4//! files, then synthesizes results for accurate classification.
5
6use std::{borrow::Cow, cmp::Reverse, fmt::Write as _, path::Path};
7
8use futures::stream::{self, StreamExt};
9use serde::{Deserialize, Serialize};
10
11use crate::{
12   api::{OneShotSpec, run_oneshot, strict_json_schema},
13   config::CommitConfig,
14   diff::{FileDiff, parse_diff, reconstruct_diff},
15   error::{CommitGenError, Result},
16   templates,
17   tokens::TokenCounter,
18   types::ConventionalAnalysis,
19};
20
21/// Observation from a single file during map phase
22#[derive(Debug, Clone, Serialize, Deserialize)]
23pub struct FileObservation {
24   pub file:         String,
25   pub observations: Vec<String>,
26   pub additions:    usize,
27   pub deletions:    usize,
28}
29
30/// Maximum tokens per file in map phase (leave headroom for prompt template +
31/// context)
32const MAX_FILE_TOKENS: usize = 50_000;
33const MAP_PHASE_CONCURRENCY: usize = 16;
34
35const fn map_phase_model(config: &CommitConfig) -> &str {
36   config.summary_model.as_str()
37}
38
39fn build_file_batches(
40   files: &[FileDiff],
41   counter: &TokenCounter,
42   budget: usize,
43) -> Vec<Vec<usize>> {
44   build_file_batches_for_indices(files, 0..files.len(), counter, budget)
45}
46
47fn build_llm_file_batches(
48   files: &[FileDiff],
49   counter: &TokenCounter,
50   budget: usize,
51) -> Vec<Vec<usize>> {
52   if files.iter().all(|file| !file.is_binary) {
53      return build_file_batches(files, counter, budget);
54   }
55
56   build_file_batches_for_indices(
57      files,
58      files
59         .iter()
60         .enumerate()
61         .filter_map(|(idx, file)| (!file.is_binary).then_some(idx)),
62      counter,
63      budget,
64   )
65}
66
67fn build_file_batches_for_indices<I>(
68   files: &[FileDiff],
69   indices: I,
70   counter: &TokenCounter,
71   budget: usize,
72) -> Vec<Vec<usize>>
73where
74   I: IntoIterator<Item = usize>,
75{
76   let budget = budget.max(1);
77   let mut batches = Vec::new();
78   let mut current_batch = Vec::new();
79   let mut current_tokens = 0usize;
80
81   for idx in indices {
82      let file_tokens = files[idx].token_estimate(counter);
83      if file_tokens > budget {
84         if !current_batch.is_empty() {
85            batches.push(std::mem::take(&mut current_batch));
86            current_tokens = 0;
87         }
88         batches.push(vec![idx]);
89         continue;
90      }
91
92      if !current_batch.is_empty() && current_tokens.saturating_add(file_tokens) > budget {
93         batches.push(std::mem::take(&mut current_batch));
94         current_tokens = 0;
95      }
96
97      current_batch.push(idx);
98      current_tokens = current_tokens.saturating_add(file_tokens);
99   }
100
101   if !current_batch.is_empty() {
102      batches.push(current_batch);
103   }
104
105   batches
106}
107
108/// Check if map-reduce should be used.
109///
110/// Route only when the included diff is large enough to benefit from
111/// per-file analysis, or when a single included file would be truncated in the
112/// map phase.
113#[tracing::instrument(target = "lgit", name = "map_reduce.should_use", skip_all, fields(diff_bytes = diff.len(), threshold = config.map_reduce_threshold))]
114pub fn should_use_map_reduce(diff: &str, config: &CommitConfig, counter: &TokenCounter) -> bool {
115   if !config.map_reduce_enabled {
116      return false;
117   }
118
119   let files = parse_diff(diff);
120   let mut has_included_file = false;
121   let mut total_tokens = 0usize;
122
123   for file in files.iter().filter(|file| {
124      !config
125         .excluded_files
126         .iter()
127         .any(|excluded| file.filename.ends_with(excluded))
128   }) {
129      has_included_file = true;
130
131      let file_tokens = file.token_estimate(counter);
132      if file_tokens > MAX_FILE_TOKENS {
133         return true;
134      }
135
136      total_tokens = total_tokens.saturating_add(file_tokens);
137      if total_tokens >= config.map_reduce_threshold {
138         return true;
139      }
140   }
141
142   has_included_file && total_tokens >= config.map_reduce_threshold
143}
144
145/// Maximum files to include in context header (prevent token explosion)
146const MAX_CONTEXT_FILES: usize = 20;
147
148/// Precomputed context header metadata for cross-file awareness.
149struct ContextFile<'a> {
150   filename:     &'a str,
151   summary_line: String,
152   change_size:  usize,
153}
154
155struct ContextHeaders<'a> {
156   files:               Vec<ContextFile<'a>>,
157   ranked_indices:      Vec<usize>,
158   large_commit_header: Option<String>,
159}
160
161impl<'a> ContextHeaders<'a> {
162   fn new(files: &'a [FileDiff]) -> Self {
163      // Skip detailed context for very large commits (diminishing returns).
164      if files.len() > 100 {
165         return Self {
166            files:               Vec::new(),
167            ranked_indices:      Vec::new(),
168            large_commit_header: Some(format!("(Large commit with {} total files)", files.len())),
169         };
170      }
171
172      let files: Vec<_> = files
173         .iter()
174         .map(|file| {
175            let change_size = file.additions + file.deletions;
176            let description = infer_file_description(&file.filename, &file.content);
177            ContextFile {
178               filename: &file.filename,
179               summary_line: format!(
180                  "- {} ({} lines): {}",
181                  file.filename, change_size, description
182               ),
183               change_size,
184            }
185         })
186         .collect();
187
188      let mut ranked_indices = Vec::new();
189      if files.len() > MAX_CONTEXT_FILES {
190         ranked_indices = (0..files.len()).collect();
191         ranked_indices.sort_by_key(|&idx| Reverse(files[idx].change_size));
192      }
193
194      Self { files, ranked_indices, large_commit_header: None }
195   }
196
197   fn header_for_files(&self, current_files: &[&str]) -> Cow<'_, str> {
198      if let Some(header) = &self.large_commit_header {
199         return Cow::Borrowed(header.as_str());
200      }
201
202      let current_count = self
203         .files
204         .iter()
205         .filter(|file| is_current_context_file(file.filename, current_files))
206         .count();
207      let total_other = self.files.len().saturating_sub(current_count);
208
209      if total_other == 0 {
210         return Cow::Borrowed("");
211      }
212
213      let mut header = String::with_capacity(32 + total_other.min(MAX_CONTEXT_FILES) * 80);
214      header.push_str("OTHER FILES IN THIS CHANGE:");
215
216      let mut shown = 0usize;
217      if total_other > MAX_CONTEXT_FILES {
218         for &idx in &self.ranked_indices {
219            let file = &self.files[idx];
220            if is_current_context_file(file.filename, current_files) {
221               continue;
222            }
223
224            header.push('\n');
225            header.push_str(&file.summary_line);
226            shown += 1;
227
228            if shown == MAX_CONTEXT_FILES {
229               break;
230            }
231         }
232      } else {
233         for file in &self.files {
234            if is_current_context_file(file.filename, current_files) {
235               continue;
236            }
237
238            header.push('\n');
239            header.push_str(&file.summary_line);
240            shown += 1;
241         }
242      }
243
244      if shown < total_other {
245         write!(&mut header, "\n... and {} more files", total_other - shown)
246            .expect("writing to a string cannot fail");
247      }
248
249      Cow::Owned(header)
250   }
251}
252
253fn is_current_context_file(filename: &str, current_files: &[&str]) -> bool {
254   current_files.contains(&filename)
255}
256
257/// Infer a brief description of what a file likely contains based on
258/// name/content
259fn infer_file_description(filename: &str, content: &str) -> &'static str {
260   let filename_lower = filename.to_lowercase();
261
262   // Check filename patterns
263   if filename_lower.contains("test") {
264      return "test file";
265   }
266   if filename_lower.contains("prompt") || filename_lower.contains("system") {
267      return "prompt template";
268   }
269   if Path::new(filename)
270      .extension()
271      .is_some_and(|e| e.eq_ignore_ascii_case("md"))
272   {
273      return "documentation";
274   }
275   let ext = Path::new(filename).extension();
276   if filename_lower.contains("config")
277      || ext.is_some_and(|e| e.eq_ignore_ascii_case("toml"))
278      || ext.is_some_and(|e| e.eq_ignore_ascii_case("yaml"))
279      || ext.is_some_and(|e| e.eq_ignore_ascii_case("yml"))
280   {
281      return "configuration";
282   }
283   if filename_lower.contains("error") {
284      return "error definitions";
285   }
286   if filename_lower.contains("type") {
287      return "type definitions";
288   }
289   if filename_lower.ends_with("mod.rs") || filename_lower.ends_with("lib.rs") {
290      return "module exports";
291   }
292   if filename_lower.ends_with("main.rs")
293      || filename_lower.ends_with("main.go")
294      || filename_lower.ends_with("main.py")
295   {
296      return "entry point";
297   }
298
299   // Check content patterns
300   if content.contains("impl ") || content.contains("fn ") {
301      return "implementation";
302   }
303   if content.contains("struct ") || content.contains("enum ") {
304      return "type definitions";
305   }
306   if content.contains("async ") || content.contains("await") {
307      return "async code";
308   }
309
310   "source code"
311}
312
313/// Map phase: analyze token-budgeted file batches and extract observations
314#[tracing::instrument(target = "lgit", name = "map_reduce.map_phase", skip_all, fields(file_count = files.len(), model = map_model_name))]
315async fn map_phase(
316   files: &[FileDiff],
317   map_model_name: &str,
318   config: &CommitConfig,
319   counter: &TokenCounter,
320) -> Result<Vec<FileObservation>> {
321   let context_headers = ContextHeaders::new(files);
322   let llm_batches = build_llm_file_batches(files, counter, config.map_batch_token_budget);
323   let total_batches = llm_batches.len();
324
325   let mut observations_by_index = vec![None; files.len()];
326   for (idx, file) in files.iter().enumerate().filter(|(_, file)| file.is_binary) {
327      observations_by_index[idx] = Some(FileObservation {
328         file:         file.filename.clone(),
329         observations: vec!["Binary file changed.".to_string()],
330         additions:    0,
331         deletions:    0,
332      });
333   }
334
335   let batch_results: Vec<Result<Vec<(usize, FileObservation)>>> =
336      stream::iter(llm_batches.into_iter().enumerate())
337         .map(|(batch_idx, batch_indices)| {
338            let context_headers = &context_headers;
339            async move {
340               let batch_files: Vec<&FileDiff> =
341                  batch_indices.iter().map(|&idx| &files[idx]).collect();
342               let current_paths: Vec<&str> = batch_files
343                  .iter()
344                  .map(|file| file.filename.as_str())
345                  .collect();
346               let context_header = context_headers.header_for_files(&current_paths);
347               let progress_label = format!(
348                  "map batch {}/{} ({} files)",
349                  batch_idx + 1,
350                  total_batches,
351                  batch_files.len()
352               );
353               let observations = map_file_batch(
354                  &batch_files,
355                  &context_header,
356                  map_model_name,
357                  config,
358                  counter,
359                  &progress_label,
360               )
361               .await?;
362
363               Ok(batch_indices.into_iter().zip(observations).collect())
364            }
365         })
366         .buffer_unordered(MAP_PHASE_CONCURRENCY)
367         .collect()
368         .await;
369
370   for result in batch_results {
371      for (idx, observation) in result? {
372         observations_by_index[idx] = Some(observation);
373      }
374   }
375
376   let mut observations = Vec::with_capacity(files.len());
377   for (idx, observation) in observations_by_index.into_iter().enumerate() {
378      let observation = observation.ok_or_else(|| {
379         CommitGenError::Other(format!("Missing map observation for {}", files[idx].filename))
380      })?;
381      observations.push(observation);
382   }
383
384   Ok(observations)
385}
386
387#[tracing::instrument(target = "lgit", name = "map_reduce.observe_diff_files", skip_all, fields(diff_bytes = diff.len(), model = map_model_name))]
388pub async fn observe_diff_files(
389   diff: &str,
390   map_model_name: &str,
391   config: &CommitConfig,
392   counter: &TokenCounter,
393) -> Result<Vec<FileObservation>> {
394   let mut files = parse_diff(diff);
395
396   files.retain(|file| {
397      !config
398         .excluded_files
399         .iter()
400         .any(|excluded| file.filename.ends_with(excluded))
401   });
402
403   if files.is_empty() {
404      return Err(CommitGenError::Other(
405         "No relevant files to summarize after filtering".to_string(),
406      ));
407   }
408
409   let llm_file_count = files.iter().filter(|file| !file.is_binary).count();
410   let batch_count = build_llm_file_batches(&files, counter, config.map_batch_token_budget).len();
411   crate::api::print_llm_progress(|| {
412      format!(
413         "Map-reduce map phase: {batch_count} batch LLM queries for {llm_file_count} files queued \
414          on {map_model_name} (max {MAP_PHASE_CONCURRENCY} parallel)"
415      )
416   });
417
418   map_phase(&files, map_model_name, config, counter).await
419}
420
421/// Analyze a token-budgeted file batch and extract per-file observations
422#[tracing::instrument(target = "lgit", name = "map_reduce.map_file_batch", skip_all, fields(file_count = files.len(), model = model_name))]
423async fn map_file_batch(
424   files: &[&FileDiff],
425   context_header: &str,
426   model_name: &str,
427   config: &CommitConfig,
428   counter: &TokenCounter,
429   progress_label: &str,
430) -> Result<Vec<FileObservation>> {
431   let rendered_diffs: Vec<String> = files
432      .iter()
433      .map(|file| render_file_diff_for_batch(file, counter))
434      .collect();
435   let prompt_files: Vec<templates::MapFile<'_>> = files
436      .iter()
437      .zip(&rendered_diffs)
438      .map(|(file, diff)| templates::MapFile { path: file.filename.as_str(), diff })
439      .collect();
440   let variant = if config.markdown_output { "markdown" } else { "default" };
441   let parts = templates::render_map_prompt(variant, &prompt_files, context_header)?;
442   let observation_schema = build_batch_observation_schema();
443   let response = run_oneshot::<BatchObservationResponse>(config, &OneShotSpec {
444      operation: "map-reduce/map",
445      model: model_name,
446      prompt_family: "map",
447      prompt_variant: variant,
448      system_prompt: &parts.system,
449      user_prompt: &parts.user,
450      tool_name: "create_file_observations",
451      tool_description: "Extract observations from a batch of file changes",
452      schema: &observation_schema,
453      progress_label: Some(progress_label),
454      debug: None,
455      cacheable: true,
456   })
457   .await?;
458
459   Ok(map_batch_response_to_observations(
460      files,
461      &response.output,
462      response.text_content.as_deref(),
463      response.stop_reason.as_deref(),
464   ))
465}
466
467fn render_file_diff_for_batch(file: &FileDiff, counter: &TokenCounter) -> String {
468   let file_tokens = file.token_estimate(counter);
469   if file_tokens > MAX_FILE_TOKENS {
470      let mut file_clone = file.clone();
471      let target_size = MAX_FILE_TOKENS * 4; // Convert tokens to chars
472      file_clone.truncate(target_size);
473      eprintln!(
474         "  {} truncated {} ({} \u{2192} {} tokens)",
475         crate::style::icons::WARNING,
476         file.filename,
477         file_tokens,
478         file_clone.token_estimate(counter)
479      );
480      return reconstruct_diff(&[file_clone]);
481   }
482
483   reconstruct_single_file_diff(file)
484}
485
486fn reconstruct_single_file_diff(file: &FileDiff) -> String {
487   let mut diff = String::with_capacity(file.size());
488   diff.push_str(&file.header);
489   if !file.content.is_empty() {
490      diff.push('\n');
491      diff.push_str(&file.content);
492   }
493   diff
494}
495
496fn map_batch_response_to_observations(
497   files: &[&FileDiff],
498   response: &BatchObservationResponse,
499   text_content: Option<&str>,
500   stop_reason: Option<&str>,
501) -> Vec<FileObservation> {
502   if response.files.is_empty() && text_content.is_some_and(|text| !text.trim().is_empty()) {
503      crate::style::warn(
504         "Model returned batch observations as text; using fallback observations for every file.",
505      );
506      return files
507         .iter()
508         .map(|file| fallback_file_observation(file))
509         .collect();
510   }
511
512   let stopped_at_max_tokens = stop_reason == Some("max_tokens");
513   let mut used_entries = vec![false; response.files.len()];
514   files
515      .iter()
516      .map(|file| {
517         let Some(entry_idx) =
518            find_observation_entry(file.filename.as_str(), &response.files, &used_entries, files)
519         else {
520            return fallback_file_observation(file);
521         };
522
523         used_entries[entry_idx] = true;
524         let entry = &response.files[entry_idx];
525         let observations = if entry.observations.is_empty() && stopped_at_max_tokens {
526            vec![fallback_observation_text(&file.filename)]
527         } else {
528            entry.observations.clone()
529         };
530
531         FileObservation { file: file.filename.clone(), observations, additions: 0, deletions: 0 }
532      })
533      .collect()
534}
535
536fn find_observation_entry(
537   filename: &str,
538   entries: &[FileObservationEntry],
539   used_entries: &[bool],
540   batch_files: &[&FileDiff],
541) -> Option<usize> {
542   find_entry_by(entries, used_entries, |entry| entry.path == filename)
543      .or_else(|| {
544         let filename_basename = path_basename(filename);
545         let basename_is_unique = batch_files
546            .iter()
547            .filter(|file| path_basename(file.filename.as_str()) == filename_basename)
548            .count()
549            == 1;
550         basename_is_unique
551            .then(|| {
552               find_entry_by(entries, used_entries, |entry| {
553                  path_basename(&entry.path) == filename_basename
554               })
555            })
556            .flatten()
557      })
558      .or_else(|| {
559         find_entry_by(entries, used_entries, |entry| path_suffix_matches(&entry.path, filename))
560      })
561}
562
563fn find_entry_by<F>(
564   entries: &[FileObservationEntry],
565   used_entries: &[bool],
566   mut matches: F,
567) -> Option<usize>
568where
569   F: FnMut(&FileObservationEntry) -> bool,
570{
571   entries
572      .iter()
573      .enumerate()
574      .find_map(|(idx, entry)| (!used_entries[idx] && matches(entry)).then_some(idx))
575}
576
577fn path_basename(path: &str) -> &str {
578   Path::new(path)
579      .file_name()
580      .and_then(|name| name.to_str())
581      .unwrap_or(path)
582}
583
584fn path_suffix_matches(left: &str, right: &str) -> bool {
585   path_has_suffix(left, right) || path_has_suffix(right, left)
586}
587
588fn path_has_suffix(path: &str, suffix: &str) -> bool {
589   if path == suffix {
590      return true;
591   }
592
593   path
594      .strip_suffix(suffix)
595      .is_some_and(|prefix| prefix.ends_with('/') || prefix.ends_with('\\'))
596}
597
598fn fallback_file_observation(file: &FileDiff) -> FileObservation {
599   FileObservation {
600      file:         file.filename.clone(),
601      observations: vec![fallback_observation_text(&file.filename)],
602      additions:    0,
603      deletions:    0,
604   }
605}
606
607fn fallback_observation_text(filename: &str) -> String {
608   let fallback_target = path_basename(filename);
609   format!("Updated {fallback_target}.")
610}
611
612/// Reduce phase: synthesize all observations into final analysis
613#[tracing::instrument(target = "lgit", name = "map_reduce.reduce_phase", skip_all, fields(observation_count = observations.len(), model = model_name))]
614pub async fn reduce_phase(
615   observations: &[FileObservation],
616   stat: &str,
617   scope_candidates: &str,
618   model_name: &str,
619   config: &CommitConfig,
620) -> Result<ConventionalAnalysis> {
621   let type_enum: Vec<&str> = config.types.keys().map(|s| s.as_str()).collect();
622   let observations_json =
623      serde_json::to_string_pretty(observations).unwrap_or_else(|_| "[]".to_string());
624
625   let types_description = crate::api::format_types_description(config);
626   let variant = if config.markdown_output { "markdown" } else { "default" };
627   let parts = templates::render_reduce_prompt(
628      variant,
629      &observations_json,
630      stat,
631      scope_candidates,
632      Some(&types_description),
633   )?;
634
635   let analysis_schema = build_analysis_schema(&type_enum, config);
636   let response = run_oneshot::<ConventionalAnalysis>(config, &OneShotSpec {
637      operation:        "map-reduce/reduce",
638      model:            model_name,
639      prompt_family:    "reduce",
640      prompt_variant:   variant,
641      system_prompt:    &parts.system,
642      user_prompt:      &parts.user,
643      tool_name:        "create_conventional_analysis",
644      tool_description: "Analyze changes and classify as conventional commit with type, scope, \
645                         summary, details, and metadata",
646      schema:           &analysis_schema,
647      progress_label:   Some("reduce file observations"),
648      debug:            None,
649      cacheable:        true,
650   })
651   .await?;
652
653   Ok(response.output)
654}
655
656/// Run full map-reduce pipeline for large diffs
657#[tracing::instrument(target = "lgit", name = "map_reduce.run", skip_all, fields(diff_bytes = diff.len(), model = model_name))]
658pub async fn run_map_reduce(
659   diff: &str,
660   stat: &str,
661   scope_candidates: &str,
662   model_name: &str,
663   config: &CommitConfig,
664   counter: &TokenCounter,
665) -> Result<ConventionalAnalysis> {
666   let map_model_name = map_phase_model(config);
667   let observations = observe_diff_files(diff, map_model_name, config, counter).await?;
668   let file_count = observations.len();
669   crate::api::print_llm_progress(|| {
670      format!("Map-reduce reduce phase: synthesizing {file_count} file observations")
671   });
672
673   reduce_phase(&observations, stat, scope_candidates, model_name, config).await
674}
675
676#[derive(Debug, Deserialize, Serialize)]
677struct BatchObservationResponse {
678   #[serde(default)]
679   files: Vec<FileObservationEntry>,
680}
681
682#[derive(Debug, Deserialize, Serialize)]
683struct FileObservationEntry {
684   path:         String,
685   #[serde(default, deserialize_with = "deserialize_observations")]
686   observations: Vec<String>,
687}
688
689/// Deserialize observations flexibly: handles array, stringified array, or
690/// bullet string
691fn deserialize_observations<'de, D>(deserializer: D) -> std::result::Result<Vec<String>, D::Error>
692where
693   D: serde::Deserializer<'de>,
694{
695   use std::fmt;
696
697   use serde::de::{self, Visitor};
698
699   struct ObservationsVisitor;
700
701   impl<'de> Visitor<'de> for ObservationsVisitor {
702      type Value = Vec<String>;
703
704      fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
705         formatter.write_str("an array of strings, a JSON array string, or a bullet-point string")
706      }
707
708      fn visit_seq<A>(self, mut seq: A) -> std::result::Result<Self::Value, A::Error>
709      where
710         A: de::SeqAccess<'de>,
711      {
712         let mut vec = Vec::new();
713         while let Some(item) = seq.next_element::<String>()? {
714            vec.push(item);
715         }
716         Ok(vec)
717      }
718
719      fn visit_str<E>(self, s: &str) -> std::result::Result<Self::Value, E>
720      where
721         E: de::Error,
722      {
723         Ok(parse_string_to_observations(s))
724      }
725   }
726
727   deserializer.deserialize_any(ObservationsVisitor)
728}
729
730/// Parse a string into observations: handles JSON array string or bullet-point
731/// string
732fn parse_string_to_observations(s: &str) -> Vec<String> {
733   let trimmed = s.trim();
734   if trimmed.is_empty() {
735      return Vec::new();
736   }
737
738   // Try parsing as JSON array first
739   if trimmed.starts_with('[')
740      && let Ok(arr) = serde_json::from_str::<Vec<String>>(trimmed)
741   {
742      return arr;
743   }
744
745   // Fall back to bullet-point parsing
746   trimmed
747      .lines()
748      .map(str::trim)
749      .filter(|line| !line.is_empty())
750      .map(|line| {
751         line
752            .strip_prefix("- ")
753            .or_else(|| line.strip_prefix("* "))
754            .or_else(|| line.strip_prefix("• "))
755            .unwrap_or(line)
756            .trim()
757            .to_string()
758      })
759      .filter(|line| !line.is_empty())
760      .collect()
761}
762
763fn build_batch_observation_schema() -> serde_json::Value {
764   strict_json_schema(
765      serde_json::json!({
766         "files": {
767            "type": "array",
768            "description": "Per-file observations for every file in the map batch.",
769            "items": {
770               "type": "object",
771               "properties": {
772                  "path": {
773                     "type": "string",
774                     "description": "The exact input file path this observation set describes."
775                  },
776                  "observations": {
777                     "type": "array",
778                     "description": "Factual observations about what changed in this file.",
779                     "items": {
780                        "type": "string"
781                     }
782                  }
783               },
784               "required": ["path", "observations"],
785               "additionalProperties": false
786            }
787         }
788      }),
789      &["files"],
790   )
791}
792
793fn build_analysis_schema(type_enum: &[&str], config: &CommitConfig) -> serde_json::Value {
794   strict_json_schema(
795      serde_json::json!({
796         "type": {
797            "type": "string",
798            "enum": type_enum,
799            "description": "Commit type based on combined changes"
800         },
801         "scope": {
802            "type": "string",
803            "description": "Optional scope (module/component). Omit if unclear or multi-component."
804         },
805         "summary": {
806            "type": "string",
807            "description": format!(
808               "Concise past-tense commit summary without type/scope prefix or trailing period; target {} chars, hard limit {}.",
809               config.summary_guideline,
810               config.summary_hard_limit
811            ),
812            "maxLength": config.summary_hard_limit
813         },
814         "details": {
815            "type": "array",
816            "description": "Array of 0-6 detail items with changelog metadata.",
817            "items": {
818               "type": "object",
819               "properties": {
820                  "text": {
821                     "type": "string",
822                     "description": "Detail about change, starting with past-tense verb, ending with period"
823                  },
824                  "changelog_category": {
825                     "type": "string",
826                     "enum": ["Added", "Changed", "Fixed", "Deprecated", "Removed", "Security"],
827                     "description": "Changelog category if user-visible. Omit for internal changes."
828                  },
829                  "user_visible": {
830                     "type": "boolean",
831                     "description": "True if this change affects users/API and should appear in changelog"
832                  }
833               },
834               "required": ["text", "user_visible"]
835            }
836         },
837         "issue_refs": {
838            "type": "array",
839            "description": "Issue numbers from context (e.g., ['#123', '#456']). Empty if none.",
840            "items": {
841               "type": "string"
842            }
843         }
844      }),
845      &["type", "details", "issue_refs"],
846   )
847}
848
849#[cfg(test)]
850mod tests {
851   use super::*;
852   use crate::tokens::TokenCounter;
853
854   fn test_counter() -> TokenCounter {
855      TokenCounter::new("http://localhost:4000", None, "claude-sonnet-4.5")
856   }
857
858   fn file_with_tokens(filename: &str, token_estimate: usize) -> FileDiff {
859      FileDiff {
860         filename:  filename.to_string(),
861         header:    String::new(),
862         content:   "x".repeat(token_estimate * 4),
863         additions: 0,
864         deletions: 0,
865         is_binary: false,
866      }
867   }
868
869   #[test]
870   fn test_map_phase_model_uses_summary_model() {
871      let config = CommitConfig {
872         summary_model: "claude-haiku-4-5".to_string(),
873         analysis_model: "claude-opus-4.1".to_string(),
874         ..Default::default()
875      };
876
877      assert_eq!(map_phase_model(&config), "claude-haiku-4-5");
878      assert_eq!(MAP_PHASE_CONCURRENCY, 16);
879   }
880
881   #[test]
882   fn test_build_file_batches_single_batch_when_under_budget() {
883      let counter = test_counter();
884      let files = vec![
885         file_with_tokens("a.rs", 4),
886         file_with_tokens("b.rs", 4),
887         file_with_tokens("c.rs", 1),
888      ];
889
890      assert_eq!(build_file_batches(&files, &counter, 10), vec![vec![0, 1, 2]]);
891   }
892
893   #[test]
894   fn test_build_file_batches_splits_when_budget_exceeded() {
895      let counter = test_counter();
896      let files = vec![
897         file_with_tokens("a.rs", 4),
898         file_with_tokens("b.rs", 4),
899         file_with_tokens("c.rs", 4),
900      ];
901
902      assert_eq!(build_file_batches(&files, &counter, 10), vec![vec![0, 1], vec![2]]);
903   }
904
905   #[test]
906   fn test_build_file_batches_preserves_order_and_every_file_once() {
907      let counter = test_counter();
908      let files = vec![
909         file_with_tokens("a.rs", 3),
910         file_with_tokens("b.rs", 8),
911         file_with_tokens("c.rs", 2),
912         file_with_tokens("d.rs", 9),
913         file_with_tokens("e.rs", 1),
914      ];
915
916      let batches = build_file_batches(&files, &counter, 10);
917      let flattened: Vec<usize> = batches.into_iter().flatten().collect();
918      assert_eq!(flattened, vec![0, 1, 2, 3, 4]);
919   }
920
921   #[test]
922   fn test_build_file_batches_isolates_oversized_files() {
923      let counter = test_counter();
924      let files = vec![
925         file_with_tokens("a.rs", 2),
926         file_with_tokens("b.rs", 2),
927         file_with_tokens("huge.rs", 12),
928         file_with_tokens("c.rs", 2),
929      ];
930
931      assert_eq!(build_file_batches(&files, &counter, 10), vec![vec![0, 1], vec![2], vec![3]]);
932   }
933
934   #[test]
935   fn test_batch_response_mapping_matches_paths_and_falls_back_for_omissions() {
936      let exact = file_with_tokens("src/lib.rs", 1);
937      let basename = file_with_tokens("src/main.rs", 1);
938      let omitted = file_with_tokens("crates/core/mod.rs", 1);
939      let files = [&exact, &basename, &omitted];
940      let response = BatchObservationResponse {
941         files: vec![
942            FileObservationEntry {
943               path:         "src/lib.rs".to_string(),
944               observations: vec!["updated library entrypoint".to_string()],
945            },
946            FileObservationEntry {
947               path:         "main.rs".to_string(),
948               observations: vec!["changed CLI wiring".to_string()],
949            },
950         ],
951      };
952
953      let result = map_batch_response_to_observations(&files, &response, None, None);
954
955      assert_eq!(result[0].file, "src/lib.rs");
956      assert_eq!(result[0].observations, vec!["updated library entrypoint".to_string()]);
957      assert_eq!(result[1].file, "src/main.rs");
958      assert_eq!(result[1].observations, vec!["changed CLI wiring".to_string()]);
959      assert_eq!(result[2].file, "crates/core/mod.rs");
960      assert_eq!(result[2].observations, vec!["Updated mod.rs.".to_string()]);
961   }
962
963   #[test]
964   fn test_batch_response_mapping_falls_back_for_text_only_response() {
965      let first = file_with_tokens("src/lib.rs", 1);
966      let second = file_with_tokens("src/main.rs", 1);
967      let files = [&first, &second];
968      let response = BatchObservationResponse { files: Vec::new() };
969
970      let result = map_batch_response_to_observations(
971         &files,
972         &response,
973         Some("- unstructured observation"),
974         None,
975      );
976
977      assert_eq!(result[0].observations, vec!["Updated lib.rs.".to_string()]);
978      assert_eq!(result[1].observations, vec!["Updated main.rs.".to_string()]);
979   }
980
981   #[test]
982   fn test_should_use_map_reduce_disabled() {
983      let config = CommitConfig { map_reduce_enabled: false, ..Default::default() };
984      let counter = test_counter();
985      // Even with many files, disabled means no map-reduce
986      let diff = r"diff --git a/a.rs b/a.rs
987@@ -0,0 +1 @@
988+a
989diff --git a/b.rs b/b.rs
990@@ -0,0 +1 @@
991+b
992diff --git a/c.rs b/c.rs
993@@ -0,0 +1 @@
994+c
995diff --git a/d.rs b/d.rs
996@@ -0,0 +1 @@
997+d";
998      assert!(!should_use_map_reduce(diff, &config, &counter));
999   }
1000
1001   #[test]
1002   fn test_should_use_map_reduce_few_files() {
1003      let config = CommitConfig::default();
1004      let counter = test_counter();
1005      // Only 2 files - below threshold
1006      let diff = r"diff --git a/a.rs b/a.rs
1007@@ -0,0 +1 @@
1008+a
1009diff --git a/b.rs b/b.rs
1010@@ -0,0 +1 @@
1011+b";
1012      assert!(!should_use_map_reduce(diff, &config, &counter));
1013   }
1014
1015   #[test]
1016   fn test_should_use_map_reduce_many_tiny_files_below_threshold() {
1017      let config = CommitConfig { map_reduce_threshold: 1_000, ..Default::default() };
1018      let counter = test_counter();
1019      let diff = r"diff --git a/a.rs b/a.rs
1020@@ -0,0 +1 @@
1021+a
1022diff --git a/b.rs b/b.rs
1023@@ -0,0 +1 @@
1024+b
1025diff --git a/c.rs b/c.rs
1026@@ -0,0 +1 @@
1027+c
1028diff --git a/d.rs b/d.rs
1029@@ -0,0 +1 @@
1030+d
1031diff --git a/e.rs b/e.rs
1032@@ -0,0 +1 @@
1033+e";
1034      assert!(!should_use_map_reduce(diff, &config, &counter));
1035   }
1036
1037   #[test]
1038   fn test_should_use_map_reduce_large_total_diff() {
1039      let config = CommitConfig { map_reduce_threshold: 20, ..Default::default() };
1040      let counter = test_counter();
1041      let payload = "a".repeat(200);
1042      let diff = format!("diff --git a/a.rs b/a.rs\n@@ -0,0 +1 @@\n+{payload}");
1043
1044      assert!(should_use_map_reduce(&diff, &config, &counter));
1045   }
1046
1047   #[test]
1048   fn test_should_use_map_reduce_single_oversized_file() {
1049      let config = CommitConfig { map_reduce_threshold: usize::MAX, ..Default::default() };
1050      let counter = test_counter();
1051      let payload = "a".repeat((MAX_FILE_TOKENS + 1) * 4);
1052      let diff = format!("diff --git a/a.rs b/a.rs\n@@ -0,0 +1 @@\n+{payload}");
1053
1054      assert!(should_use_map_reduce(&diff, &config, &counter));
1055   }
1056
1057   #[test]
1058   fn test_generate_context_header_empty() {
1059      let files = vec![FileDiff {
1060         filename:  "only.rs".to_string(),
1061         header:    String::new(),
1062         content:   String::new(),
1063         additions: 10,
1064         deletions: 5,
1065         is_binary: false,
1066      }];
1067      let context_headers = ContextHeaders::new(&files);
1068      let header = context_headers.header_for_files(&["only.rs"]);
1069      assert!(header.is_empty());
1070   }
1071
1072   #[test]
1073   fn test_generate_context_header_multiple() {
1074      let files = vec![
1075         FileDiff {
1076            filename:  "src/main.rs".to_string(),
1077            header:    String::new(),
1078            content:   "fn main() {}".to_string(),
1079            additions: 10,
1080            deletions: 5,
1081            is_binary: false,
1082         },
1083         FileDiff {
1084            filename:  "src/lib.rs".to_string(),
1085            header:    String::new(),
1086            content:   "mod test;".to_string(),
1087            additions: 3,
1088            deletions: 1,
1089            is_binary: false,
1090         },
1091         FileDiff {
1092            filename:  "tests/test.rs".to_string(),
1093            header:    String::new(),
1094            content:   "#[test]".to_string(),
1095            additions: 20,
1096            deletions: 0,
1097            is_binary: false,
1098         },
1099      ];
1100
1101      let context_headers = ContextHeaders::new(&files);
1102      let header = context_headers.header_for_files(&["src/main.rs"]);
1103      assert!(header.contains("OTHER FILES IN THIS CHANGE:"));
1104      assert!(header.contains("src/lib.rs"));
1105      assert!(header.contains("tests/test.rs"));
1106      assert!(!header.contains("src/main.rs")); // Current file excluded
1107   }
1108
1109   #[test]
1110   fn test_infer_file_description() {
1111      assert_eq!(infer_file_description("src/test_utils.rs", ""), "test file");
1112      assert_eq!(infer_file_description("README.md", ""), "documentation");
1113      assert_eq!(infer_file_description("prompts/analysis/default.md", ""), "prompt template");
1114      assert_eq!(infer_file_description("system/analysis/default.md", ""), "prompt template");
1115      assert_eq!(infer_file_description("config.toml", ""), "configuration");
1116      assert_eq!(infer_file_description("src/error.rs", ""), "error definitions");
1117      assert_eq!(infer_file_description("src/types.rs", ""), "type definitions");
1118      assert_eq!(infer_file_description("src/mod.rs", ""), "module exports");
1119      assert_eq!(infer_file_description("src/main.rs", ""), "entry point");
1120      assert_eq!(infer_file_description("src/api.rs", "fn call()"), "implementation");
1121      assert_eq!(infer_file_description("src/models.rs", "struct Foo"), "type definitions");
1122      assert_eq!(infer_file_description("src/unknown.xyz", ""), "source code");
1123   }
1124
1125   #[test]
1126   fn test_parse_string_to_observations_json_array() {
1127      let input = r#"["item one", "item two", "item three"]"#;
1128      let result = parse_string_to_observations(input);
1129      assert_eq!(result, vec!["item one", "item two", "item three"]);
1130   }
1131
1132   #[test]
1133   fn test_parse_string_to_observations_bullet_points() {
1134      let input = "- added new function\n- fixed bug in parser\n- updated tests";
1135      let result = parse_string_to_observations(input);
1136      assert_eq!(result, vec!["added new function", "fixed bug in parser", "updated tests"]);
1137   }
1138
1139   #[test]
1140   fn test_parse_string_to_observations_asterisk_bullets() {
1141      let input = "* first change\n* second change";
1142      let result = parse_string_to_observations(input);
1143      assert_eq!(result, vec!["first change", "second change"]);
1144   }
1145
1146   #[test]
1147   fn test_parse_string_to_observations_empty() {
1148      assert!(parse_string_to_observations("").is_empty());
1149      assert!(parse_string_to_observations("   ").is_empty());
1150   }
1151
1152   #[test]
1153   fn test_deserialize_observations_array() {
1154      let json = r#"{"path": "src/lib.rs", "observations": ["a", "b", "c"]}"#;
1155      let result: FileObservationEntry =
1156         serde_json::from_str(json).expect("valid observation array JSON should deserialize");
1157      assert_eq!(result.path, "src/lib.rs");
1158      assert_eq!(result.observations, vec!["a", "b", "c"]);
1159   }
1160
1161   #[test]
1162   fn test_deserialize_observations_stringified_array() {
1163      let json = r#"{"path": "src/lib.rs", "observations": "[\"a\", \"b\", \"c\"]"}"#;
1164      let result: FileObservationEntry = serde_json::from_str(json)
1165         .expect("valid stringified observation array JSON should deserialize");
1166      assert_eq!(result.path, "src/lib.rs");
1167      assert_eq!(result.observations, vec!["a", "b", "c"]);
1168   }
1169
1170   #[test]
1171   fn test_deserialize_observations_bullet_string() {
1172      let json = r#"{"path": "src/lib.rs", "observations": "- updated function\n- fixed bug"}"#;
1173      let result: FileObservationEntry =
1174         serde_json::from_str(json).expect("valid bullet observation JSON should deserialize");
1175      assert_eq!(result.path, "src/lib.rs");
1176      assert_eq!(result.observations, vec!["updated function", "fixed bug"]);
1177   }
1178}