git-iris 2.0.8

AI-powered Git workflow assistant for smart commits, code reviews, changelogs, and release notes
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
//! Task context for agent operations
//!
//! This module provides structured, validated context for agent tasks,
//! replacing fragile string-based parameter passing.

use anyhow::{Result, bail};
use serde::{Deserialize, Serialize};

/// Validated, structured context for agent tasks.
///
/// This enum represents the different modes of operation for code analysis,
/// with validation built into the constructors.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(tag = "mode", rename_all = "snake_case")]
pub enum TaskContext {
    /// Analyze staged changes (optionally including unstaged)
    Staged {
        /// Whether to include unstaged changes in analysis
        include_unstaged: bool,
    },

    /// Analyze a single commit
    Commit {
        /// The commit ID (hash, branch name, or commitish like HEAD~1)
        commit_id: String,
    },

    /// Analyze a range of commits or branch comparison
    Range {
        /// Starting reference (exclusive)
        from: String,
        /// Ending reference (inclusive)
        to: String,
    },

    /// Generate changelog or release notes with version metadata
    Changelog {
        /// Starting reference (exclusive)
        from: String,
        /// Ending reference (inclusive)
        to: String,
        /// Explicit version name (e.g., "1.2.0")
        version_name: Option<String>,
        /// Release date in YYYY-MM-DD format
        date: String,
    },

    /// Amend the previous commit with staged changes
    /// The agent sees the combined diff from HEAD^1 to staged state
    Amend {
        /// The original commit message being amended
        original_message: String,
    },

    /// Let the agent discover context via tools (default for gen command)
    #[default]
    Discover,
}

impl TaskContext {
    /// Create context for the gen (commit message) command.
    /// Always uses staged changes only.
    #[must_use]
    pub fn for_gen() -> Self {
        Self::Staged {
            include_unstaged: false,
        }
    }

    /// Create context for amending the previous commit.
    /// The agent will see the combined diff from HEAD^1 to staged state.
    #[must_use]
    pub fn for_amend(original_message: String) -> Self {
        Self::Amend { original_message }
    }

    /// Create context for the review command with full parameter validation.
    ///
    /// Validates:
    /// - `--from` requires `--to` for explicit range comparison
    /// - `--to` on its own compares `<fallback-base>..to`
    /// - `--commit` is mutually exclusive with `--from/--to`
    /// - `--include-unstaged` is incompatible with range comparisons
    ///
    /// # Errors
    ///
    /// Returns an error when the provided flag combination is invalid.
    pub fn for_review(
        commit: Option<String>,
        from: Option<String>,
        to: Option<String>,
        include_unstaged: bool,
    ) -> Result<Self> {
        Self::for_review_with_base(commit, from, to, include_unstaged, "main")
    }

    /// Create review context with an explicit default base for `--to`-only comparisons.
    ///
    /// CLI and Studio should prefer a repo-aware base from `GitRepo::get_default_base_ref()`.
    /// This lets branch comparisons follow the repository's actual primary branch
    /// instead of relying on the legacy `"main"` fallback.
    ///
    /// # Errors
    ///
    /// Returns an error when the provided flag combination is invalid.
    pub fn for_review_with_base(
        commit: Option<String>,
        from: Option<String>,
        to: Option<String>,
        include_unstaged: bool,
        default_base: &str,
    ) -> Result<Self> {
        // Validate: --from requires --to
        if from.is_some() && to.is_none() {
            bail!("When using --from, you must also specify --to for branch comparison reviews");
        }

        // Validate: --commit is mutually exclusive with --from/--to
        if commit.is_some() && (from.is_some() || to.is_some()) {
            bail!("Cannot use --commit with --from/--to. These are mutually exclusive options");
        }

        // Validate: --include-unstaged incompatible with range comparisons
        if include_unstaged && (from.is_some() || to.is_some()) {
            bail!(
                "Cannot use --include-unstaged with --from/--to. Branch comparison reviews don't include working directory changes"
            );
        }

        // Route to correct variant based on parameters
        Ok(match (commit, from, to) {
            (Some(id), _, _) => Self::Commit { commit_id: id },
            (_, Some(f), Some(t)) => Self::Range { from: f, to: t },
            (None, None, Some(t)) => Self::Range {
                from: default_base.to_string(),
                to: t,
            },
            _ => Self::Staged { include_unstaged },
        })
    }

    /// Create context for the PR command.
    ///
    /// PR command is more flexible - all parameter combinations are valid:
    /// - `from` + `to`: Explicit range/branch comparison
    /// - `from` only: Compare `from..HEAD`
    /// - `to` only: Compare `<fallback-base>..to`
    /// - Neither: Compare `<fallback-base>..HEAD`
    #[must_use]
    pub fn for_pr(from: Option<String>, to: Option<String>) -> Self {
        Self::for_pr_with_base(from, to, "main")
    }

    /// Create PR context with an explicit default comparison base.
    ///
    /// CLI and Studio should prefer a repo-aware base from `GitRepo::get_default_base_ref()`.
    #[must_use]
    pub fn for_pr_with_base(from: Option<String>, to: Option<String>, default_base: &str) -> Self {
        match (from, to) {
            (Some(f), Some(t)) => Self::Range { from: f, to: t },
            (Some(f), None) => Self::Range {
                from: f,
                to: "HEAD".to_string(),
            },
            (None, Some(t)) => Self::Range {
                from: default_base.to_string(),
                to: t,
            },
            (None, None) => Self::Range {
                from: default_base.to_string(),
                to: "HEAD".to_string(),
            },
        }
    }

    /// Create context for changelog/release-notes commands.
    ///
    /// These always require a `from` reference; `to` defaults to HEAD.
    /// Automatically sets today's date if not provided.
    #[must_use]
    pub fn for_changelog(
        from: String,
        to: Option<String>,
        version_name: Option<String>,
        date: Option<String>,
    ) -> Self {
        Self::Changelog {
            from,
            to: to.unwrap_or_else(|| "HEAD".to_string()),
            version_name,
            date: date.unwrap_or_else(|| chrono::Local::now().format("%Y-%m-%d").to_string()),
        }
    }

    /// Generate a human-readable prompt context string for the agent.
    #[must_use]
    pub fn to_prompt_context(&self) -> String {
        serde_json::to_string_pretty(self).unwrap_or_else(|_| format!("{self:?}"))
    }

    /// Generate a hint for which `git_diff` call the agent should make.
    #[must_use]
    pub fn diff_hint(&self) -> String {
        match self {
            Self::Staged { include_unstaged } => {
                if *include_unstaged {
                    "git_diff() for staged changes, then check unstaged files".to_string()
                } else {
                    "git_diff() for staged changes".to_string()
                }
            }
            Self::Commit { commit_id } => {
                format!("git_diff(from=\"{commit_id}^1\", to=\"{commit_id}\")")
            }
            Self::Range { from, to } | Self::Changelog { from, to, .. } => {
                format!("git_diff(from=\"{from}\", to=\"{to}\")")
            }
            Self::Amend { .. } => {
                "git_diff(from=\"HEAD^1\") for combined amend diff (original commit + new staged changes)".to_string()
            }
            Self::Discover => "git_diff() to discover current changes".to_string(),
        }
    }

    /// Check if this context represents a range comparison (vs staged/single commit)
    #[must_use]
    pub fn is_range(&self) -> bool {
        matches!(self, Self::Range { .. })
    }

    /// Check if this context involves unstaged changes
    #[must_use]
    pub fn includes_unstaged(&self) -> bool {
        matches!(
            self,
            Self::Staged {
                include_unstaged: true
            }
        )
    }

    /// Check if this is an amend operation
    #[must_use]
    pub fn is_amend(&self) -> bool {
        matches!(self, Self::Amend { .. })
    }

    /// Get the original commit message if this is an amend context
    #[must_use]
    pub fn original_message(&self) -> Option<&str> {
        match self {
            Self::Amend { original_message } => Some(original_message),
            _ => None,
        }
    }
}

impl std::fmt::Display for TaskContext {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Staged { include_unstaged } => {
                if *include_unstaged {
                    write!(f, "staged and unstaged changes")
                } else {
                    write!(f, "staged changes")
                }
            }
            Self::Commit { commit_id } => write!(f, "commit {commit_id}"),
            Self::Range { from, to } => write!(f, "changes from {from} to {to}"),
            Self::Changelog {
                from,
                to,
                version_name,
                date,
            } => {
                let version_str = version_name
                    .as_ref()
                    .map_or_else(|| "unreleased".to_string(), |v| format!("v{v}"));
                write!(f, "changelog {version_str} ({date}) from {from} to {to}")
            }
            Self::Amend { .. } => write!(f, "amending previous commit"),
            Self::Discover => write!(f, "auto-discovered changes"),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_for_gen() {
        let ctx = TaskContext::for_gen();
        assert!(matches!(
            ctx,
            TaskContext::Staged {
                include_unstaged: false
            }
        ));
    }

    #[test]
    fn test_review_staged_only() {
        let ctx = TaskContext::for_review(None, None, None, false).expect("should succeed");
        assert!(matches!(
            ctx,
            TaskContext::Staged {
                include_unstaged: false
            }
        ));
    }

    #[test]
    fn test_review_with_unstaged() {
        let ctx = TaskContext::for_review(None, None, None, true).expect("should succeed");
        assert!(matches!(
            ctx,
            TaskContext::Staged {
                include_unstaged: true
            }
        ));
    }

    #[test]
    fn test_review_single_commit() {
        let ctx = TaskContext::for_review(Some("abc123".to_string()), None, None, false)
            .expect("should succeed");
        assert!(matches!(ctx, TaskContext::Commit { commit_id } if commit_id == "abc123"));
    }

    #[test]
    fn test_review_range() {
        let ctx = TaskContext::for_review(
            None,
            Some("main".to_string()),
            Some("feature".to_string()),
            false,
        )
        .expect("should succeed");
        assert!(
            matches!(ctx, TaskContext::Range { from, to } if from == "main" && to == "feature")
        );
    }

    #[test]
    fn test_review_to_only_defaults_from_explicit_base() {
        let ctx = TaskContext::for_review_with_base(
            None,
            None,
            Some("feature".to_string()),
            false,
            "trunk",
        )
        .expect("should succeed");
        assert!(
            matches!(ctx, TaskContext::Range { from, to } if from == "trunk" && to == "feature")
        );
    }

    #[test]
    fn test_review_from_without_to_fails() {
        let result = TaskContext::for_review(None, Some("main".to_string()), None, false);
        assert!(result.is_err());
        assert!(
            result
                .expect_err("should be err")
                .to_string()
                .contains("--to")
        );
    }

    #[test]
    fn test_review_commit_with_range_fails() {
        // commit + from + to should fail as mutually exclusive
        let result = TaskContext::for_review(
            Some("abc123".to_string()),
            Some("main".to_string()),
            Some("feature".to_string()),
            false,
        );
        assert!(result.is_err());
        assert!(
            result
                .expect_err("should be err")
                .to_string()
                .contains("mutually exclusive")
        );
    }

    #[test]
    fn test_review_unstaged_with_range_fails() {
        let result = TaskContext::for_review(
            None,
            Some("main".to_string()),
            Some("feature".to_string()),
            true,
        );
        assert!(result.is_err());
        assert!(
            result
                .expect_err("should be err")
                .to_string()
                .contains("include-unstaged")
        );
    }

    #[test]
    fn test_pr_defaults() {
        let ctx = TaskContext::for_pr_with_base(None, None, "trunk");
        assert!(matches!(ctx, TaskContext::Range { from, to } if from == "trunk" && to == "HEAD"));
    }

    #[test]
    fn test_pr_from_only() {
        let ctx = TaskContext::for_pr(Some("develop".to_string()), None);
        assert!(
            matches!(ctx, TaskContext::Range { from, to } if from == "develop" && to == "HEAD")
        );
    }

    #[test]
    fn test_changelog() {
        let ctx = TaskContext::for_changelog(
            "v1.0.0".to_string(),
            None,
            Some("1.1.0".to_string()),
            Some("2025-01-15".to_string()),
        );
        assert!(matches!(
            ctx,
            TaskContext::Changelog { from, to, version_name, date }
                if from == "v1.0.0" && to == "HEAD"
                && version_name == Some("1.1.0".to_string())
                && date == "2025-01-15"
        ));
    }

    #[test]
    fn test_changelog_default_date() {
        let ctx = TaskContext::for_changelog("v1.0.0".to_string(), None, None, None);
        // Should use today's date
        if let TaskContext::Changelog { date, .. } = ctx {
            assert!(!date.is_empty());
            assert!(date.contains('-')); // YYYY-MM-DD format
        } else {
            panic!("Expected Changelog variant");
        }
    }

    #[test]
    fn test_diff_hint() {
        let staged = TaskContext::for_gen();
        assert!(staged.diff_hint().contains("staged"));

        let commit = TaskContext::Commit {
            commit_id: "abc".to_string(),
        };
        assert!(commit.diff_hint().contains("abc^1"));

        let range = TaskContext::Range {
            from: "main".to_string(),
            to: "dev".to_string(),
        };
        assert!(range.diff_hint().contains("main"));
        assert!(range.diff_hint().contains("dev"));

        let amend = TaskContext::for_amend("Fix bug".to_string());
        assert!(amend.diff_hint().contains("HEAD^1"));
    }

    #[test]
    fn test_amend_context() {
        let ctx = TaskContext::for_amend("Initial commit message".to_string());
        assert!(ctx.is_amend());
        assert_eq!(ctx.original_message(), Some("Initial commit message"));
        assert!(!ctx.is_range());
        assert!(!ctx.includes_unstaged());
    }

    #[test]
    fn test_amend_display() {
        let ctx = TaskContext::for_amend("Fix bug".to_string());
        assert_eq!(format!("{ctx}"), "amending previous commit");
    }
}