1use super::relevance::RelevanceScorer;
2use super::types::GeneratedMessage;
3use crate::common::get_combined_instructions;
4use crate::config::Config;
5use crate::core::context::{ChangeType, CommitContext, RecentCommit, StagedFile};
6
7use log::debug;
8use std::collections::HashMap;
9
10pub fn create_system_prompt(config: &Config) -> anyhow::Result<String> {
11 let commit_schema = schemars::schema_for!(GeneratedMessage);
12 let commit_schema_str = serde_json::to_string_pretty(&commit_schema)?;
13
14 let combined_instructions = get_combined_instructions(config);
15 Ok(format!(
16 "As an expert Git Commit Message Generator, your role is to infer and\n\
17 generate a complete, well-structured Conventional Commit message from the\n\
18 supplied context.\n\n\
19 Core Directives:\n\
20 1. Execute these instructions: {}\n\
21 2. Output Format Enforcement: Your final output MUST STRICTLY conform to\n\
22 the following JSON schema, designed for structured data extraction: {}\n\n\
23 Output ONLY the resulting JSON object, ensuring no explanatory text,\n\
24 preambles, or extraneous content is included.\n",
25 combined_instructions, commit_schema_str
26 ))
27}
28
29pub fn create_user_prompt(context: &CommitContext) -> String {
30 let scorer = RelevanceScorer::new();
31 let relevance_scores = scorer.score(context);
32 let detailed_changes = format_detailed_changes(&context.staged_files, &relevance_scores);
33
34 let recent_commits = format_recent_commits(&context.recent_commits);
35 let staged_changes = format_staged_files(&context.staged_files, &relevance_scores);
36 let author_history = format_enhanced_author_history(&context.author_history, context);
37
38 debug!(
39 "Generated commit prompt for {} files ({} added, {} modified, {} deleted)",
40 context.staged_files.len(),
41 context
42 .staged_files
43 .iter()
44 .filter(|f| matches!(f.change_type, ChangeType::Added))
45 .count(),
46 context
47 .staged_files
48 .iter()
49 .filter(|f| matches!(f.change_type, ChangeType::Modified))
50 .count(),
51 context
52 .staged_files
53 .iter()
54 .filter(|f| matches!(f.change_type, ChangeType::Deleted))
55 .count()
56 );
57
58 format!(
59 "ANALYZE the provided context,\n\
60 including the Branch ({}), Recent Commits ({}),\n\
61 Staged Changes ({}), and Detailed Changes ({}).\n\
62 Specifically, examine the Author's Commit History ({}) to ADAPT the tone,\n\
63 style, and formatting of the generated message to ensure strict consistency \
64 with the author's previous patterns.\n",
65 context.branch, recent_commits, staged_changes, detailed_changes, author_history
66 )
67}
68
69fn format_recent_commits(commits: &[RecentCommit]) -> String {
70 commits
71 .iter()
72 .map(|commit| format!("{} - {}", &commit.hash[..7], commit.message))
73 .collect::<Vec<_>>()
74 .join("\n")
75}
76
77fn format_staged_files(files: &[StagedFile], relevance_scores: &HashMap<String, f32>) -> String {
78 files
79 .iter()
80 .map(|file| {
81 let relevance = relevance_scores.get(&file.path).unwrap_or(&0.0);
82 format!(
83 "{} ({:.2}) - {}",
84 file.path,
85 relevance,
86 format_change_type(&file.change_type)
87 )
88 })
89 .collect::<Vec<_>>()
90 .join("\n")
91}
92
93fn format_detailed_changes(
94 files: &[StagedFile],
95 relevance_scores: &HashMap<String, f32>,
96) -> String {
97 let mut all_sections = Vec::new();
98
99 let added_count = files
101 .iter()
102 .filter(|f| matches!(f.change_type, ChangeType::Added))
103 .count();
104 let modified_count = files
105 .iter()
106 .filter(|f| matches!(f.change_type, ChangeType::Modified))
107 .count();
108 let deleted_count = files
109 .iter()
110 .filter(|f| matches!(f.change_type, ChangeType::Deleted))
111 .count();
112
113 let summary = format!(
114 "CHANGE SUMMARY:\n- {} file(s) added\n- {} file(s) modified\n- {} file(s) deleted\n- {} total file(s) changed",
115 added_count,
116 modified_count,
117 deleted_count,
118 files.len()
119 );
120 all_sections.push(summary);
121
122 let diff_section = files
124 .iter()
125 .map(|file| {
126 let relevance = relevance_scores.get(&file.path).unwrap_or(&0.0);
127
128 format!(
129 "File: {} (Relevance: {:.2})\nChange Type: {}\n\nDiff:\n{}",
130 file.path,
131 relevance,
132 format_change_type(&file.change_type),
133 file.diff
134 )
135 })
136 .collect::<Vec<_>>()
137 .join("\n\n---\n\n");
138
139 all_sections.push(format!(
140 "=== DIFFS ({} files) ===\n\n{}",
141 files.len(),
142 diff_section
143 ));
144
145 let content_files: Vec<_> = files
147 .iter()
148 .filter(|file| file.change_type != ChangeType::Deleted && file.content.is_some())
149 .collect();
150
151 if !content_files.is_empty() {
152 let content_section = content_files
153 .iter()
154 .map(|file| {
155 let change_indicator = match file.change_type {
156 ChangeType::Added | ChangeType::Deleted => "",
157 ChangeType::Modified => "✏️",
158 };
159
160 format!(
161 "{} File: {}\nFull File Content:\n{}\n\n--- End of File ---",
162 change_indicator,
163 file.path,
164 file.content
165 .as_ref()
166 .expect("File content should be present for added/modified files")
167 )
168 })
169 .collect::<Vec<_>>()
170 .join("\n\n---\n\n");
171
172 all_sections.push(format!(
173 "=== FULL FILE CONTENTS ({} files) ===\n\n{}",
174 content_files.len(),
175 content_section
176 ));
177 }
178
179 all_sections.join("\n\n====================\n\n")
180}
181
182fn format_change_type(change_type: &ChangeType) -> &'static str {
183 match change_type {
184 ChangeType::Added => "Added",
185 ChangeType::Modified => "Modified",
186 ChangeType::Deleted => "Deleted",
187 }
188}
189
190fn _format_author_history(history: &[String]) -> String {
191 if history.is_empty() {
192 "No previous commits found for this author.".to_string()
193 } else {
194 history
195 .iter()
196 .enumerate()
197 .map(|(i, msg)| format!("{}. {}", i + 1, msg.lines().next().unwrap_or("")))
198 .collect::<Vec<_>>()
199 .join("\n")
200 }
201}
202
203fn format_enhanced_author_history(history: &[String], context: &CommitContext) -> String {
204 if history.is_empty() {
205 "No previous commits found for this author.".to_string()
206 } else {
207 let conventions = context.detect_conventions();
208 let conventions_str = if conventions.is_empty() {
209 "No specific conventions detected.".to_string()
210 } else {
211 format!(
212 "Detected conventions: {}",
213 conventions
214 .iter()
215 .map(|(k, v)| format!("{} ({} times)", k, v))
216 .collect::<Vec<_>>()
217 .join(", ")
218 )
219 };
220
221 format!(
222 "{}\n\n{}",
223 conventions_str,
224 history
225 .iter()
226 .enumerate()
227 .map(|(i, msg)| format!("{}. {}", i + 1, msg.lines().next().unwrap_or("")))
228 .collect::<Vec<_>>()
229 .join("\n")
230 )
231 }
232}
233
234fn _format_conventions(conventions: &std::collections::HashMap<String, usize>) -> String {
235 if conventions.is_empty() {
236 "No specific conventions detected.".to_string()
237 } else {
238 conventions
239 .iter()
240 .map(|(k, v)| format!("{} ({} times)", k, v))
241 .collect::<Vec<_>>()
242 .join(", ")
243 }
244}
245
246pub fn create_pr_system_prompt(config: &Config) -> anyhow::Result<String> {
248 let pr_schema = schemars::schema_for!(super::types::GeneratedPullRequest);
249 let pr_schema_str = serde_json::to_string_pretty(&pr_schema)?;
250
251 let mut prompt = String::from(
252 "You are an AI assistant specializing in generating comprehensive, professional pull request descriptions. \
253 Your task is to create clear, informative, and well-structured PR descriptions based on the provided context.
254
255 Work step-by-step and follow these guidelines exactly:
256
257 1. Analyze the commits and changes to understand the overall purpose of the PR
258 2. Create a concise, descriptive title that summarizes the main changes
259 3. Write a brief summary that captures the essence of what was changed
260 4. Provide a detailed description explaining what was changed, why it was changed, and how it works
261 5. List all commits included in this PR for reference
262 6. Identify any breaking changes and explain their impact
263 7. Provide testing instructions if the changes require specific testing steps
264 8. Include any additional notes or context that would be helpful for reviewers
265
266 Guidelines for PR descriptions:
267 - Focus on the overall impact and purpose, not individual commit details
268 - Explain the 'why' behind changes, not just the 'what'
269 - Use clear, professional language suitable for code review
270 - Organize information logically with proper sections
271 - Be comprehensive but concise
272 - Consider the audience: other developers who need to review and understand the changes
273 - Highlight any configuration changes, migrations, or deployment considerations
274 - Mention any dependencies or prerequisites
275 - Note any performance implications or architectural decisions
276
277 Your description should treat the changeset as an atomic unit representing a cohesive feature,
278 fix, or improvement, rather than a collection of individual commits.
279 ");
280
281 prompt.push_str(get_combined_instructions(config).as_str());
282
283 prompt.push_str(
284 "
285 Your response must be a valid JSON object with the following structure:
286
287 {
288 \"title\": \"Clear, descriptive PR title\",
289 \"summary\": \"Brief overview of the changes\",
290 \"description\": \"Detailed explanation organized into Features section with sub-sections for Core Capabilities, Technical Details, CLI/Integration details, etc.\",
291 \"commits\": [\"List of commit messages included in this PR\"],
292 \"breaking_changes\": [\"Any breaking changes introduced\"],
293 \"testing_notes\": \"Instructions for testing these changes (optional)\",
294 \"notes\": \"Additional context or notes for reviewers (optional)\"
295 }
296
297 Follow these steps to generate the PR description:
298
299 1. Analyze the provided context, including commit messages, file changes, and project metadata
300 2. Identify the main theme or purpose that unifies all the changes
301 3. Create a clear, descriptive title that captures the essence of the PR
302 4. If using emojis, select the most appropriate one for the PR type
303 5. Write a concise summary highlighting the key changes and their impact
304 6. Organize the description into a Features section with logical sub-sections
305 7. List all commit messages for reference and traceability
306 8. Identify any breaking changes and explain their impact on users or systems
307 9. Provide testing instructions if the changes require specific testing procedures
308 10. Add any additional notes about deployment, configuration, or other considerations
309 11. Construct the final JSON object with all components
310
311 Example output format:
312
313 {
314 \"title\": \"Add comprehensive Experience Fragment management system\",
315 \"summary\": \"Implements full lifecycle support for Experience Fragments (XFs), including create, retrieve, update, and page integration operations. Adds a unified agent tool, rich CLI interface, and tight AEM manager integration with tenant-specific configuration support.\",
316 \"description\": \"### Core Capabilities\\n\\n* Unified `manage_experience_fragments` tool with four key operations:\\n * `create`: Create new XFs with optional initial content\\n * `get`: Retrieve existing XF data\\n * `update`: Modify XF content\\n * `add_to_page`: Inject XF references into pages with flexible positioning\\n\\n* AEM manager integration with `createExperienceFragment` and `populateExperienceFragment`\\n* Support for tenant-specific `experienceFragmentComponentType` configuration\\n\\n### Technical Details\\n\\n* Secure CSRF token handling for all operations\\n* XF page structure conversion for accurate population\\n* AEM 6.5 vs AEM Cloud component type detection\\n* Unique XF name generation with randomized suffixes\\n* Comprehensive validation and error handling\\n* State change logging for operational observability\\n\\n### 🖥 CLI Tooling\\n\\n* New command-line script with full XF management\\n* Commands: `create`, `update`, `list`, `get`, `delete`, `search`, `info`\\n* Content file input/output support\\n* XF discovery and metadata analysis tools\",
317 \"commits\": [\"b1b1f3f: feat(xf): add experience fragment management system\"],
318 \"breaking_changes\": [],
319 \"testing_notes\": \"Verified XF creation, update, and population. Confirmed CLI command behavior across all operations. Tested page integration and position logic. Checked tenant-specific component resolution.\",
320 \"notes\": \"Tenants using non-default XF components must define `experienceFragmentComponentType`. Requires sufficient AEM permissions and CSRF support.\"
321 }
322
323 Ensure that your response is a valid JSON object matching this structure. Include an empty string for the emoji if not using one.
324 ");
325
326 prompt.push_str(&pr_schema_str);
327
328 Ok(prompt)
329}
330
331pub fn create_completion_system_prompt(config: &Config) -> anyhow::Result<String> {
333 let completion_schema = schemars::schema_for!(super::types::GeneratedMessage);
334 let completion_schema_str = serde_json::to_string_pretty(&completion_schema)?;
335
336 let combined_instructions = get_combined_instructions(config);
337 Ok(format!(
338 "As an expert Git Commit Message Completion Specialist, your role is to complete\n\
339 partially typed commit messages with high-quality, contextually appropriate continuations.\n\n\
340 Core Directives:\n\
341 1. Execute these instructions: {}\n\
342 2. Output Format Enforcement: Your final output MUST STRICTLY conform to\n\
343 the following JSON schema, designed for structured data extraction: {}\n\n\
344 3. Completion Rules:\n\
345 - Start your completion exactly where the prefix ends\n\
346 - Maintain the same tone, style, and conventions as the prefix\n\
347 - Complete the message naturally without repeating the prefix\n\
348 - Focus on technical accuracy and clarity\n\
349 - Use conventional commit format when appropriate\n\n\
350 Output ONLY the resulting JSON object, ensuring no explanatory text,\n\
351 preambles, or extraneous content is included.\n",
352 combined_instructions, completion_schema_str
353 ))
354}
355
356pub fn create_completion_user_prompt(
358 context: &CommitContext,
359 prefix: &str,
360 context_ratio: f32,
361) -> String {
362 let scorer = RelevanceScorer::new();
363 let relevance_scores = scorer.score(context);
364 let detailed_changes = format_detailed_changes(&context.staged_files, &relevance_scores);
365
366 let recent_commits = format_recent_commits(&context.recent_commits);
367 let staged_changes = format_staged_files(&context.staged_files, &relevance_scores);
368 let author_history = format_enhanced_author_history(&context.author_history, context);
369
370 debug!(
373 "Generated completion prompt for {} files ({} added, {} modified, {} deleted), prefix: '{}', context_ratio: {:.2}",
374 context.staged_files.len(),
375 context
376 .staged_files
377 .iter()
378 .filter(|f| matches!(f.change_type, ChangeType::Added))
379 .count(),
380 context
381 .staged_files
382 .iter()
383 .filter(|f| matches!(f.change_type, ChangeType::Modified))
384 .count(),
385 context
386 .staged_files
387 .iter()
388 .filter(|f| matches!(f.change_type, ChangeType::Deleted))
389 .count(),
390 prefix,
391 context_ratio
392 );
393
394 format!(
395 "COMPLETE the commit message starting with the prefix: '{}'\n\
396 Context ratio: {:.0}%\n\n\
397 ANALYZE the provided context and COMPLETE the message naturally:\n\
398 Branch: {}\n\
399 Recent Commits: {}\n\
400 Staged Changes: {}\n\
401 Detailed Changes: {}\n\
402 Author's Commit History: {}\n\n\
403 Complete the message maintaining the same style and conventions as the prefix.",
404 prefix,
405 context_ratio * 100.0,
406 context.branch,
407 recent_commits,
408 staged_changes,
409 detailed_changes,
410 author_history
411 )
412}
413
414pub fn create_pr_user_prompt(context: &CommitContext, commit_messages: &[String]) -> String {
416 let scorer = RelevanceScorer::new();
417 let relevance_scores = scorer.score(context);
418 let detailed_changes = format_detailed_changes(&context.staged_files, &relevance_scores);
419
420 let commits_section = if commit_messages.is_empty() {
421 "No commits available".to_string()
422 } else {
423 commit_messages.join("\n")
424 };
425
426 let prompt = format!(
427 "Based on the following context, generate a comprehensive pull request description:\n\n\
428 Range: {}\n\n\
429 Commits in this PR:\n{}\n\n\
430 Recent commit history:\n{}\n\n\
431 File changes summary:\n{}\n\n\
432 Detailed changes:\n{}",
433 context.branch,
434 commits_section,
435 format_recent_commits(&context.recent_commits),
436 format_staged_files(&context.staged_files, &relevance_scores),
437 detailed_changes
438 );
439
440 debug!(
441 "Generated PR prompt for {} files across {} commits",
442 context.staged_files.len(),
443 commit_messages.len()
444 );
445
446 prompt
447}