beads_rust 0.1.42

Agent-first issue tracker (SQLite + JSONL)
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
//! Text formatting functions for `beads_rust`.
//!
//! Provides plain text (non-ANSI) formatting for terminal output:
//! - Status icons (○ ◐ ● ❄ ✓ ✗ 📌)
//! - Priority labels (P0-P4)
//! - Type badges ([bug], [feature], etc.)
//! - Issue line formatting

use crate::model::{Issue, IssueType, Priority, Status};
use crossterm::style::Stylize;
use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};

/// Status icon characters.
pub mod icons {
    /// Open issue - available to work (hollow circle).
    pub const OPEN: &str = "";
    /// In progress - active work (half-filled).
    pub const IN_PROGRESS: &str = "";
    /// Blocked - needs attention (filled circle).
    pub const BLOCKED: &str = "";
    /// Deferred - scheduled for later (snowflake).
    pub const DEFERRED: &str = "";
    /// Closed - completed (checkmark).
    pub const CLOSED: &str = "";
    /// Tombstone - soft deleted (X mark).
    pub const TOMBSTONE: &str = "";
    /// Pinned - elevated priority (pushpin).
    pub const PINNED: &str = "📌";
    /// Unknown status.
    pub const UNKNOWN: &str = "?";
}

/// Formatting options for text output.
#[derive(Debug, Clone, Copy)]
pub struct TextFormatOptions {
    pub use_color: bool,
    pub max_width: Option<usize>,
    pub wrap: bool,
}

impl TextFormatOptions {
    #[must_use]
    pub const fn plain() -> Self {
        Self {
            use_color: false,
            max_width: None,
            wrap: false,
        }
    }
}

/// Return the icon character for a status.
#[must_use]
pub const fn format_status_icon(status: &Status) -> &'static str {
    match status {
        Status::Open => icons::OPEN,
        Status::InProgress => icons::IN_PROGRESS,
        Status::Blocked => icons::BLOCKED,
        Status::Deferred | Status::Draft => icons::DEFERRED,
        Status::Closed => icons::CLOSED,
        Status::Tombstone => icons::TOMBSTONE,
        Status::Pinned => icons::PINNED,
        Status::Custom(_) => icons::UNKNOWN,
    }
}

/// Format priority as "P0", "P1", etc.
#[must_use]
pub fn format_priority(priority: &Priority) -> String {
    format!("P{}", priority.0)
}

/// Format status label with optional color.
#[must_use]
pub fn format_status_label(status: &Status, use_color: bool) -> String {
    let label = status.as_str();
    if !use_color {
        return label.to_string();
    }

    match status {
        Status::Open => label.green().to_string(),
        Status::InProgress => label.yellow().to_string(),
        Status::Blocked => label.red().to_string(),
        Status::Deferred | Status::Draft => label.blue().to_string(),
        Status::Closed | Status::Tombstone => label.grey().to_string(),
        Status::Pinned => label.magenta().bold().to_string(),
        Status::Custom(_) => label.to_string(),
    }
}

/// Format status icon with optional color.
#[must_use]
pub fn format_status_icon_colored(status: &Status, use_color: bool) -> String {
    let icon = format_status_icon(status);
    if !use_color {
        return icon.to_string();
    }

    match status {
        Status::Open => icon.green().to_string(),
        Status::InProgress => icon.yellow().to_string(),
        Status::Blocked => icon.red().to_string(),
        Status::Deferred | Status::Draft => icon.blue().to_string(),
        Status::Closed | Status::Tombstone => icon.grey().to_string(),
        Status::Pinned => icon.magenta().bold().to_string(),
        Status::Custom(_) => icon.to_string(),
    }
}

/// Format priority label with optional color.
#[must_use]
pub fn format_priority_label(priority: &Priority, use_color: bool) -> String {
    let label = format_priority(priority);
    if !use_color {
        return label;
    }

    match priority.0 {
        0 => label.red().bold().to_string(),
        1 => label.red().to_string(),
        2 => label.yellow().to_string(),
        3 | 4 => label.grey().to_string(),
        _ => label,
    }
}

/// Format priority badge with optional color.
///
/// Matches bd format: `[● P2]` (bullet before priority number).
#[must_use]
pub fn format_priority_badge(priority: &Priority, use_color: bool) -> String {
    format!("[● {}]", format_priority_label(priority, use_color))
}

/// Format issue type as a bracketed badge.
#[must_use]
pub fn format_type_badge(issue_type: &IssueType) -> String {
    format!("[{}]", issue_type.as_str())
}

/// Format issue type badge with optional color.
#[must_use]
pub fn format_type_badge_colored(issue_type: &IssueType, use_color: bool) -> String {
    let label = issue_type.as_str();
    if !use_color {
        return format!("[{label}]");
    }

    let colored = match issue_type {
        IssueType::Bug => label.red().to_string(),
        IssueType::Feature => label.cyan().to_string(),
        IssueType::Task | IssueType::Custom(_) => label.to_string(),
        IssueType::Epic => label.magenta().bold().to_string(),
        IssueType::Docs | IssueType::Question => label.blue().to_string(),
        IssueType::Chore => label.grey().to_string(),
    };

    format!("[{colored}]")
}

/// Determine terminal width from environment (falls back to 80).
///
/// Checks in order:
/// 1. `COLUMNS` environment variable
/// 2. Terminal size via crossterm
/// 3. Falls back to 80
#[must_use]
pub fn terminal_width() -> usize {
    // Try COLUMNS first
    if let Ok(columns) = std::env::var("COLUMNS")
        && let Ok(value) = columns.trim().parse::<usize>()
        && value > 0
    {
        return value;
    }

    // Try crossterm for actual terminal size
    if let Ok((cols, _)) = crossterm::terminal::size()
        && cols > 0
    {
        return cols as usize;
    }

    80
}

/// Truncate a title to fit within `max_len` visible columns.
///
/// Handles wide characters (emojis, CJK) correctly using `unicode-width`.
#[must_use]
pub fn truncate_title(title: &str, max_len: usize) -> String {
    if max_len == 0 {
        return String::new();
    }

    let width = UnicodeWidthStr::width(title);
    if width <= max_len {
        return title.to_string();
    }

    if max_len <= 3 {
        let mut w = 0;
        let mut s = String::new();
        for c in title.chars() {
            let cw = UnicodeWidthChar::width(c).unwrap_or(0);
            if w + cw > max_len {
                break;
            }
            w += cw;
            s.push(c);
        }
        return s;
    }

    let target_len = max_len - 3;
    let mut w = 0;
    let mut s = String::new();
    for c in title.chars() {
        let cw = UnicodeWidthChar::width(c).unwrap_or(0);
        if w + cw > target_len {
            break;
        }
        w += cw;
        s.push(c);
    }
    s.push_str("...");
    s
}

fn visible_len(text: &str) -> usize {
    UnicodeWidthStr::width(text)
}

/// Format a single-line issue summary with options.
///
/// Format: `{icon} {id} [● {priority}] [{type}] - {title}`
/// (matches bd text output format)
#[must_use]
pub fn format_issue_line_with(issue: &Issue, options: TextFormatOptions) -> String {
    let status_icon_plain = format_status_icon(&issue.status);
    // Account for the bullet in priority badge: [● P2]
    let priority_badge_plain = format!("[● {}]", format_priority(&issue.priority));
    let type_badge_plain = format_type_badge(&issue.issue_type);

    // Add 3 for " - " separator between type badge and title
    let prefix_len = visible_len(status_icon_plain)
        + 1
        + visible_len(&issue.id)
        + 1
        + visible_len(&priority_badge_plain)
        + 1
        + visible_len(&type_badge_plain)
        + 3; // " - " separator

    let title = if options.wrap {
        issue.title.clone()
    } else {
        options.max_width.map_or_else(
            || issue.title.clone(),
            |width| truncate_title(&issue.title, width.saturating_sub(prefix_len)),
        )
    };

    let status_icon = format_status_icon_colored(&issue.status, options.use_color);
    let priority_badge = format_priority_badge(&issue.priority, options.use_color);
    let type_badge = format_type_badge_colored(&issue.issue_type, options.use_color);

    format!(
        "{status_icon} {} {priority_badge} {type_badge} - {title}",
        issue.id
    )
}

/// Format a single-line issue summary.
///
/// Format: `{icon} {id} [{priority}] [{type}] {title}`
#[must_use]
pub fn format_issue_line(issue: &Issue) -> String {
    format_issue_line_with(issue, TextFormatOptions::plain())
}

fn issue_detail_lines(issue: &Issue, include_extended: bool) -> Vec<String> {
    let mut details = vec![
        format!("Status: {}", issue.status),
        format!("Priority: {}", format_priority(&issue.priority)),
        format!("Type: {}", issue.issue_type),
    ];

    if let Some(assignee) = issue.assignee.as_deref()
        && !assignee.is_empty()
    {
        details.push(format!("Assignee: {assignee}"));
    }
    if let Some(owner) = issue.owner.as_deref()
        && !owner.is_empty()
    {
        details.push(format!("Owner: {owner}"));
    }
    if !issue.labels.is_empty() {
        details.push(format!("Labels: {}", issue.labels.join(", ")));
    }
    if let Some(due_at) = issue.due_at {
        details.push(format!("Due: {}", due_at.format("%Y-%m-%d")));
    }
    if let Some(defer_until) = issue.defer_until {
        details.push(format!(
            "Deferred Until: {}",
            defer_until.format("%Y-%m-%d")
        ));
    }

    if include_extended {
        details.push(format!("Created: {}", issue.created_at.format("%Y-%m-%d")));
        details.push(format!("Updated: {}", issue.updated_at.format("%Y-%m-%d")));
    }

    details
}

/// Format an issue as a multi-line long text block.
#[must_use]
pub fn format_issue_long_with(issue: &Issue, options: TextFormatOptions) -> String {
    let mut lines = vec![format_issue_line_with(issue, options)];
    lines.extend(
        issue_detail_lines(issue, true)
            .into_iter()
            .map(|detail| format!("  {detail}")),
    );
    lines.join("\n")
}

/// Format an issue as a tree-style pretty text block.
#[must_use]
pub fn format_issue_pretty_with(
    issue: &Issue,
    options: TextFormatOptions,
    include_extended: bool,
) -> String {
    let mut lines = vec![format_issue_line_with(issue, options)];
    let details = issue_detail_lines(issue, include_extended);
    let detail_count = details.len();

    for (index, detail) in details.into_iter().enumerate() {
        let branch = if index + 1 == detail_count {
            "└──"
        } else {
            "├──"
        };
        lines.push(format!("{branch} {detail}"));
    }

    lines.join("\n")
}

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

    fn make_test_issue() -> Issue {
        Issue {
            id: "bd-test".to_string(),
            content_hash: None,
            title: "Test title".to_string(),
            description: None,
            design: None,
            acceptance_criteria: None,
            notes: None,
            status: Status::Open,
            priority: Priority::MEDIUM,
            issue_type: IssueType::Task,
            assignee: None,
            owner: None,
            estimated_minutes: None,
            created_at: Utc::now(),
            created_by: None,
            updated_at: Utc::now(),
            closed_at: None,
            close_reason: None,
            closed_by_session: None,
            due_at: None,
            defer_until: None,
            external_ref: None,
            source_system: None,
            source_repo: None,
            deleted_at: None,
            deleted_by: None,
            delete_reason: None,
            original_type: None,
            compaction_level: None,
            compacted_at: None,
            compacted_at_commit: None,
            original_size: None,
            sender: None,
            ephemeral: false,
            pinned: false,
            is_template: false,
            labels: vec![],
            dependencies: vec![],
            comments: vec![],
        }
    }

    #[test]
    fn test_status_icons() {
        assert_eq!(format_status_icon(&Status::Open), "");
        assert_eq!(format_status_icon(&Status::InProgress), "");
        assert_eq!(format_status_icon(&Status::Blocked), "");
        assert_eq!(format_status_icon(&Status::Deferred), "");
        assert_eq!(format_status_icon(&Status::Closed), "");
        assert_eq!(format_status_icon(&Status::Tombstone), "");
        assert_eq!(format_status_icon(&Status::Pinned), "📌");
        assert_eq!(
            format_status_icon(&Status::Custom("custom".to_string())),
            "?"
        );
    }

    #[test]
    fn test_format_priority() {
        assert_eq!(format_priority(&Priority::CRITICAL), "P0");
        assert_eq!(format_priority(&Priority::HIGH), "P1");
        assert_eq!(format_priority(&Priority::MEDIUM), "P2");
        assert_eq!(format_priority(&Priority::LOW), "P3");
        assert_eq!(format_priority(&Priority::BACKLOG), "P4");
    }

    #[test]
    fn test_format_type_badge() {
        assert_eq!(format_type_badge(&IssueType::Task), "[task]");
        assert_eq!(format_type_badge(&IssueType::Bug), "[bug]");
        assert_eq!(format_type_badge(&IssueType::Feature), "[feature]");
        assert_eq!(format_type_badge(&IssueType::Epic), "[epic]");
        assert_eq!(format_type_badge(&IssueType::Chore), "[chore]");
        assert_eq!(format_type_badge(&IssueType::Docs), "[docs]");
        assert_eq!(format_type_badge(&IssueType::Question), "[question]");
        assert_eq!(
            format_type_badge(&IssueType::Custom("custom".to_string())),
            "[custom]"
        );
    }

    #[test]
    fn test_format_issue_line_open() {
        let issue = make_test_issue();
        let line = format_issue_line(&issue);
        // Format matches bd: {icon} {id} [● {priority}] [{type}] - {title}
        assert_eq!(line, "○ bd-test [● P2] [task] - Test title");
    }

    #[test]
    fn test_format_issue_line_in_progress() {
        let mut issue = make_test_issue();
        issue.status = Status::InProgress;
        let line = format_issue_line(&issue);
        assert!(line.starts_with(""));
    }

    #[test]
    fn test_format_issue_line_closed() {
        let mut issue = make_test_issue();
        issue.status = Status::Closed;
        let line = format_issue_line(&issue);
        assert!(line.starts_with(""));
    }

    #[test]
    fn test_format_issue_line_bug_high_priority() {
        let mut issue = make_test_issue();
        issue.issue_type = IssueType::Bug;
        issue.priority = Priority::HIGH;
        issue.title = "Critical bug".to_string();
        let line = format_issue_line(&issue);
        assert!(line.contains("[● P1]"));
        assert!(line.contains("[bug]"));
        assert!(line.contains("Critical bug"));
    }

    #[test]
    fn test_format_issue_line_epic() {
        let mut issue = make_test_issue();
        issue.issue_type = IssueType::Epic;
        issue.priority = Priority::CRITICAL;
        let line = format_issue_line(&issue);
        assert!(line.contains("[● P0]"));
        assert!(line.contains("[epic]"));
    }

    #[test]
    fn test_format_issue_line_blocked() {
        let mut issue = make_test_issue();
        issue.status = Status::Blocked;
        let line = format_issue_line(&issue);
        assert!(line.starts_with(""));
    }

    #[test]
    fn test_format_issue_line_deferred() {
        let mut issue = make_test_issue();
        issue.status = Status::Deferred;
        let line = format_issue_line(&issue);
        assert!(line.starts_with(""));
    }

    #[test]
    fn test_truncate_title_adds_ellipsis() {
        let title = "This is a long title";
        let truncated = truncate_title(title, 10);
        assert_eq!(truncated, "This is...");
    }

    #[test]
    fn test_format_issue_line_with_truncation() {
        let mut issue = make_test_issue();
        issue.title = "A very long issue title".to_string();
        let options = TextFormatOptions {
            use_color: false,
            max_width: Some(30),
            wrap: false,
        };
        let line = format_issue_line_with(&issue, options);
        assert!(line.contains("..."));
    }

    #[test]
    fn test_format_issue_line_with_wrap() {
        let mut issue = make_test_issue();
        issue.title = "A very long issue title".to_string();
        let options = TextFormatOptions {
            use_color: false,
            max_width: Some(20),
            wrap: true,
        };
        let line = format_issue_line_with(&issue, options);
        assert!(!line.contains("..."));
        assert!(line.contains("A very long issue title"));
    }

    #[test]
    fn test_format_issue_long_with_includes_extended_fields() {
        let mut issue = make_test_issue();
        issue.assignee = Some("alice".to_string());
        issue.labels = vec!["core".to_string(), "frontend".to_string()];

        let output = format_issue_long_with(&issue, TextFormatOptions::plain());

        assert!(output.contains("Status: open"));
        assert!(output.contains("Priority: P2"));
        assert!(output.contains("Assignee: alice"));
        assert!(output.contains("Labels: core, frontend"));
        assert!(output.contains("Created: "));
        assert!(output.contains("Updated: "));
    }

    #[test]
    fn test_format_issue_pretty_with_uses_tree_connectors() {
        let mut issue = make_test_issue();
        issue.assignee = Some("alice".to_string());

        let output = format_issue_pretty_with(&issue, TextFormatOptions::plain(), false);

        assert!(output.contains("├── Status: open"));
        assert!(output.contains("├── Priority: P2"));
        assert!(output.contains("└── Assignee: alice"));
        assert!(!output.contains("Created: "));
    }
}