gait 0.1.3

AI-powered toolkit that enhances `Git` workflow
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
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
use super::relevance::RelevanceScorer;
use super::types::GeneratedMessage;
use crate::common::get_combined_instructions;
use crate::config::Config;
use crate::core::context::{ChangeType, CommitContext, RecentCommit, StagedFile};

use log::debug;
use std::collections::HashMap;

pub fn create_system_prompt(config: &Config) -> anyhow::Result<String> {
    let commit_schema = schemars::schema_for!(GeneratedMessage);
    let commit_schema_str = serde_json::to_string_pretty(&commit_schema)?;

    let combined_instructions = get_combined_instructions(config);
    Ok(format!(
        "# ROLE: Git Commit Message Generator\n\
         \n\
         You are an expert Git Commit Message Generator specializing in creating high-quality, \
         conventional commit messages from code changes.\n\
         \n\
         ## Core Responsibilities\n\
         \n\
         1. **Analyze Context:** Infer the intent and impact of code changes\n\
         2. **Generate Messages:** Create well-structured, conventional commit messages\n\
         3. **Maintain Standards:** Follow conventional commit format and best practices\n\
         4. **Ensure Quality:** Make messages concise, descriptive, and actionable\n\
         \n\
         ## Instructions\n\
         \n\
         {}\n\
         \n\
         ## Output Requirements\n\
         \n\
         **Format:** Your final output MUST STRICTLY conform to the following JSON schema:\n\
         \n\
         ```json\n\
         {}\n\
         ```\n\
         \n\
         **Important:** Output ONLY the JSON object. No explanatory text, preambles, \
         or additional content.\n",
        combined_instructions, commit_schema_str
    ))
}

pub fn create_user_prompt(context: &CommitContext) -> String {
    let scorer = RelevanceScorer::new();
    let relevance_scores = scorer.score(context);
    let detailed_changes = format_detailed_changes(&context.staged_files, &relevance_scores);

    let recent_commits = format_recent_commits(&context.recent_commits);
    let staged_changes = format_staged_files(&context.staged_files, &relevance_scores);
    let author_history = format_enhanced_author_history(&context.author_history, context);

    debug!(
        "Generated commit prompt for {} files ({} added, {} modified, {} deleted)",
        context.staged_files.len(),
        context
            .staged_files
            .iter()
            .filter(|f| matches!(f.change_type, ChangeType::Added))
            .count(),
        context
            .staged_files
            .iter()
            .filter(|f| matches!(f.change_type, ChangeType::Modified))
            .count(),
        context
            .staged_files
            .iter()
            .filter(|f| matches!(f.change_type, ChangeType::Deleted))
            .count()
    );

    format!(
        "# TASK: Generate Commit Message\n\
         \n\
         ANALYZE the provided context and generate a well-structured commit message.\n\
         \n\
         ## Context Information\n\
         \n\
         **Branch:** {}\n\
         \n\
         **Recent Commits:**\n\
         {}\n\
         \n\
         **Staged Changes:**\n\
         {}\n\
         \n\
         **Detailed Changes:**\n\
         {}\n\
         \n\
         **Author's Commit History:**\n\
         {}\n\
         \n\
         ## Analysis Requirements\n\
         \n\
         1. ANALYZE the patterns in the author's commit history\n\
         2. Ensure the generated message maintains consistent tone, style, and formatting\n\
         3. Follow conventional commit standards when appropriate\n\
         4. Make the message concise yet descriptive\n\
         5. Focus on the intent and impact of the changes\n",
        context.branch, recent_commits, staged_changes, detailed_changes, author_history
    )
}

fn format_recent_commits(commits: &[RecentCommit]) -> String {
    commits
        .iter()
        .map(|commit| {
            format!(
                "{} - {}",
                &commit.hash[..commit.hash.len().min(7)],
                commit.message
            )
        })
        .collect::<Vec<_>>()
        .join("\n")
}

fn format_staged_files(files: &[StagedFile], relevance_scores: &HashMap<String, f32>) -> String {
    files
        .iter()
        .map(|file| {
            let relevance = relevance_scores.get(&file.path).unwrap_or(&0.0);
            format!(
                "{} ({:.2}) - {}",
                file.path,
                relevance,
                format_change_type(&file.change_type)
            )
        })
        .collect::<Vec<_>>()
        .join("\n")
}

fn format_detailed_changes(
    files: &[StagedFile],
    relevance_scores: &HashMap<String, f32>,
) -> String {
    let mut all_sections = Vec::new();

    // Add a statistical summary at the top
    let added_count = files
        .iter()
        .filter(|f| matches!(f.change_type, ChangeType::Added))
        .count();
    let modified_count = files
        .iter()
        .filter(|f| matches!(f.change_type, ChangeType::Modified))
        .count();
    let deleted_count = files
        .iter()
        .filter(|f| matches!(f.change_type, ChangeType::Deleted))
        .count();

    let summary = format!(
        "CHANGE SUMMARY:\n- {} file(s) added\n- {} file(s) modified\n- {} file(s) deleted\n- {} total file(s) changed",
        added_count,
        modified_count,
        deleted_count,
        files.len()
    );
    all_sections.push(summary);

    // First section: File summaries with diffs
    let diff_section = files
        .iter()
        .map(|file| {
            let relevance = relevance_scores.get(&file.path).unwrap_or(&0.0);

            format!(
                "File: {} (Relevance: {:.2})\nChange Type: {}\n\nDiff:\n{}",
                file.path,
                relevance,
                format_change_type(&file.change_type),
                file.diff
            )
        })
        .collect::<Vec<_>>()
        .join("\n\n---\n\n");

    all_sections.push(format!(
        "=== DIFFS ({} files) ===\n\n{}",
        files.len(),
        diff_section
    ));

    // Second section: Full file contents (only for added/modified files)
    let content_files: Vec<_> = files
        .iter()
        .filter(|file| file.change_type != ChangeType::Deleted && file.content.is_some())
        .collect();

    if !content_files.is_empty() {
        let content_section = content_files
            .iter()
            .map(|file| {
                let change_indicator = match file.change_type {
                    ChangeType::Added | ChangeType::Deleted => "",
                    ChangeType::Modified => "✏️",
                };

                format!(
                    "{} File: {}\nFull File Content:\n{}\n\n--- End of File ---",
                    change_indicator,
                    file.path,
                    file.content
                        .as_ref()
                        .expect("File content should be present for added/modified files")
                )
            })
            .collect::<Vec<_>>()
            .join("\n\n---\n\n");

        all_sections.push(format!(
            "=== FULL FILE CONTENTS ({} files) ===\n\n{}",
            content_files.len(),
            content_section
        ));
    }

    all_sections.join("\n\n====================\n\n")
}

fn format_change_type(change_type: &ChangeType) -> &'static str {
    match change_type {
        ChangeType::Added => "Added",
        ChangeType::Modified => "Modified",
        ChangeType::Deleted => "Deleted",
    }
}

fn _format_author_history(history: &[String]) -> String {
    if history.is_empty() {
        "No previous commits found for this author.".to_string()
    } else {
        history
            .iter()
            .enumerate()
            .map(|(i, msg)| format!("{}. {}", i + 1, msg.lines().next().unwrap_or("")))
            .collect::<Vec<_>>()
            .join("\n")
    }
}

fn format_enhanced_author_history(history: &[String], context: &CommitContext) -> String {
    if history.is_empty() {
        "No previous commits found for this author.".to_string()
    } else {
        let conventions = context.detect_conventions();
        let conventions_str = if conventions.is_empty() {
            "No specific conventions detected.".to_string()
        } else {
            format!(
                "Detected conventions: {}",
                conventions
                    .iter()
                    .map(|(k, v)| format!("{} ({} times)", k, v))
                    .collect::<Vec<_>>()
                    .join(", ")
            )
        };

        format!(
            "{}\n\n{}",
            conventions_str,
            history
                .iter()
                .enumerate()
                .map(|(i, msg)| format!("{}. {}", i + 1, msg.lines().next().unwrap_or("")))
                .collect::<Vec<_>>()
                .join("\n")
        )
    }
}

fn _format_conventions(conventions: &std::collections::HashMap<String, usize>) -> String {
    if conventions.is_empty() {
        "No specific conventions detected.".to_string()
    } else {
        conventions
            .iter()
            .map(|(k, v)| format!("{} ({} times)", k, v))
            .collect::<Vec<_>>()
            .join(", ")
    }
}

/// Creates a system prompt for PR description generation
pub fn create_pr_system_prompt(config: &Config) -> anyhow::Result<String> {
    let pr_schema = schemars::schema_for!(super::types::GeneratedPullRequest);
    let pr_schema_str = serde_json::to_string_pretty(&pr_schema)?;

    let mut prompt = String::from(
        "# ROLE: Pull Request Description Specialist\n\
        \n\
        You are an AI assistant specializing in generating comprehensive, professional pull request descriptions. \
        Your task is to ANALYZE the provided context and create clear, informative, and well-structured PR descriptions.\n\
        \n\
        ## Core Responsibilities\n\
        \n\
        1. **Analyze Changeset:** Understand the overall purpose and impact of the PR as a cohesive unit\n\
        2. **Create Structure:** Generate well-organized PR descriptions with clear sections\n\
        3. **Explain Context:** Focus on the 'why' and 'how' behind changes, not just the 'what'\n\
        4. **Ensure Quality:** Use professional language suitable for code review\n\
        \n\
        ## PR Description Structure\n\
        \n\
        ANALYZE the commits and changes, then create:\n\
        \n\
        1. **Title:** Concise, descriptive title summarizing the main changes\n\
        2. **Summary:** Brief overview capturing the essence of what was changed\n\
        3. **Description:** Detailed explanation of changes, rationale, and implementation\n\
        4. **Commits:** List of all commits included in this PR for reference\n\
        5. **Breaking Changes:** Identify and explain any breaking changes\n\
        6. **Testing:** Provide testing instructions if specific steps are required\n\
        7. **Additional Notes:** Include helpful context for reviewers\n\
        \n\
        ## Guidelines\n\
        \n\
        - **Holistic View:** Treat the changeset as an atomic unit, not individual commits\n\
        - **Clear Language:** Use professional, accessible language for all developers\n\
        - **Logical Organization:** Structure information with proper sections and hierarchy\n\
        - **Comprehensive Yet Concise:** Be thorough but avoid unnecessary detail\n\
        - **Reviewer-Focused:** Consider what reviewers need to understand and approve\n\
        - **Technical Context:** Highlight configuration, migration, deployment, and performance considerations\n\
        - **Dependencies:** Mention prerequisites, dependencies, and architectural decisions\n\
        \n\
        Focus on the overall impact and purpose rather than individual commit details.
        ");

    prompt.push_str(get_combined_instructions(config).as_str());

    prompt.push_str(
        "
        Your response must be a valid JSON object with the following structure:

        {
          \"title\": \"Clear, descriptive PR title\",
          \"summary\": \"Brief overview of the changes\",
          \"description\": \"Detailed explanation organized into Features section with sub-sections for Core Capabilities, Technical Details, CLI/Integration details, etc.\",
          \"commits\": [\"List of commit messages included in this PR\"],
          \"breaking_changes\": [\"Any breaking changes introduced\"],
          \"testing_notes\": \"Instructions for testing these changes (optional)\",
          \"notes\": \"Additional context or notes for reviewers (optional)\"
        }

        Follow these steps to generate the PR description:

        1. Analyze the provided context, including commit messages, file changes, and project metadata
        2. Identify the main theme or purpose that unifies all the changes
        3. Create a clear, descriptive title that captures the essence of the PR
        4. If using emojis, select the most appropriate one for the PR type
        5. Write a concise summary highlighting the key changes and their impact
        6. Organize the description into a Features section with logical sub-sections
        7. List all commit messages for reference and traceability
        8. Identify any breaking changes and explain their impact on users or systems
        9. Provide testing instructions if the changes require specific testing procedures
        10. Add any additional notes about deployment, configuration, or other considerations
        11. Construct the final JSON object with all components

        Example output format:

        {
          \"title\": \"Add comprehensive Experience Fragment management system\",
          \"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.\",
          \"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\",
          \"commits\": [\"b1b1f3f: feat(xf): add experience fragment management system\"],
          \"breaking_changes\": [],
          \"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.\",
          \"notes\": \"Tenants using non-default XF components must define `experienceFragmentComponentType`. Requires sufficient AEM permissions and CSRF support.\"
        }

        Ensure that your response is a valid JSON object matching this structure. Include an empty string for the emoji if not using one.
        ");

    prompt.push_str(&pr_schema_str);

    Ok(prompt)
}

/// Creates a system prompt for commit message completion
pub fn create_completion_system_prompt(config: &Config) -> anyhow::Result<String> {
    let completion_schema = schemars::schema_for!(super::types::GeneratedMessage);
    let completion_schema_str = serde_json::to_string_pretty(&completion_schema)?;

    let combined_instructions = get_combined_instructions(config);
    Ok(format!(
        "# ROLE: Git Commit Message Completion Specialist\n\
         \n\
         You are an expert Git Commit Message Completion Specialist specializing in completing \
         partially typed commit messages with high-quality, contextually appropriate continuations.\n\
         \n\
         ## Core Responsibilities\n\
         \n\
         1. **Complete Messages:** Finish partially typed commit messages naturally\n\
         2. **Maintain Context:** Preserve the original intent and style of the prefix\n\
         3. **Ensure Quality:** Create coherent, well-structured final messages\n\
         4. **Follow Standards:** Use conventional commit format when appropriate\n\
         \n\
         ## Instructions\n\
         \n\
         {}\n\
         \n\
         ## Completion Rules\n\
         \n\
         1. **Start Point:** Begin completion exactly where the prefix ends\n\
         2. **Style Consistency:** Maintain the same tone, style, and conventions as the prefix\n\
         3. **Natural Flow:** Complete the message naturally without repeating the prefix\n\
         4. **Technical Accuracy:** Focus on technical accuracy and clarity\n\
         5. **Format Standards:** Use conventional commit format when appropriate\n\
         \n\
         ## Output Requirements\n\
         \n\
         **Format:** Your final output MUST STRICTLY conform to the following JSON schema:\n\
         \n\
         ```json\n\
         {}\n\
         ```\n\
         \n\
         **Important:** Output ONLY the JSON object. No explanatory text, preambles, \
         or additional content.\n",
        combined_instructions, completion_schema_str
    ))
}

/// Creates a user prompt for commit message completion
pub fn create_completion_user_prompt(
    context: &CommitContext,
    prefix: &str,
    context_ratio: f32,
) -> String {
    let scorer = RelevanceScorer::new();
    let relevance_scores = scorer.score(context);
    let detailed_changes = format_detailed_changes(&context.staged_files, &relevance_scores);

    let recent_commits = format_recent_commits(&context.recent_commits);
    let staged_changes = format_staged_files(&context.staged_files, &relevance_scores);
    let author_history = format_enhanced_author_history(&context.author_history, context);

    // Detect conventions from history (already included in enhanced author history)

    debug!(
        "Generated completion prompt for {} files ({} added, {} modified, {} deleted), prefix: '{}', context_ratio: {:.2}",
        context.staged_files.len(),
        context
            .staged_files
            .iter()
            .filter(|f| matches!(f.change_type, ChangeType::Added))
            .count(),
        context
            .staged_files
            .iter()
            .filter(|f| matches!(f.change_type, ChangeType::Modified))
            .count(),
        context
            .staged_files
            .iter()
            .filter(|f| matches!(f.change_type, ChangeType::Deleted))
            .count(),
        prefix,
        context_ratio
    );

    format!(
        "# TASK: Complete Commit Message\n\
         \n\
         ANALYZE the provided context and complete the commit message naturally.\n\
         \n\
         ## Message Prefix\n\
         \n\
         **Prefix:** '{}'\n\
         **Context Ratio:** {:.0}%\n\
         \n\
         ## Context Information\n\
         \n\
         **Branch:** {}\n\
         \n\
         **Recent Commits:**\n\
         {}\n\
         \n\
         **Staged Changes:**\n\
         {}\n\
         \n\
         **Detailed Changes:**\n\
         {}\n\
         \n\
         **Author's Commit History:**\n\
         {}\n\
         \n\
         ## Completion Requirements\n\
         \n\
         1. ANALYZE the author's commit history patterns\n\
         2. Complete the message maintaining the same style and conventions as the prefix\n\
         3. Continue naturally from where the prefix ends\n\
         4. Ensure the completed message is coherent and well-structured\n\
         5. Follow conventional commit standards when appropriate\n",
        prefix,
        context_ratio * 100.0,
        context.branch,
        recent_commits,
        staged_changes,
        detailed_changes,
        author_history
    )
}

/// Creates a user prompt for PR description generation
pub fn create_pr_user_prompt(context: &CommitContext, commit_messages: &[String]) -> String {
    let scorer = RelevanceScorer::new();
    let relevance_scores = scorer.score(context);
    let detailed_changes = format_detailed_changes(&context.staged_files, &relevance_scores);

    let commits_section = if commit_messages.is_empty() {
        "No commits available".to_string()
    } else {
        commit_messages.join("\n")
    };

    let prompt = format!(
        "Based on the following context, generate a comprehensive pull request description:\n\n\
         Range: {}\n\n\
         Commits in this PR:\n{}\n\n\
         Recent commit history:\n{}\n\n\
         File changes summary:\n{}\n\n\
         Detailed changes:\n{}",
        context.branch,
        commits_section,
        format_recent_commits(&context.recent_commits),
        format_staged_files(&context.staged_files, &relevance_scores),
        detailed_changes
    );

    debug!(
        "Generated PR prompt for {} files across {} commits",
        context.staged_files.len(),
        commit_messages.len()
    );

    prompt
}