agentty 0.14.1

Agentty is an ADE (Agentic Development Environment) for structured, controllable AI-assisted software development.
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
use ag_forge::{ReviewComment, ReviewCommentSnapshot, ReviewCommentThread};

use super::app_mode::{ReviewCommentAction, ReviewCommentActionSelection};

/// One row in the grouped review-comment selector projection.
pub(crate) enum GroupedReviewCommentRow<'a> {
    /// Selectable standalone comment or inline thread.
    Entry(ReviewCommentEntry<'a>),
    /// Non-selectable heading rendered before one populated group.
    GroupLabel(&'static str),
}

/// One selectable review-comment entry and its detail source.
#[derive(Clone, Copy)]
pub(crate) enum ReviewCommentEntry<'a> {
    /// Review-request-wide discussion comment without an inline thread ID.
    General(&'a ReviewComment),
    /// Forge review thread attached to a file or line range.
    Thread(&'a ReviewCommentThread),
}

/// Returns the complete selector projection in unresolved, outdated,
/// resolved, then standalone order, including labels for each populated
/// group.
pub(crate) fn grouped_review_comment_rows(
    snapshot: &ReviewCommentSnapshot,
) -> Vec<GroupedReviewCommentRow<'_>> {
    let mut rows = Vec::with_capacity(
        snapshot
            .threads
            .len()
            .saturating_add(snapshot.pr_level_comments.len())
            .saturating_add(4),
    );
    append_group_rows(
        &mut rows,
        "Unresolved",
        snapshot
            .threads
            .iter()
            .filter(|thread| !thread.is_resolved && thread.is_outdated != Some(true))
            .map(ReviewCommentEntry::Thread),
    );
    append_group_rows(
        &mut rows,
        "Outdated",
        snapshot
            .threads
            .iter()
            .filter(|thread| !thread.is_resolved && thread.is_outdated == Some(true))
            .map(ReviewCommentEntry::Thread),
    );
    append_group_rows(
        &mut rows,
        "Resolved",
        snapshot
            .threads
            .iter()
            .filter(|thread| thread.is_resolved)
            .map(ReviewCommentEntry::Thread),
    );
    append_group_rows(
        &mut rows,
        "Standalone",
        snapshot
            .pr_level_comments
            .iter()
            .map(ReviewCommentEntry::General),
    );

    rows
}

/// Returns only selectable entries from one materialized grouped projection.
pub(crate) fn selectable_entries<'rows, 'snapshot>(
    rows: &'rows [GroupedReviewCommentRow<'snapshot>],
) -> impl Iterator<Item = ReviewCommentEntry<'snapshot>> + 'rows
where
    'snapshot: 'rows,
{
    rows.iter().filter_map(|row| match row {
        GroupedReviewCommentRow::Entry(entry) => Some(*entry),
        GroupedReviewCommentRow::GroupLabel(_) => None,
    })
}

/// Returns the selected standalone comment or inline thread from one
/// materialized grouped projection.
pub(crate) fn selected_entry<'snapshot>(
    rows: &[GroupedReviewCommentRow<'snapshot>],
    selected_comment_index: usize,
) -> Option<ReviewCommentEntry<'snapshot>> {
    selectable_entries(rows).nth(selected_comment_index)
}

/// Returns the forge-native identifier for the selected grouped thread row.
pub(crate) fn selected_thread_id(
    snapshot: &ReviewCommentSnapshot,
    selected_comment_index: usize,
) -> Option<&str> {
    let rows = grouped_review_comment_rows(snapshot);

    selected_entry(&rows, selected_comment_index).and_then(|entry| match entry {
        ReviewCommentEntry::General(_) => None,
        ReviewCommentEntry::Thread(thread) => Some(thread.id.as_str()),
    })
}

/// Returns the selected thread identifier only when the thread is actionable.
pub(crate) fn selected_actionable_thread_id(
    snapshot: &ReviewCommentSnapshot,
    selected_comment_index: usize,
) -> Option<&str> {
    let rows = grouped_review_comment_rows(snapshot);

    selected_entry(&rows, selected_comment_index).and_then(|entry| match entry {
        ReviewCommentEntry::Thread(thread) if thread.is_actionable() => Some(thread.id.as_str()),
        ReviewCommentEntry::General(_) | ReviewCommentEntry::Thread(_) => None,
    })
}

/// Returns the action selected for one forge thread, when present.
pub(crate) fn selected_action(
    selections: &[ReviewCommentActionSelection],
    thread_id: &str,
) -> Option<ReviewCommentAction> {
    selections
        .iter()
        .find(|selection| selection.thread_id == thread_id)
        .map(|selection| selection.action)
}

/// Toggles one thread's batch action, replacing a different existing action.
pub(crate) fn toggle_action(
    selections: &mut Vec<ReviewCommentActionSelection>,
    thread_id: &str,
    action: ReviewCommentAction,
) {
    if let Some(selection_index) = selections
        .iter()
        .position(|selection| selection.thread_id == thread_id)
    {
        if selections[selection_index].action == action {
            selections.remove(selection_index);
        } else {
            selections[selection_index].action = action;
        }

        return;
    }

    selections.push(ReviewCommentActionSelection {
        action,
        thread_id: thread_id.to_string(),
    });
}

/// Drops selections for threads that are no longer actionable after refresh.
pub(crate) fn retain_actionable_selections(
    selections: &mut Vec<ReviewCommentActionSelection>,
    snapshot: &ReviewCommentSnapshot,
) {
    selections.retain(|selection| {
        snapshot
            .threads
            .iter()
            .any(|thread| thread.id == selection.thread_id && thread.is_actionable())
    });
}

/// Retargets a positional selection to the same forge thread in an updated
/// snapshot, falling back to the nearest valid row if the thread disappeared.
pub(crate) fn retarget_selected_index(
    previous_snapshot: Option<&ReviewCommentSnapshot>,
    previous_selected_index: usize,
    updated_snapshot: &ReviewCommentSnapshot,
) -> usize {
    let selected_thread_id = previous_snapshot
        .and_then(|snapshot| selected_thread_id(snapshot, previous_selected_index));
    let updated_rows = grouped_review_comment_rows(updated_snapshot);
    if let Some(updated_index) = selected_thread_id.and_then(|selected_thread_id| {
        selectable_entries(&updated_rows).position(
            |entry| matches!(entry, ReviewCommentEntry::Thread(thread) if thread.id == selected_thread_id),
        )
    }) {
        return updated_index;
    }

    let updated_item_count = updated_snapshot
        .threads
        .len()
        .saturating_add(updated_snapshot.pr_level_comments.len());

    previous_selected_index.min(updated_item_count.saturating_sub(1))
}

/// Adds one heading and its entries only when the group is populated.
fn append_group_rows<'a>(
    rows: &mut Vec<GroupedReviewCommentRow<'a>>,
    label: &'static str,
    entries: impl Iterator<Item = ReviewCommentEntry<'a>>,
) {
    let mut group_has_entries = false;
    for entry in entries {
        if !group_has_entries {
            rows.push(GroupedReviewCommentRow::GroupLabel(label));
            group_has_entries = true;
        }
        rows.push(GroupedReviewCommentRow::Entry(entry));
    }
}

#[cfg(test)]
mod tests {
    use ag_forge::{ReviewComment, ReviewCommentAnchorSide};

    use super::*;

    #[test]
    fn test_grouped_review_comment_rows_include_populated_labels_and_entries() {
        // Arrange
        let mut outdated = thread("outdated", false);
        outdated.is_outdated = Some(true);
        let mut resolved_outdated = thread("resolved-outdated", true);
        resolved_outdated.is_outdated = Some(true);
        let mut snapshot = snapshot_with_threads([
            thread("resolved", true),
            outdated,
            resolved_outdated,
            thread("unresolved", false),
        ]);
        snapshot.pr_level_comments.push(ReviewComment {
            author: "reviewer".to_string(),
            body: "Standalone comment".to_string(),
        });

        // Act
        let rows = grouped_review_comment_rows(&snapshot);
        let labels_and_entries = rows
            .iter()
            .map(|row| match row {
                GroupedReviewCommentRow::Entry(ReviewCommentEntry::General(comment)) => {
                    format!("comment:{}", comment.body)
                }
                GroupedReviewCommentRow::Entry(ReviewCommentEntry::Thread(thread)) => {
                    format!("thread:{}", thread.id)
                }
                GroupedReviewCommentRow::GroupLabel(label) => format!("label:{label}"),
            })
            .collect::<Vec<_>>();

        // Assert
        assert_eq!(
            labels_and_entries,
            vec![
                "label:Unresolved",
                "thread:unresolved",
                "label:Outdated",
                "thread:outdated",
                "label:Resolved",
                "thread:resolved",
                "thread:resolved-outdated",
                "label:Standalone",
                "comment:Standalone comment",
            ]
        );
    }

    #[test]
    fn test_grouped_review_comment_rows_omit_empty_group_labels() {
        // Arrange
        let snapshot = snapshot_with_threads([thread("unresolved", false)]);

        // Act
        let labels = grouped_review_comment_rows(&snapshot)
            .into_iter()
            .filter_map(|row| match row {
                GroupedReviewCommentRow::GroupLabel(label) => Some(label),
                GroupedReviewCommentRow::Entry(_) => None,
            })
            .collect::<Vec<_>>();

        // Assert
        assert_eq!(labels, vec!["Unresolved"]);
    }

    #[test]
    fn test_selectable_entries_reuses_materialized_grouped_rows() {
        // Arrange
        let mut snapshot = snapshot_with_threads([thread("thread", false)]);
        snapshot.pr_level_comments.push(ReviewComment {
            author: "reviewer".to_string(),
            body: "Standalone comment".to_string(),
        });
        let rows = grouped_review_comment_rows(&snapshot);

        // Act
        let selected_entries = selectable_entries(&rows).collect::<Vec<_>>();

        // Assert
        assert!(matches!(
            selected_entries[0],
            ReviewCommentEntry::Thread(thread) if thread.id == "thread"
        ));
        assert!(matches!(
            selected_entries[1],
            ReviewCommentEntry::General(comment) if comment.body == "Standalone comment"
        ));
    }

    #[test]
    fn test_retarget_selected_index_follows_thread_between_resolution_groups() {
        // Arrange
        let previous_snapshot =
            snapshot_with_threads([thread("selected", false), thread("other", false)]);
        let updated_snapshot =
            snapshot_with_threads([thread("selected", true), thread("other", false)]);

        // Act
        let updated_index = retarget_selected_index(Some(&previous_snapshot), 0, &updated_snapshot);

        // Assert
        assert_eq!(updated_index, 1);
        assert_eq!(
            selected_thread_id(&updated_snapshot, updated_index),
            Some("selected")
        );
    }

    #[test]
    fn test_retarget_selected_index_clamps_when_selected_thread_disappears() {
        // Arrange
        let previous_snapshot =
            snapshot_with_threads([thread("first", false), thread("selected", false)]);
        let updated_snapshot = snapshot_with_threads([thread("remaining", false)]);

        // Act
        let updated_index = retarget_selected_index(Some(&previous_snapshot), 1, &updated_snapshot);
        let empty_index = retarget_selected_index(None, 4, &ReviewCommentSnapshot::default());

        // Assert
        assert_eq!(updated_index, 0);
        assert_eq!(empty_index, 0);
    }

    #[test]
    fn test_toggle_action_adds_replaces_and_removes_thread_selection() {
        // Arrange
        let mut selections = Vec::new();

        // Act
        toggle_action(&mut selections, "thread", ReviewCommentAction::Address);
        toggle_action(&mut selections, "thread", ReviewCommentAction::Deny);
        let replaced = selections.clone();
        toggle_action(&mut selections, "thread", ReviewCommentAction::Deny);

        // Assert
        assert_eq!(
            replaced,
            vec![ReviewCommentActionSelection {
                action: ReviewCommentAction::Deny,
                thread_id: "thread".to_string(),
            }]
        );
        assert!(selections.is_empty());
    }

    #[test]
    fn test_retain_actionable_selections_removes_stale_threads() {
        // Arrange
        let snapshot = snapshot_with_threads([thread("current", false), thread("resolved", true)]);
        let mut selections = vec![
            ReviewCommentActionSelection {
                action: ReviewCommentAction::Address,
                thread_id: "current".to_string(),
            },
            ReviewCommentActionSelection {
                action: ReviewCommentAction::Deny,
                thread_id: "resolved".to_string(),
            },
            ReviewCommentActionSelection {
                action: ReviewCommentAction::Address,
                thread_id: "missing".to_string(),
            },
        ];

        // Act
        retain_actionable_selections(&mut selections, &snapshot);

        // Assert
        assert_eq!(selections.len(), 1);
        assert_eq!(
            selected_action(&selections, "current"),
            Some(ReviewCommentAction::Address)
        );
        assert_eq!(selected_action(&selections, "resolved"), None);
    }

    /// Builds a snapshot from inline threads without standalone comments.
    fn snapshot_with_threads<const THREAD_COUNT: usize>(
        threads: [ReviewCommentThread; THREAD_COUNT],
    ) -> ReviewCommentSnapshot {
        ReviewCommentSnapshot {
            pr_level_comments: Vec::new(),
            threads: Vec::from(threads),
        }
    }

    /// Builds one current or resolved inline thread.
    fn thread(id: &str, is_resolved: bool) -> ReviewCommentThread {
        ReviewCommentThread {
            anchor_side: ReviewCommentAnchorSide::New,
            comments: vec![ReviewComment {
                author: "reviewer".to_string(),
                body: "Review comment".to_string(),
            }],
            id: id.to_string(),
            is_outdated: Some(false),
            is_resolved,
            line: Some(1),
            path: "src/main.rs".to_string(),
            start_line: None,
        }
    }
}