mutiny-diff 0.1.22

TUI git diff viewer with worktree management
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
use std::collections::BTreeMap;

use serde::{Deserialize, Serialize};

/// Category of an annotation for structured agent feedback.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum AnnotationCategory {
    Bug,
    Style,
    Performance,
    Security,
    Suggestion,
    Question,
    Nitpick,
}

impl AnnotationCategory {
    pub fn label(&self) -> &'static str {
        match self {
            Self::Bug => "Bug",
            Self::Style => "Style",
            Self::Performance => "Perf",
            Self::Security => "Security",
            Self::Suggestion => "Suggestion",
            Self::Question => "Question",
            Self::Nitpick => "Nitpick",
        }
    }

    pub fn shortcut(&self) -> char {
        match self {
            Self::Bug => 'b',
            Self::Style => 's',
            Self::Performance => 'p',
            Self::Security => 'x',
            Self::Suggestion => 'g',
            Self::Question => 'q',
            Self::Nitpick => 'n',
        }
    }

    pub fn all() -> &'static [AnnotationCategory] {
        &[
            Self::Bug,
            Self::Style,
            Self::Performance,
            Self::Security,
            Self::Suggestion,
            Self::Question,
            Self::Nitpick,
        ]
    }
}

/// Severity level of an annotation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum AnnotationSeverity {
    Critical,
    Major,
    Minor,
    Info,
}

impl AnnotationSeverity {
    pub fn label(&self) -> &'static str {
        match self {
            Self::Critical => "Critical",
            Self::Major => "Major",
            Self::Minor => "Minor",
            Self::Info => "Info",
        }
    }

    pub fn shortcut(&self) -> char {
        match self {
            Self::Critical => 'c',
            Self::Major => 'M',
            Self::Minor => 'm',
            Self::Info => 'i',
        }
    }

    pub fn all() -> &'static [AnnotationSeverity] {
        &[Self::Critical, Self::Major, Self::Minor, Self::Info]
    }
}

/// A file path + line ranges that anchor an annotation to specific diff lines.
/// Stores old-file and new-file ranges separately so the LLM prompt can
/// distinguish between deleted, added, and context lines.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LineAnchor {
    pub file_path: String,
    pub old_range: Option<(u32, u32)>, // (start, end) in old file
    pub new_range: Option<(u32, u32)>, // (start, end) in new file
}

/// A quick-reaction score attached to a line or range.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LineScore {
    pub file_path: String,
    pub old_range: Option<(u32, u32)>,
    pub new_range: Option<(u32, u32)>,
    pub score: u8, // 1-5
    pub created_at: String,
}

impl LineScore {
    /// Representative line for sorting.
    pub fn sort_line(&self) -> u32 {
        self.new_range
            .map(|(s, _)| s)
            .or(self.old_range.map(|(s, _)| s))
            .unwrap_or(0)
    }
}

impl LineAnchor {
    /// A single representative line number for sorting/navigation.
    /// Prefers new-file start, falls back to old-file start.
    pub fn sort_line(&self) -> u32 {
        self.new_range
            .map(|(s, _)| s)
            .or(self.old_range.map(|(s, _)| s))
            .unwrap_or(0)
    }

    /// Whether this anchor covers a given old-file line number.
    pub fn covers_old(&self, lineno: u32) -> bool {
        self.old_range
            .is_some_and(|(s, e)| lineno >= s && lineno <= e)
    }

    /// Whether this anchor covers a given new-file line number.
    pub fn covers_new(&self, lineno: u32) -> bool {
        self.new_range
            .is_some_and(|(s, e)| lineno >= s && lineno <= e)
    }

    /// Whether this anchor covers the given old/new line number pair.
    /// Returns true if either side matches (when present).
    pub fn covers(&self, old_lineno: Option<u32>, new_lineno: Option<u32>) -> bool {
        if let Some(n) = new_lineno {
            if self.covers_new(n) {
                return true;
            }
        }
        if let Some(n) = old_lineno {
            if self.covers_old(n) {
                return true;
            }
        }
        false
    }

    /// Check if this anchor's ranges overlap with the given ranges.
    fn overlaps(&self, old_range: Option<(u32, u32)>, new_range: Option<(u32, u32)>) -> bool {
        let old_overlaps = match (self.old_range, old_range) {
            (Some((s1, e1)), Some((s2, e2))) => s1 <= e2 && s2 <= e1,
            _ => false,
        };
        let new_overlaps = match (self.new_range, new_range) {
            (Some((s1, e1)), Some((s2, e2))) => s1 <= e2 && s2 <= e1,
            _ => false,
        };
        old_overlaps || new_overlaps
    }

    /// Check if this anchor exactly matches the given ranges.
    fn matches(&self, old_range: Option<(u32, u32)>, new_range: Option<(u32, u32)>) -> bool {
        self.old_range == old_range && self.new_range == new_range
    }
}

/// A single annotation attached to a range of diff lines.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Annotation {
    pub anchor: LineAnchor,
    pub comment: String,
    pub created_at: String,
    #[serde(default = "default_category")]
    pub category: AnnotationCategory,
    #[serde(default = "default_severity")]
    pub severity: AnnotationSeverity,
}

fn default_category() -> AnnotationCategory {
    AnnotationCategory::Suggestion
}

fn default_severity() -> AnnotationSeverity {
    AnnotationSeverity::Minor
}

/// State for all annotations in the current session.
/// Keyed by file path for efficient lookup.
#[derive(Debug, Default)]
pub struct AnnotationState {
    /// Map of file_path → list of annotations on that file.
    pub annotations: BTreeMap<String, Vec<Annotation>>,
    /// Quick-reaction scores (separate from annotations).
    pub scores: BTreeMap<String, Vec<LineScore>>,
}

impl AnnotationState {
    /// Add an annotation for a file.
    pub fn add(&mut self, annotation: Annotation) {
        let key = annotation.anchor.file_path.clone();
        self.annotations.entry(key).or_default().push(annotation);
    }

    /// Check if any annotation covers the given line numbers in a file.
    pub fn has_annotation_at(
        &self,
        file_path: &str,
        old_lineno: Option<u32>,
        new_lineno: Option<u32>,
    ) -> bool {
        if let Some(anns) = self.annotations.get(file_path) {
            anns.iter().any(|a| a.anchor.covers(old_lineno, new_lineno))
        } else {
            false
        }
    }

    /// Delete all annotations overlapping the given ranges in a file.
    pub fn delete_at(
        &mut self,
        file_path: &str,
        old_range: Option<(u32, u32)>,
        new_range: Option<(u32, u32)>,
    ) {
        if let Some(anns) = self.annotations.get_mut(file_path) {
            anns.retain(|a| !a.anchor.overlaps(old_range, new_range));
            if anns.is_empty() {
                self.annotations.remove(file_path);
            }
        }
    }

    /// Get all annotations as a flat, sorted list (by file then sort_line).
    pub fn all_sorted(&self) -> Vec<&Annotation> {
        let mut result: Vec<&Annotation> =
            self.annotations.values().flat_map(|v| v.iter()).collect();
        result.sort_by_key(|a| (&a.anchor.file_path, a.anchor.sort_line()));
        result
    }

    /// Return all annotations whose range covers the given line numbers.
    pub fn annotations_overlapping(
        &self,
        file_path: &str,
        old_lineno: Option<u32>,
        new_lineno: Option<u32>,
    ) -> Vec<&Annotation> {
        if let Some(anns) = self.annotations.get(file_path) {
            anns.iter()
                .filter(|a| a.anchor.covers(old_lineno, new_lineno))
                .collect()
        } else {
            Vec::new()
        }
    }

    /// Delete a specific annotation matching by anchor ranges + comment text.
    pub fn delete_annotation(
        &mut self,
        file_path: &str,
        old_range: Option<(u32, u32)>,
        new_range: Option<(u32, u32)>,
        comment: &str,
    ) {
        if let Some(anns) = self.annotations.get_mut(file_path) {
            if let Some(pos) = anns
                .iter()
                .position(|a| a.anchor.matches(old_range, new_range) && a.comment == comment)
            {
                anns.remove(pos);
            }
            if anns.is_empty() {
                self.annotations.remove(file_path);
            }
        }
    }

    /// Update a specific annotation's comment text.
    pub fn update_comment(
        &mut self,
        file_path: &str,
        old_range: Option<(u32, u32)>,
        new_range: Option<(u32, u32)>,
        old_comment: &str,
        new_comment: &str,
    ) {
        if let Some(anns) = self.annotations.get_mut(file_path) {
            if let Some(ann) = anns
                .iter_mut()
                .find(|a| a.anchor.matches(old_range, new_range) && a.comment == old_comment)
            {
                ann.comment = new_comment.to_string();
            }
        }
    }

    /// Total count of annotations.
    pub fn count(&self) -> usize {
        self.annotations.values().map(|v| v.len()).sum()
    }

    /// Find the next annotation after the given file/line position.
    /// Returns (file_path, sort_line) of the next annotation.
    pub fn next_after(&self, file_path: &str, lineno: u32) -> Option<(&str, u32)> {
        let sorted = self.all_sorted();
        for ann in &sorted {
            let sl = ann.anchor.sort_line();
            if ann.anchor.file_path.as_str() > file_path
                || (ann.anchor.file_path == file_path && sl > lineno)
            {
                return Some((&ann.anchor.file_path, sl));
            }
        }
        // Wrap around to first
        sorted
            .first()
            .map(|a| (a.anchor.file_path.as_str(), a.anchor.sort_line()))
    }

    /// Find the previous annotation before the given file/line position.
    pub fn prev_before(&self, file_path: &str, lineno: u32) -> Option<(&str, u32)> {
        let sorted = self.all_sorted();
        for ann in sorted.iter().rev() {
            let sl = ann.anchor.sort_line();
            if ann.anchor.file_path.as_str() < file_path
                || (ann.anchor.file_path == file_path && sl < lineno)
            {
                return Some((&ann.anchor.file_path, sl));
            }
        }
        // Wrap around to last
        sorted
            .last()
            .map(|a| (a.anchor.file_path.as_str(), a.anchor.sort_line()))
    }

    /// Set a score for a line/range. Replaces any existing score at the same position.
    pub fn set_score(&mut self, score: LineScore) {
        let key = score.file_path.clone();
        let entries = self.scores.entry(key).or_default();
        // Remove any existing score at the same position
        entries.retain(|s| s.old_range != score.old_range || s.new_range != score.new_range);
        entries.push(score);
    }

    /// Remove score at a position.
    pub fn remove_score(
        &mut self,
        file_path: &str,
        old_range: Option<(u32, u32)>,
        new_range: Option<(u32, u32)>,
    ) {
        if let Some(scores) = self.scores.get_mut(file_path) {
            scores.retain(|s| s.old_range != old_range || s.new_range != new_range);
            if scores.is_empty() {
                self.scores.remove(file_path);
            }
        }
    }

    /// Get score at a specific line position.
    pub fn score_at(
        &self,
        file_path: &str,
        old_lineno: Option<u32>,
        new_lineno: Option<u32>,
    ) -> Option<u8> {
        self.scores.get(file_path).and_then(|scores| {
            scores.iter().find_map(|s| {
                let covers_new = matches!(
                    (new_lineno, s.new_range),
                    (Some(n), Some((start, end))) if n >= start && n <= end
                );
                let covers_old = matches!(
                    (old_lineno, s.old_range),
                    (Some(n), Some((start, end))) if n >= start && n <= end
                );
                let covers = covers_new || covers_old;
                if covers {
                    Some(s.score)
                } else {
                    None
                }
            })
        })
    }

    /// Get all scores as a flat sorted list.
    pub fn all_scores_sorted(&self) -> Vec<&LineScore> {
        let mut result: Vec<&LineScore> = self.scores.values().flat_map(|v| v.iter()).collect();
        result.sort_by_key(|s| (&s.file_path, s.sort_line()));
        result
    }

    /// Total score count.
    pub fn score_count(&self) -> usize {
        self.scores.values().map(|v| v.len()).sum()
    }

    /// Count files that have any feedback (annotations and/or scores).
    pub fn files_with_annotations(&self) -> usize {
        let mut files = std::collections::BTreeSet::new();
        files.extend(self.annotations.keys().map(String::as_str));
        files.extend(self.scores.keys().map(String::as_str));
        files.len()
    }
}