gitai/features/commit/
completion.rs

1#![allow(clippy::cast_possible_truncation)]
2#![allow(clippy::as_conversions)]
3
4use super::prompt::{create_completion_system_prompt, create_completion_user_prompt};
5use super::types::GeneratedMessage;
6use crate::config::Config;
7use crate::core::context::CommitContext;
8use crate::core::llm;
9use crate::core::token_optimizer::TokenOptimizer;
10use crate::git::{CommitResult, GitRepo};
11
12use anyhow::Result;
13use log::debug;
14use std::path::Path;
15use std::sync::Arc;
16use tokio::sync::{RwLock, mpsc};
17
18/// Service for handling Git commit message completion with AI assistance
19pub struct CompletionService {
20    config: Config,
21    repo: Arc<GitRepo>,
22    provider_name: String,
23    verify: bool,
24    cached_context: Arc<RwLock<Option<CommitContext>>>,
25}
26
27impl CompletionService {
28    /// Create a new `CompletionService` instance
29    ///
30    /// # Arguments
31    ///
32    /// * `config` - The configuration for the service
33    /// * `repo_path` - The path to the Git repository (unused but kept for API compatibility)
34    /// * `provider_name` - The name of the LLM provider to use
35    /// * `verify` - Whether to verify commits
36    /// * `git_repo` - An existing `GitRepo` instance
37    ///
38    /// # Returns
39    ///
40    /// A Result containing the new `CompletionService` instance or an error
41    pub fn new(
42        config: Config,
43        _repo_path: &Path,
44        provider_name: &str,
45        verify: bool,
46        git_repo: GitRepo,
47    ) -> Result<Self> {
48        Ok(Self {
49            config,
50            repo: Arc::new(git_repo),
51            provider_name: provider_name.to_string(),
52            verify,
53            cached_context: Arc::new(RwLock::new(None)),
54        })
55    }
56
57    /// Check if the repository is remote
58    pub fn is_remote_repository(&self) -> bool {
59        self.repo.is_remote()
60    }
61
62    /// Check the environment for necessary prerequisites
63    pub fn check_environment(&self) -> Result<()> {
64        self.config.check_environment()
65    }
66
67    /// Get Git information for the current repository
68    pub async fn get_git_info(&self) -> Result<CommitContext> {
69        {
70            let cached_context = self.cached_context.read().await;
71            if let Some(context) = &*cached_context {
72                return Ok(context.clone());
73            }
74        }
75
76        let context = self.repo.get_git_info(&self.config).await?;
77
78        {
79            let mut cached_context = self.cached_context.write().await;
80            *cached_context = Some(context.clone());
81        }
82        Ok(context)
83    }
84
85    /// Generate a commit message completion using AI
86    ///
87    /// # Arguments
88    ///
89    /// * `prefix` - The prefix text to complete
90    /// * `context_ratio` - The ratio of the original message to use as context (0.0 to 1.0)
91    ///
92    /// # Returns
93    ///
94    /// A Result containing the generated completion or an error
95    pub async fn complete_message(
96        &self,
97        prefix: &str,
98        context_ratio: f32,
99    ) -> anyhow::Result<GeneratedMessage> {
100        let mut config_clone = self.config.clone();
101
102        // Set instructions to include completion context
103        let completion_instructions = format!(
104            "Complete the commit message starting with the prefix: '{}'. Use {}% of the original message as context.",
105            prefix,
106            (context_ratio * 100.0) as i32
107        );
108        config_clone.instructions = completion_instructions;
109
110        let mut context = self.get_git_info().await?;
111
112        // Enhance context with semantically similar history
113        context.author_history = context.get_enhanced_history(10);
114
115        // Create system prompt for completion
116        let system_prompt = create_completion_system_prompt(&config_clone)?;
117
118        // Use the shared optimization logic
119        let (_, final_user_prompt) = self
120            .optimize_prompt(&config_clone, &system_prompt, context, |ctx| {
121                create_completion_user_prompt(ctx, prefix, context_ratio)
122            })
123            .await;
124
125        let generated_message = llm::get_message::<GeneratedMessage>(
126            &config_clone,
127            &self.provider_name,
128            &system_prompt,
129            &final_user_prompt,
130        )
131        .await?;
132
133        Ok(generated_message)
134    }
135
136    /// Private helper method to handle common token optimization logic
137    ///
138    /// # Arguments
139    ///
140    /// * `config_clone` - Configuration with preset and instructions
141    /// * `system_prompt` - The system prompt to use
142    /// * `context` - The commit context
143    /// * `create_user_prompt_fn` - A function that creates a user prompt from a context
144    ///
145    /// # Returns
146    ///
147    /// A tuple containing the optimized context and final user prompt
148    async fn optimize_prompt<F>(
149        &self,
150        config_clone: &Config,
151        system_prompt: &str,
152        mut context: CommitContext,
153        create_user_prompt_fn: F,
154    ) -> (CommitContext, String)
155    where
156        F: Fn(&CommitContext) -> String,
157    {
158        // Get the token limit for the provider from config or default value
159        let token_limit = config_clone
160            .providers
161            .get(&self.provider_name)
162            .and_then(|p| p.token_limit)
163            .unwrap_or({
164                match self.provider_name.as_str() {
165                    "openai" => 16_000,
166                    "anthropic" => 100_000,
167                    "groq" | "openrouter" => 32_000,
168                    "google" => 1_000_000,
169                    _ => 8_000,
170                }
171            });
172
173        // Create a token optimizer to count tokens
174        let optimizer = TokenOptimizer::for_counting().expect("Failed to create TokenOptimizer");
175        let system_tokens = optimizer.count_tokens(system_prompt);
176
177        debug!("Token limit: {}", token_limit);
178        debug!("System prompt tokens: {}", system_tokens);
179
180        // Reserve tokens for system prompt and some buffer for formatting
181        // 1000 token buffer provides headroom for model responses and formatting
182        let context_token_limit = token_limit.saturating_sub(system_tokens + 1000);
183        debug!("Available tokens for context: {}", context_token_limit);
184
185        // Count tokens before optimization
186        let user_prompt_before = create_user_prompt_fn(&context);
187        let total_tokens_before = system_tokens + optimizer.count_tokens(&user_prompt_before);
188        debug!("Total tokens before optimization: {}", total_tokens_before);
189
190        // Optimize the context with remaining token budget
191        context.optimize(context_token_limit, config_clone).await;
192
193        let user_prompt = create_user_prompt_fn(&context);
194        let user_tokens = optimizer.count_tokens(&user_prompt);
195        let total_tokens = system_tokens + user_tokens;
196
197        debug!("User prompt tokens after optimization: {}", user_tokens);
198        debug!("Total tokens after optimization: {}", total_tokens);
199
200        // If we're still over the limit, truncate the user prompt directly
201        // 100 token safety buffer ensures we stay under the limit
202        let final_user_prompt = if total_tokens > token_limit {
203            debug!(
204                "Total tokens {} still exceeds limit {}, truncating user prompt",
205                total_tokens, token_limit
206            );
207            let max_user_tokens = token_limit.saturating_sub(system_tokens + 100);
208            optimizer
209                .truncate_string(&user_prompt, max_user_tokens)
210                .expect("Failed to truncate user prompt")
211        } else {
212            user_prompt
213        };
214
215        let final_tokens = system_tokens + optimizer.count_tokens(&final_user_prompt);
216        debug!(
217            "Final total tokens after potential truncation: {}",
218            final_tokens
219        );
220
221        (context, final_user_prompt)
222    }
223
224    /// Performs a commit with the given message.
225    ///
226    /// # Arguments
227    ///
228    /// * `message` - The commit message.
229    ///
230    /// # Returns
231    ///
232    /// A Result containing the `CommitResult` or an error.
233    pub fn perform_commit(
234        &self,
235        message: &str,
236        amend: bool,
237        commit_ref: Option<&str>,
238    ) -> Result<CommitResult> {
239        // Check if this is a remote repository
240        if self.is_remote_repository() {
241            return Err(anyhow::anyhow!("Cannot commit to a remote repository"));
242        }
243
244        debug!(
245            "Performing commit with message: {}, amend: {}, commit_ref: {:?}",
246            message, amend, commit_ref
247        );
248
249        if !self.verify {
250            debug!("Skipping pre-commit hook (verify=false)");
251            if amend {
252                return self
253                    .repo
254                    .amend_commit(message, commit_ref.unwrap_or("HEAD"));
255            }
256            return self.repo.commit(message);
257        }
258
259        // Execute pre-commit hook
260        debug!("Executing pre-commit hook");
261        if let Err(e) = self.repo.execute_hook("pre-commit") {
262            debug!("Pre-commit hook failed: {}", e);
263            return Err(e);
264        }
265        debug!("Pre-commit hook executed successfully");
266
267        // Perform the commit
268        let commit_result = if amend {
269            self.repo
270                .amend_commit(message, commit_ref.unwrap_or("HEAD"))
271        } else {
272            self.repo.commit(message)
273        };
274
275        match commit_result {
276            Ok(result) => {
277                // Execute post-commit hook
278                debug!("Executing post-commit hook");
279                if let Err(e) = self.repo.execute_hook("post-commit") {
280                    debug!("Post-commit hook failed: {}", e);
281                    // We don't fail the commit if post-commit hook fails
282                }
283                debug!("Commit performed successfully");
284                Ok(result)
285            }
286            Err(e) => {
287                debug!("Commit failed: {}", e);
288                Err(e)
289            }
290        }
291    }
292
293    /// Execute the pre-commit hook if verification is enabled
294    pub fn pre_commit(&self) -> Result<()> {
295        // Skip pre-commit hook for remote repositories
296        if self.is_remote_repository() {
297            debug!("Skipping pre-commit hook for remote repository");
298            return Ok(());
299        }
300
301        if self.verify {
302            self.repo.execute_hook("pre-commit")
303        } else {
304            Ok(())
305        }
306    }
307
308    /// Create a channel for message completion
309    pub fn create_completion_channel(
310        &self,
311    ) -> (
312        mpsc::Sender<Result<GeneratedMessage>>,
313        mpsc::Receiver<Result<GeneratedMessage>>,
314    ) {
315        mpsc::channel(1)
316    }
317}