agentty 0.12.5

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
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
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
use std::collections::BTreeMap;
use std::sync::Arc;

use ratatui::Frame;
use ratatui::layout::Rect;
use ratatui::style::Style;
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Borders, List, ListItem, ListState};

use crate::ui::diff_util::{DiffLine, DiffLineKind, FileTreeItem};
use crate::ui::{Component, style};

const DIFF_GIT_FILE_HEADER_PREFIX: &str = "diff --git";
const DIFF_GIT_PATH_PREFIX: &str = "diff --git a/";
const DIFF_GIT_PATH_SEPARATOR: &str = " b/";
const DIFF_GIT_FALLBACK_PREFIX: &str = "diff --git ";
const FILE_EXPLORER_TITLE: &str = " Files ";
const NO_FILES_LABEL: &str = "No files";
const PATH_SEGMENT_SEPARATOR: char = '/';
const FOLDER_SUFFIX: &str = "/";
const TREE_BRANCH_MIDDLE: &str = "";
const TREE_BRANCH_LAST: &str = "";
const TREE_PREFIX_CONTINUATION: &str = "";
const TREE_PREFIX_SPACER: &str = "  ";
const RENAME_ORIGIN_PREFIX: &str = " <- ";
const ROOT_TREE_PREFIX: &str = "";

/// Diff file explorer panel rendering the changed file list.
pub struct FileExplorer {
    file_list_lines: Arc<[Line<'static>]>,
    selected_index: usize,
}

/// A file entry in the tree along with optional rename origin metadata.
#[derive(Clone)]
struct FileLeaf {
    name: String,
    rename_from: Option<String>,
}

/// Tree node containing nested folders and files for a diff file list.
#[derive(Default)]
struct FileTreeNode {
    files: Vec<FileLeaf>,
    folders: BTreeMap<String, FileTreeNode>,
}

/// Parsed and normalized file path details extracted from a diff header.
#[derive(Debug)]
struct ParsedPath {
    path_segments: Vec<String>,
    rename_from: Option<String>,
}

impl FileTreeNode {
    /// Inserts a parsed file path into the tree, creating parent folders as
    /// needed.
    fn insert(&mut self, parsed_path: ParsedPath) {
        let ParsedPath {
            path_segments,
            rename_from,
        } = parsed_path;
        let Some((file_name, folder_segments)) = path_segments.split_last() else {
            return;
        };

        let mut current_node = self;
        for folder_name in folder_segments {
            current_node = current_node.folders.entry(folder_name.clone()).or_default();
        }

        current_node.files.push(FileLeaf {
            name: file_name.clone(),
            rename_from,
        });
    }

    /// Sorts files and all descendants to keep rendering deterministic.
    fn sort_recursive(&mut self) {
        self.files.sort_by(|left, right| left.name.cmp(&right.name));

        for child in self.folders.values_mut() {
            child.sort_recursive();
        }
    }
}

impl FileExplorer {
    /// Creates a new file explorer component from parsed diff lines.
    pub fn new(parsed_lines: &[DiffLine<'_>]) -> Self {
        let (file_list_lines, _) = Self::file_tree(parsed_lines);

        Self {
            file_list_lines: Arc::from(file_list_lines),
            selected_index: 0,
        }
    }

    /// Creates a file explorer component from cached rendered tree lines.
    pub(crate) fn from_cached_lines(file_list_lines: Arc<[Line<'static>]>) -> Self {
        Self {
            file_list_lines,
            selected_index: 0,
        }
    }

    /// Sets the selected item index in the file tree.
    #[must_use]
    pub fn selected_index(mut self, index: usize) -> Self {
        self.selected_index = index;
        self
    }

    /// Returns the next selected index for a file list of `item_count` items.
    ///
    /// Selection wraps to the first item when moving forward from the last
    /// item. When `item_count` is zero, `current_index` is returned unchanged.
    pub fn next_selected_index(current_index: usize, item_count: usize) -> usize {
        if item_count == 0 {
            return current_index;
        }

        let normalized_index = Self::normalize_selected_index(current_index, item_count);

        (normalized_index + 1) % item_count
    }

    /// Returns the previous selected index for a file list of `item_count`
    /// items.
    ///
    /// Selection wraps to the last item when moving backward from the first
    /// item. When `item_count` is zero, `current_index` is returned unchanged.
    pub fn previous_selected_index(current_index: usize, item_count: usize) -> usize {
        if item_count == 0 {
            return current_index;
        }

        let normalized_index = Self::normalize_selected_index(current_index, item_count);

        if normalized_index == 0 {
            item_count - 1
        } else {
            normalized_index - 1
        }
    }

    /// Returns the number of items (files and folders) in the explorer list.
    pub fn count_items(parsed_lines: &[DiffLine<'_>]) -> usize {
        let (lines, _) = Self::file_tree(parsed_lines);

        lines.len()
    }

    /// Returns the [`FileTreeItem`] list for the given parsed diff lines.
    ///
    /// Each entry corresponds one-to-one to a rendered tree line so the
    /// selected index can be used to look up the matching item.
    pub fn file_tree_items(parsed_lines: &[DiffLine<'_>]) -> Vec<FileTreeItem> {
        let (_, items) = Self::file_tree(parsed_lines);

        items
    }

    /// Builds the rendered file tree lines and matching selection items for
    /// one parsed diff snapshot.
    pub(crate) fn file_tree(
        parsed_lines: &[DiffLine<'_>],
    ) -> (Vec<Line<'static>>, Vec<FileTreeItem>) {
        Self::build_tree(parsed_lines)
    }

    /// Builds the tree display lines and parallel [`FileTreeItem`] list from
    /// parsed diff headers.
    fn build_tree(parsed_lines: &[DiffLine<'_>]) -> (Vec<Line<'static>>, Vec<FileTreeItem>) {
        let mut file_tree = FileTreeNode::default();

        for diff_line in parsed_lines {
            if diff_line.kind != DiffLineKind::FileHeader
                || !diff_line.content.starts_with(DIFF_GIT_FILE_HEADER_PREFIX)
            {
                continue;
            }

            if let Some(parsed_path) = Self::parse_path(diff_line.content) {
                file_tree.insert(parsed_path);
            }
        }

        let mut file_list_lines = Vec::new();
        let mut items = Vec::new();
        file_tree.sort_recursive();
        Self::append_tree_lines(
            &file_tree,
            ROOT_TREE_PREFIX,
            ROOT_TREE_PREFIX,
            &mut file_list_lines,
            &mut items,
        );

        if file_list_lines.is_empty() {
            file_list_lines.push(Line::from(Span::styled(
                NO_FILES_LABEL,
                Style::default().fg(style::palette::text_subtle()),
            )));
        }

        (file_list_lines, items)
    }

    /// Clamps `current_index` to a valid list index for `item_count` items.
    fn normalize_selected_index(current_index: usize, item_count: usize) -> usize {
        current_index.min(item_count.saturating_sub(1))
    }

    /// Parses a diff header into a normalized path representation for tree
    /// insertion.
    fn parse_path(file_header_line: &str) -> Option<ParsedPath> {
        if let Some(stripped_header) = file_header_line.strip_prefix(DIFF_GIT_PATH_PREFIX) {
            if let Some((old_path, new_path)) = stripped_header.split_once(DIFF_GIT_PATH_SEPARATOR)
            {
                let path_segments = Self::split_path_segments(new_path);
                if path_segments.is_empty() {
                    return None;
                }

                let rename_from = if old_path == new_path {
                    None
                } else {
                    Some(old_path.to_string())
                };

                return Some(ParsedPath {
                    path_segments,
                    rename_from,
                });
            }

            return Some(ParsedPath {
                path_segments: vec![stripped_header.to_string()],
                rename_from: None,
            });
        }

        Some(ParsedPath {
            path_segments: vec![file_header_line.replace(DIFF_GIT_FALLBACK_PREFIX, "")],
            rename_from: None,
        })
    }

    /// Splits a repository-relative path into individual folder/file segments.
    fn split_path_segments(path: &str) -> Vec<String> {
        path.split(PATH_SEGMENT_SEPARATOR)
            .filter(|segment| !segment.is_empty())
            .map(ToString::to_string)
            .collect()
    }

    /// Appends a depth-first textual tree representation for the node and its
    /// children, while building a parallel [`FileTreeItem`] list.
    fn append_tree_lines(
        node: &FileTreeNode,
        prefix: &str,
        path_prefix: &str,
        lines: &mut Vec<Line<'static>>,
        items: &mut Vec<FileTreeItem>,
    ) {
        let total_children = node.folders.len() + node.files.len();
        let mut child_index = 0;

        for (folder_name, folder_node) in &node.folders {
            child_index += 1;
            let is_last_child = child_index == total_children;
            let branch_prefix = if is_last_child {
                TREE_BRANCH_LAST
            } else {
                TREE_BRANCH_MIDDLE
            };
            let line_text = format!("{prefix}{branch_prefix}{folder_name}{FOLDER_SUFFIX}");
            let folder_path = format!("{path_prefix}{folder_name}/");

            lines.push(Line::from(Span::styled(
                line_text,
                Style::default().fg(style::palette::warning()),
            )));
            items.push(FileTreeItem::Folder(folder_path.clone()));

            let child_prefix = if is_last_child {
                format!("{prefix}{TREE_PREFIX_SPACER}")
            } else {
                format!("{prefix}{TREE_PREFIX_CONTINUATION}")
            };

            Self::append_tree_lines(folder_node, &child_prefix, &folder_path, lines, items);
        }

        for file in &node.files {
            child_index += 1;
            let is_last_child = child_index == total_children;
            let branch_prefix = if is_last_child {
                TREE_BRANCH_LAST
            } else {
                TREE_BRANCH_MIDDLE
            };
            let file_name = format!("{prefix}{branch_prefix}{}", file.name);
            let file_path = format!("{path_prefix}{}", file.name);
            let mut spans = vec![Span::styled(
                file_name,
                Style::default().fg(style::palette::accent()),
            )];

            if let Some(rename_from) = &file.rename_from {
                spans.push(Span::styled(
                    format!("{RENAME_ORIGIN_PREFIX}{rename_from}"),
                    Style::default().fg(style::palette::text_subtle()),
                ));
            }

            lines.push(Line::from(spans));
            items.push(FileTreeItem::File(file_path));
        }
    }
}

impl Component for FileExplorer {
    fn render(&self, f: &mut Frame, area: Rect) {
        let items: Vec<ListItem> = self
            .file_list_lines
            .iter()
            .cloned()
            .map(ListItem::new)
            .collect();

        let list = List::new(items)
            .block(
                Block::default()
                    .borders(Borders::ALL)
                    .title(Span::styled(
                        FILE_EXPLORER_TITLE,
                        Style::default().fg(style::palette::accent()),
                    ))
                    .border_style(style::border_style()),
            )
            .highlight_style(Style::default().bg(style::palette::surface_selection()));

        let mut state = ListState::default();
        state.select(Some(self.selected_index));

        f.render_stateful_widget(list, area, &mut state);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::domain::theme::ColorTheme;

    #[test]
    fn test_render_uses_palette_border_for_file_explorer() {
        // Arrange
        let _theme_scope = style::scoped_active_theme(ColorTheme::Current);
        let parsed_lines = vec![DiffLine {
            kind: DiffLineKind::FileHeader,
            old_line: None,
            new_line: None,
            content: DIFF_SAME_PATH_HEADER,
        }];
        let backend = ratatui::backend::TestBackend::new(40, 10);
        let mut terminal = ratatui::Terminal::new(backend).expect("failed to create terminal");

        // Act
        terminal
            .draw(|frame| {
                FileExplorer::new(&parsed_lines).render(frame, frame.area());
            })
            .expect("failed to draw file explorer");

        // Assert
        let buffer = terminal.backend().buffer();
        let border_cell = &buffer.content()[0];
        assert_eq!(border_cell.symbol(), "");
        assert_eq!(border_cell.fg, style::palette::border());
    }

    const DIFF_SAME_PATH_HEADER: &str = "diff --git a/src/main.rs b/src/main.rs";
    const DIFF_RENAME_HEADER: &str = "diff --git a/src/old.rs b/src/new.rs";
    const DIFF_NONSTANDARD_HEADER: &str = "diff --git old/path new/path";
    const DIFF_README_HEADER: &str = "diff --git a/README.md b/README.md";
    const DIFF_NESTED_HEADER: &str =
        "diff --git a/src/ui/component/file_explorer.rs b/src/ui/component/file_explorer.rs";
    const EXPECTED_SRC_FOLDER_LINE: &str = "└ src/";
    const EXPECTED_MAIN_FILE_LINE: &str = "  └ main.rs";
    const EXPECTED_NEW_FILE_LINE: &str = "  └ new.rs";
    const EXPECTED_RENAME_LINE: &str = " <- src/old.rs";
    const EXPECTED_NONSTANDARD_LINE: &str = "└ old/path new/path";
    const EXPECTED_NESTED_TREE_LINES: [&str; 6] = [
        "├ src/",
        "│ ├ ui/",
        "│ │ └ component/",
        "│ │   └ file_explorer.rs",
        "│ └ main.rs",
        "└ README.md",
    ];
    const UNCHANGED_DIFF_LINE: &str = " unchanged";

    fn line_text(line: &Line<'static>) -> String {
        line.spans
            .iter()
            .map(|span| span.content.to_string())
            .collect()
    }

    #[test]
    fn test_file_list_lines_with_same_path() {
        // Arrange
        let parsed_lines = vec![DiffLine {
            kind: DiffLineKind::FileHeader,
            old_line: None,
            new_line: None,
            content: DIFF_SAME_PATH_HEADER,
        }];

        // Act
        let lines = FileExplorer::build_tree(&parsed_lines).0;

        // Assert
        assert_eq!(lines.len(), 2);
        assert_eq!(lines[0].spans[0].content, EXPECTED_SRC_FOLDER_LINE);
        assert_eq!(lines[1].spans[0].content, EXPECTED_MAIN_FILE_LINE);
    }

    #[test]
    fn test_next_selected_index_wraps_from_last_to_first() {
        // Arrange
        let current_index = 1;
        let item_count = 2;

        // Act
        let next_index = FileExplorer::next_selected_index(current_index, item_count);

        // Assert
        assert_eq!(next_index, 0);
    }

    #[test]
    fn test_previous_selected_index_wraps_from_first_to_last() {
        // Arrange
        let current_index = 0;
        let item_count = 2;

        // Act
        let previous_index = FileExplorer::previous_selected_index(current_index, item_count);

        // Assert
        assert_eq!(previous_index, 1);
    }

    #[test]
    fn test_file_list_lines_with_rename() {
        // Arrange
        let parsed_lines = vec![DiffLine {
            kind: DiffLineKind::FileHeader,
            old_line: None,
            new_line: None,
            content: DIFF_RENAME_HEADER,
        }];

        // Act
        let lines = FileExplorer::build_tree(&parsed_lines).0;

        // Assert
        assert_eq!(lines.len(), 2);
        assert_eq!(lines[0].spans[0].content, EXPECTED_SRC_FOLDER_LINE);
        assert_eq!(lines[1].spans[0].content, EXPECTED_NEW_FILE_LINE);
        assert_eq!(lines[1].spans[1].content, EXPECTED_RENAME_LINE);
    }

    #[test]
    fn test_file_list_lines_with_nonstandard_header() {
        // Arrange
        let parsed_lines = vec![DiffLine {
            kind: DiffLineKind::FileHeader,
            old_line: None,
            new_line: None,
            content: DIFF_NONSTANDARD_HEADER,
        }];

        // Act
        let lines = FileExplorer::build_tree(&parsed_lines).0;

        // Assert
        assert_eq!(lines.len(), 1);
        assert_eq!(lines[0].spans[0].content, EXPECTED_NONSTANDARD_LINE);
    }

    #[test]
    fn test_file_list_lines_with_nested_structure() {
        // Arrange
        let parsed_lines = vec![
            DiffLine {
                kind: DiffLineKind::FileHeader,
                old_line: None,
                new_line: None,
                content: DIFF_SAME_PATH_HEADER,
            },
            DiffLine {
                kind: DiffLineKind::FileHeader,
                old_line: None,
                new_line: None,
                content: DIFF_NESTED_HEADER,
            },
            DiffLine {
                kind: DiffLineKind::FileHeader,
                old_line: None,
                new_line: None,
                content: DIFF_README_HEADER,
            },
        ];

        // Act
        let lines = FileExplorer::build_tree(&parsed_lines).0;

        // Assert
        let line_text: Vec<String> = lines.iter().map(line_text).collect();
        assert_eq!(
            line_text,
            EXPECTED_NESTED_TREE_LINES
                .iter()
                .map(std::string::ToString::to_string)
                .collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_file_list_lines_with_no_files() {
        // Arrange
        let parsed_lines = vec![DiffLine {
            kind: DiffLineKind::Context,
            old_line: Some(1),
            new_line: Some(1),
            content: UNCHANGED_DIFF_LINE,
        }];

        // Act
        let lines = FileExplorer::build_tree(&parsed_lines).0;

        // Assert
        assert_eq!(lines.len(), 1);
        assert_eq!(lines[0].spans[0].content, NO_FILES_LABEL);
    }

    #[test]
    fn test_file_tree_items_returns_folders_and_files() {
        // Arrange
        let parsed_lines = vec![DiffLine {
            kind: DiffLineKind::FileHeader,
            old_line: None,
            new_line: None,
            content: DIFF_SAME_PATH_HEADER,
        }];

        // Act
        let items = FileExplorer::file_tree_items(&parsed_lines);

        // Assert
        assert_eq!(items.len(), 2);
        assert_eq!(items[0], FileTreeItem::Folder("src/".to_string()));
        assert_eq!(items[1], FileTreeItem::File("src/main.rs".to_string()));
    }

    #[test]
    fn test_file_tree_items_nested_structure() {
        // Arrange
        let parsed_lines = vec![
            DiffLine {
                kind: DiffLineKind::FileHeader,
                old_line: None,
                new_line: None,
                content: DIFF_SAME_PATH_HEADER,
            },
            DiffLine {
                kind: DiffLineKind::FileHeader,
                old_line: None,
                new_line: None,
                content: DIFF_NESTED_HEADER,
            },
            DiffLine {
                kind: DiffLineKind::FileHeader,
                old_line: None,
                new_line: None,
                content: DIFF_README_HEADER,
            },
        ];

        // Act
        let items = FileExplorer::file_tree_items(&parsed_lines);

        // Assert
        assert_eq!(
            items,
            vec![
                FileTreeItem::Folder("src/".to_string()),
                FileTreeItem::Folder("src/ui/".to_string()),
                FileTreeItem::Folder("src/ui/component/".to_string()),
                FileTreeItem::File("src/ui/component/file_explorer.rs".to_string()),
                FileTreeItem::File("src/main.rs".to_string()),
                FileTreeItem::File("README.md".to_string()),
            ]
        );
    }

    #[test]
    fn test_file_tree_items_with_rename() {
        // Arrange
        let parsed_lines = vec![DiffLine {
            kind: DiffLineKind::FileHeader,
            old_line: None,
            new_line: None,
            content: DIFF_RENAME_HEADER,
        }];

        // Act
        let items = FileExplorer::file_tree_items(&parsed_lines);

        // Assert
        assert_eq!(items.len(), 2);
        assert_eq!(items[0], FileTreeItem::Folder("src/".to_string()));
        assert_eq!(items[1], FileTreeItem::File("src/new.rs".to_string()));
    }
}