beads_rust 0.5.10

Agent-first issue tracker (SQLite + JSONL)
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
use crate::format::contains_markdown;
use crate::format::{
    IssueDetails, IssueWithDependencyMetadata, format_status_label, format_type_label,
    sanitize_terminal_inline, sanitize_terminal_text,
};
use crate::model::{Comment, Dependency, Issue};
use crate::output::{OutputContext, OutputMode, Theme};
use rich_rust::prelude::*;
use rich_rust::renderables::markdown::Markdown;

/// Renders a single issue with full details in a styled panel.
pub struct IssuePanel<'a> {
    issue: &'a Issue,
    details: Option<&'a IssueDetails>,
    theme: &'a Theme,
    show_dependencies: bool,
    show_dependents: bool,
    show_comments: bool,
}

impl<'a> IssuePanel<'a> {
    #[must_use]
    pub fn new(issue: &'a Issue, theme: &'a Theme) -> Self {
        Self {
            issue,
            details: None,
            theme,
            show_dependencies: true,
            show_dependents: true,
            show_comments: true,
        }
    }

    #[must_use]
    pub fn from_details(details: &'a IssueDetails, theme: &'a Theme) -> Self {
        Self {
            issue: &details.issue,
            details: Some(details),
            theme,
            show_dependencies: true,
            show_dependents: true,
            show_comments: true,
        }
    }

    #[must_use]
    pub fn show_dependencies(mut self, show: bool) -> Self {
        self.show_dependencies = show;
        self
    }

    #[must_use]
    pub fn show_dependents(mut self, show: bool) -> Self {
        self.show_dependents = show;
        self
    }

    #[must_use]
    pub fn show_comments(mut self, show: bool) -> Self {
        self.show_comments = show;
        self
    }

    pub fn print(&self, ctx: &OutputContext, wrap: bool) {
        let mut content = Text::new("");
        let issue_id = sanitize_terminal_inline(&self.issue.id);

        // Header: ID and Status badges
        content.append_styled(
            &format!("{}  ", issue_id.as_ref()),
            self.theme.issue_id.clone(),
        );
        content.append_styled(
            &format!("[P{}]  ", self.issue.priority.0),
            self.theme.priority_style(self.issue.priority),
        );
        content.append_styled(
            &format!("{}  ", format_status_label(&self.issue.status, false)),
            self.theme.status_style(&self.issue.status),
        );
        content.append_styled(
            &format!("{}\n\n", format_type_label(&self.issue.issue_type)),
            self.theme.type_style(&self.issue.issue_type),
        );

        // Title
        content.append_styled(
            sanitize_terminal_inline(&self.issue.title).as_ref(),
            self.theme.issue_title.clone(),
        );
        content.append("\n");

        // Description. In Rich mode a description that uses markdown is
        // rendered (headings, emphasis, code, lists, links) at the panel's
        // inner width; plain prose and every non-Rich mode keep the verbatim
        // text so Plain/JSON output is unchanged.
        if let Some(ref desc) = self.issue.description {
            content.append("\n");
            let sanitized = sanitize_terminal_text(desc);
            if ctx.mode() == OutputMode::Rich && contains_markdown(&sanitized) {
                let inner_width = ctx.width().saturating_sub(4).max(1);
                for segment in Markdown::new(sanitized.as_ref()).render(inner_width) {
                    match segment.style {
                        Some(style) => content.append_styled(&segment.text, style),
                        None => content.append(&segment.text),
                    }
                }
            } else {
                content.append_styled(sanitized.as_ref(), self.theme.issue_description.clone());
            }
            content.append("\n");
        }

        // Metadata section
        content.append_styled(
            "\n───────────────────────────────────\n",
            self.theme.dimmed.clone(),
        );

        // Assignee
        if let Some(ref assignee) = self.issue.assignee {
            content.append_styled("Assignee: ", self.theme.dimmed.clone());
            content.append_styled(
                &format!("{}\n", sanitize_terminal_inline(assignee)),
                self.theme.username.clone(),
            );
        }

        // Labels
        let labels = self
            .details
            .map_or(self.issue.labels.as_slice(), |d| d.labels.as_slice());
        if !labels.is_empty() {
            content.append_styled("Labels:   ", self.theme.dimmed.clone());
            for (i, label) in labels.iter().enumerate() {
                if i > 0 {
                    content.append(", ");
                }
                content.append_styled(
                    sanitize_terminal_inline(label).as_ref(),
                    self.theme.label.clone(),
                );
            }
            content.append("\n");
        }

        // Timestamps
        content.append_styled("Created:  ", self.theme.dimmed.clone());
        content.append_styled(
            &format!("{}\n", self.issue.created_at.format("%Y-%m-%d %H:%M")),
            self.theme.timestamp.clone(),
        );

        content.append_styled("Updated:  ", self.theme.dimmed.clone());
        content.append_styled(
            &format!("{}\n", self.issue.updated_at.format("%Y-%m-%d %H:%M")),
            self.theme.timestamp.clone(),
        );

        self.append_rollup(&mut content);
        self.append_relationships(&mut content);

        // Comments
        let comments: &[Comment] = self
            .details
            .map_or(self.issue.comments.as_slice(), |d| d.comments.as_slice());
        self.append_comments(&mut content, comments);

        // Build and print panel — always use terminal width so descriptions
        // are never silently truncated (issue #91).
        let panel_width = ctx.width();
        let content = if wrap {
            wrap_rich_text(&content, panel_width)
        } else {
            content
        };
        let panel = Panel::from_rich_text(&content, panel_width)
            .title(Text::styled(
                issue_id.into_owned(),
                self.theme.panel_title.clone(),
            ))
            .box_style(self.theme.box_style)
            .border_style(self.theme.panel_border.clone());

        ctx.render(&panel);
    }

    /// Render the derived parent-child subtree rollup (GitHub #384 phase 3).
    /// The issue's own status badge stays authoritative; this line reports
    /// what the subtree beneath it is doing.
    fn append_rollup(&self, content: &mut Text) {
        let Some(rollup) = self.details.and_then(|details| details.rollup.as_ref()) else {
            return;
        };
        let breakdown = rollup
            .descendants
            .iter()
            .map(|(status, count)| format!("{count} {}", sanitize_terminal_inline(status)))
            .collect::<Vec<_>>()
            .join(", ");
        let rollup_status = rollup
            .status
            .parse::<crate::model::Status>()
            .unwrap_or_default();
        content.append_styled("Rollup:   ", self.theme.dimmed.clone());
        content.append_styled(
            sanitize_terminal_inline(&rollup.status).as_ref(),
            self.theme.status_style(&rollup_status),
        );
        content.append_styled(&format!(" ({breakdown})\n"), self.theme.dimmed.clone());
    }

    fn append_relationships(&self, content: &mut Text) {
        if self.show_dependencies {
            if let Some(details) = self.details {
                render_dependency_list(
                    "Dependencies",
                    &details.dependencies,
                    content,
                    self.theme,
                    false,
                );
            } else if !self.issue.dependencies.is_empty() {
                render_dependency_refs(&self.issue.dependencies, content, self.theme);
            }
        }

        if self.show_dependents
            && let Some(details) = self.details
        {
            render_dependency_list("Dependents", &details.dependents, content, self.theme, true);
        }
    }

    fn append_comments(&self, content: &mut Text, comments: &[Comment]) {
        if !self.show_comments || comments.is_empty() {
            return;
        }

        content.append_styled("\nComments:\n", self.theme.emphasis.clone());
        for comment in comments {
            content.append("  ");
            content.append_styled(
                &comment.created_at.format("%Y-%m-%d %H:%M UTC").to_string(),
                self.theme.timestamp.clone(),
            );
            content.append(" ");
            content.append_styled(
                sanitize_terminal_inline(&comment.author).as_ref(),
                self.theme.username.clone(),
            );
            content.append_styled(": ", self.theme.dimmed.clone());
            content.append_styled(
                sanitize_terminal_text(&comment.body).as_ref(),
                self.theme.comment.clone(),
            );
            content.append("\n");
        }
    }
}

fn wrap_rich_text(text: &Text, panel_width: usize) -> Text {
    let content_width = panel_width.saturating_sub(4).max(1);
    let lines = text.wrap(content_width);
    let mut wrapped = Text::new("");
    for (idx, line) in lines.iter().enumerate() {
        if idx > 0 {
            wrapped.append("\n");
        }
        wrapped.append_text(line);
    }
    wrapped
}

fn render_dependency_list(
    title: &str,
    deps: &[IssueWithDependencyMetadata],
    content: &mut Text,
    theme: &Theme,
    is_dependent: bool,
) {
    if deps.is_empty() {
        return;
    }

    content.append_styled(
        "\n───────────────────────────────────\n",
        theme.dimmed.clone(),
    );
    content.append_styled(&format!("{title}:\n"), theme.emphasis.clone());
    for dep in deps {
        content.append_styled(dependency_arrow(is_dependent), theme.dimmed.clone());
        content.append_styled(
            sanitize_terminal_inline(&dep.id).as_ref(),
            theme.issue_id.clone(),
        );
        content.append(" ");
        content.append_styled(
            &format!("[{}]", format_status_label(&dep.status, false)),
            theme.status_style(&dep.status),
        );
        content.append(" ");
        content.append_styled(
            sanitize_terminal_inline(&dep.title).as_ref(),
            theme.issue_title.clone(),
        );
        content.append(" ");
        content.append_styled(
            &format!("({})", sanitize_terminal_inline(dep.dep_type.as_str())),
            theme.muted.clone(),
        );
        content.append("\n");
    }
}

fn dependency_arrow(is_dependent: bool) -> &'static str {
    if is_dependent { "" } else { "" }
}

fn render_dependency_refs(deps: &[Dependency], content: &mut Text, theme: &Theme) {
    if deps.is_empty() {
        return;
    }

    content.append_styled(
        "\n───────────────────────────────────\n",
        theme.dimmed.clone(),
    );
    content.append_styled("Dependencies:\n", theme.emphasis.clone());
    for dep in deps {
        content.append_styled("", theme.dimmed.clone());
        content.append_styled(
            sanitize_terminal_inline(&dep.depends_on_id).as_ref(),
            theme.issue_id.clone(),
        );
        content.append(" ");
        content.append_styled(
            &format!("({})", sanitize_terminal_inline(dep.dep_type.as_str())),
            theme.muted.clone(),
        );
        content.append("\n");
    }
}

#[cfg(test)]
mod tests {
    use super::{dependency_arrow, render_dependency_list, render_dependency_refs};
    use crate::format::IssueWithDependencyMetadata;
    use crate::model::{Dependency, DependencyType, Priority, Status};
    use crate::output::Theme;
    use chrono::Utc;
    use rich_rust::prelude::Text;

    #[test]
    fn test_dependency_arrow_tracks_direction() {
        assert_eq!(dependency_arrow(false), "");
        assert_eq!(dependency_arrow(true), "");
    }

    #[test]
    fn dependency_rendering_sanitizes_ids_and_types() {
        let theme = Theme::default();
        let metadata_deps = vec![IssueWithDependencyMetadata {
            id: "bd-dep\x1b[2J".to_string(),
            title: "Dependency title".to_string(),
            status: Status::Open,
            priority: Priority::MEDIUM,
            dep_type: "blocks\x07".to_string(),
        }];
        let mut metadata_content = Text::new("");
        render_dependency_list(
            "Dependencies",
            &metadata_deps,
            &mut metadata_content,
            &theme,
            false,
        );

        let raw_deps = vec![Dependency {
            issue_id: "bd-source".to_string(),
            depends_on_id: "bd-target\x1b]52;c;bad\x07".to_string(),
            dep_type: DependencyType::Custom("custom\x08type".to_string()),
            created_at: Utc::now(),
            created_by: None,
            metadata: None,
            thread_id: None,
        }];
        let mut raw_content = Text::new("");
        render_dependency_refs(&raw_deps, &mut raw_content, &theme);

        for rendered in [metadata_content.plain(), raw_content.plain()] {
            assert!(!rendered.contains('\x1b'));
            assert!(!rendered.contains('\x07'));
            assert!(!rendered.contains('\x08'));
        }
        assert!(metadata_content.plain().contains("bd-dep\\u{1b}[2J"));
        assert!(metadata_content.plain().contains("blocks\\u{7}"));
        assert!(
            raw_content
                .plain()
                .contains("bd-target\\u{1b}]52;c;bad\\u{7}")
        );
        assert!(raw_content.plain().contains("custom\\u{8}type"));
    }
}