beads_rust 0.1.44

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
//! Comments command implementation.

use super::{
    auto_import_storage_ctx_if_stale, resolve_issue_id, retry_mutation_with_jsonl_recovery,
};
use crate::cli::{CommentAddArgs, CommentCommands, CommentsArgs};
use crate::config;
use crate::error::{BeadsError, Result};
use crate::model::Comment;
use crate::output::{OutputContext, OutputMode};
use crate::storage::SqliteStorage;
use crate::util::id::{IdResolver, ResolverConfig};
use crate::util::time::format_relative_time;
use chrono::Utc;
use rich_rust::prelude::*;
use std::fs;
use std::io::Read;
use std::path::Path;

/// Execute the comments command.
///
/// # Errors
///
/// Returns an error if database operations fail or if inputs are invalid.
pub fn execute(
    args: &CommentsArgs,
    json: bool,
    cli: &config::CliOverrides,
    ctx: &OutputContext,
) -> Result<()> {
    let beads_dir = config::discover_beads_dir_with_cli(cli)?;

    match &args.command {
        Some(CommentCommands::Add(add_args)) => execute_add(add_args, cli, ctx, &beads_dir),
        Some(CommentCommands::List(list_args)) => {
            execute_list(&list_args.id, json, cli, ctx, &beads_dir, list_args.wrap)
        }
        None => {
            let id = args
                .id
                .as_deref()
                .ok_or_else(|| BeadsError::validation("id", "missing issue id"))?;
            execute_list(id, json, cli, ctx, &beads_dir, args.wrap)
        }
    }
}

fn execute_add(
    args: &CommentAddArgs,
    cli: &config::CliOverrides,
    ctx: &OutputContext,
    beads_dir: &Path,
) -> Result<()> {
    let (mut storage_ctx, route_cli, auto_flush_external) =
        open_routed_storage_for_input(beads_dir, cli, &args.id)?;
    let config_layer = storage_ctx.load_config(&route_cli)?;
    let id_config = config::id_config_from_layer(&config_layer);
    let resolver = IdResolver::new(ResolverConfig::with_prefix(id_config.prefix));
    let actor = config::actor_from_layer(&config_layer);

    let (issue_id, author, text) =
        prepare_comment_add(args, &storage_ctx.storage, &resolver, actor.as_deref())?;
    let comment = retry_mutation_with_jsonl_recovery(
        &mut storage_ctx,
        true,
        "comment add",
        Some(issue_id.as_str()),
        |storage| storage.add_comment(&issue_id, &author, &text),
    )?;
    storage_ctx.flush_no_db_if_dirty()?;
    if auto_flush_external && let Err(error) = storage_ctx.auto_flush_if_enabled() {
        tracing::debug!(
            beads_dir = %storage_ctx.paths.beads_dir.display(),
            error = %error,
            "Routed auto-flush failed (non-fatal)"
        );
    }
    crate::util::set_last_touched_id(beads_dir, &issue_id);

    if matches!(ctx.mode(), OutputMode::Quiet) {
        return Ok(());
    }

    if ctx.is_json() {
        ctx.json_pretty(&comment);
    } else if ctx.is_toon() {
        ctx.toon(&comment);
    } else if ctx.is_rich() {
        render_comment_added_rich(&issue_id, &comment, ctx);
    } else {
        println!("Comment added to {issue_id}");
    }

    Ok(())
}

fn execute_list(
    issue_input: &str,
    json: bool,
    cli: &config::CliOverrides,
    ctx: &OutputContext,
    beads_dir: &Path,
    wrap: bool,
) -> Result<()> {
    let (storage_ctx, route_cli, _) = open_routed_storage_for_input(beads_dir, cli, issue_input)?;
    let config_layer = storage_ctx.load_config(&route_cli)?;
    let id_config = config::id_config_from_layer(&config_layer);
    let resolver = IdResolver::new(ResolverConfig::with_prefix(id_config.prefix));

    list_comments_by_id(
        issue_input,
        &storage_ctx.storage,
        &resolver,
        json,
        ctx,
        wrap,
    )
}

fn open_routed_storage_for_input(
    local_beads_dir: &Path,
    cli: &config::CliOverrides,
    issue_input: &str,
) -> Result<(config::OpenStorageResult, config::CliOverrides, bool)> {
    let route = config::routing::resolve_route(issue_input, local_beads_dir)?;
    let mut route_cli = cli.clone();
    if route.is_external {
        route_cli.db = None;
    }
    let mut storage_ctx = config::open_storage_with_cli(&route.beads_dir, &route_cli)?;
    auto_import_storage_ctx_if_stale(&mut storage_ctx, &route_cli)?;
    Ok((storage_ctx, route_cli, route.is_external))
}

fn prepare_comment_add(
    args: &CommentAddArgs,
    storage: &SqliteStorage,
    resolver: &IdResolver,
    actor: Option<&str>,
) -> Result<(String, String, String)> {
    let issue_id = resolve_issue_id(storage, resolver, &args.id)?;
    let text = read_comment_text(args)?;
    if text.trim().is_empty() {
        return Err(BeadsError::validation(
            "text",
            "comment text cannot be empty",
        ));
    }
    let author = resolve_author(args.author.as_deref(), actor);
    Ok((issue_id, author, text))
}

fn list_comments_by_id(
    id: &str,
    storage: &SqliteStorage,
    resolver: &IdResolver,
    _json: bool,
    ctx: &OutputContext,
    wrap: bool,
) -> Result<()> {
    let issue_id = resolve_issue_id(storage, resolver, id)?;
    let comments = storage.get_comments(&issue_id)?;

    if matches!(ctx.mode(), OutputMode::Quiet) {
        return Ok(());
    }

    if ctx.is_json() {
        ctx.json_pretty(&comments);
        return Ok(());
    }

    if ctx.is_toon() {
        ctx.toon(&comments);
        return Ok(());
    }

    if matches!(ctx.mode(), OutputMode::Rich) {
        render_comments_list_rich(&issue_id, &comments, ctx, wrap);
        return Ok(());
    }

    if comments.is_empty() {
        println!("No comments for {issue_id}.");
        return Ok(());
    }

    println!("Comments for {issue_id}:");
    for comment in comments {
        let timestamp = comment.created_at.format("%Y-%m-%d %H:%M UTC");
        println!("[{}] at {}", comment.author, timestamp);
        println!("{}", comment.body.trim_end_matches('\n'));
        println!();
    }

    Ok(())
}

/// Render a list of comments in rich format.
fn render_comments_list_rich(
    issue_id: &str,
    comments: &[Comment],
    ctx: &OutputContext,
    wrap: bool,
) {
    let console = Console::default();
    let theme = ctx.theme();
    let width = ctx.width();

    if comments.is_empty() {
        let mut text = Text::new("");
        text.append_styled("\u{1f4ad} ", theme.dimmed.clone());
        text.append_styled(
            &format!("No comments for {issue_id}."),
            theme.dimmed.clone(),
        );
        console.print_renderable(&text);
        return;
    }

    let mut content = Text::new("");
    let now = Utc::now();

    for (i, comment) in comments.iter().enumerate() {
        if i > 0 {
            // Separator between comments
            content.append_styled(
                &"\u{2500}".repeat(40.min(width.saturating_sub(4))),
                theme.dimmed.clone(),
            );
            content.append("\n\n");
        }

        // Author and timestamp
        content.append_styled(&format!("@{}", comment.author), theme.username.clone());
        content.append_styled(" \u{2022} ", theme.dimmed.clone());
        content.append_styled(
            &format_relative_time(comment.created_at, now),
            theme.timestamp.clone(),
        );
        content.append("\n");

        // Comment body
        content.append(comment.body.trim_end_matches('\n'));
        content.append("\n\n");
    }

    let title = format!("Comments: {} ({})", issue_id, comments.len());
    let content = if wrap {
        wrap_rich_text(&content, width)
    } else {
        content
    };
    let panel = Panel::from_rich_text(&content, width)
        .title(Text::styled(&title, theme.panel_title.clone()))
        .box_style(theme.box_style);

    console.print_renderable(&panel);
}

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
}

/// Render confirmation for a newly added comment.
fn render_comment_added_rich(issue_id: &str, comment: &Comment, ctx: &OutputContext) {
    let console = Console::default();
    let theme = ctx.theme();

    let mut text = Text::new("");
    text.append_styled("\u{2713} ", theme.success.clone());
    text.append_styled("Added comment to ", theme.success.clone());
    text.append_styled(issue_id, theme.issue_id.clone());
    console.print_renderable(&text);

    console.print("");

    // Show the comment that was added
    let mut comment_text = Text::new("");
    comment_text.append_styled(&format!("@{}", comment.author), theme.username.clone());
    comment_text.append_styled(" \u{2022} just now", theme.timestamp.clone());
    comment_text.append("\n");
    comment_text.append(comment.body.trim_end_matches('\n'));
    console.print_renderable(&comment_text);
}

const MAX_STDIN_COMMENT_BYTES: usize = 10 * 1024 * 1024;

fn read_limited_string<R: Read>(reader: &mut R, byte_limit: usize, field: &str) -> Result<String> {
    let max_bytes = byte_limit
        .checked_add(1)
        .and_then(|limit| u64::try_from(limit).ok())
        .unwrap_or(u64::MAX);
    let mut buffer = String::new();
    reader.take(max_bytes).read_to_string(&mut buffer)?;
    if buffer.len() > byte_limit {
        return Err(BeadsError::validation(
            field,
            format!("stdin input exceeds maximum size of {byte_limit} bytes"),
        ));
    }
    Ok(buffer)
}

fn read_comment_text(args: &CommentAddArgs) -> Result<String> {
    if let Some(path) = &args.file {
        if path.as_os_str() == "-" {
            let mut stdin = std::io::stdin();
            return read_limited_string(&mut stdin, MAX_STDIN_COMMENT_BYTES, "text");
        }
        let metadata = fs::metadata(path)?;
        if metadata.len() > MAX_STDIN_COMMENT_BYTES as u64 {
            return Err(BeadsError::validation(
                "file",
                format!(
                    "file exceeds maximum comment size of {} bytes",
                    MAX_STDIN_COMMENT_BYTES
                ),
            ));
        }
        return Ok(fs::read_to_string(path)?);
    }
    if let Some(message) = &args.message {
        return Ok(message.clone());
    }
    if !args.text.is_empty() {
        return Ok(args.text.join(" "));
    }
    Err(BeadsError::validation("text", "comment text required"))
}

fn resolve_author(author_override: Option<&str>, actor: Option<&str>) -> String {
    if let Some(author) = author_override
        && !author.trim().is_empty()
    {
        return author.to_string();
    }
    if let Some(actor) = actor
        && !actor.trim().is_empty()
    {
        return actor.to_string();
    }
    if let Some(value) = resolve_author_from_env(|name| std::env::var(name).ok()) {
        return value;
    }

    "unknown".to_string()
}

fn resolve_author_from_env(mut lookup: impl FnMut(&str) -> Option<String>) -> Option<String> {
    for key in ["BD_ACTOR", "BEADS_ACTOR", "USER", "LOGNAME", "USERNAME"] {
        if let Some(value) = lookup(key)
            && !value.trim().is_empty()
        {
            return Some(value);
        }
    }

    None
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::logging::init_test_logging;
    use std::io::Write;
    use tempfile::NamedTempFile;
    use tracing::info;

    #[test]
    fn test_resolve_author_with_override() {
        init_test_logging();
        info!("test_resolve_author_with_override: starting");
        // When author override is provided, it should be used
        let result = resolve_author(Some("custom_author"), Some("actor_name"));
        assert_eq!(result, "custom_author");
        info!("test_resolve_author_with_override: assertions passed");
    }

    #[test]
    fn test_resolve_author_empty_override_uses_actor() {
        init_test_logging();
        info!("test_resolve_author_empty_override_uses_actor: starting");
        // Empty override should fall through to actor
        let result = resolve_author(Some(""), Some("actor_name"));
        assert_eq!(result, "actor_name");
        info!("test_resolve_author_empty_override_uses_actor: assertions passed");
    }

    #[test]
    fn test_resolve_author_whitespace_override_uses_actor() {
        init_test_logging();
        info!("test_resolve_author_whitespace_override_uses_actor: starting");
        // Whitespace-only override should fall through to actor
        let result = resolve_author(Some("   "), Some("actor_name"));
        assert_eq!(result, "actor_name");
        info!("test_resolve_author_whitespace_override_uses_actor: assertions passed");
    }

    #[test]
    fn test_resolve_author_no_override_uses_actor() {
        init_test_logging();
        info!("test_resolve_author_no_override_uses_actor: starting");
        // No override should use actor
        let result = resolve_author(None, Some("actor_name"));
        assert_eq!(result, "actor_name");
        info!("test_resolve_author_no_override_uses_actor: assertions passed");
    }

    #[test]
    fn test_resolve_author_empty_actor_falls_through() {
        init_test_logging();
        info!("test_resolve_author_empty_actor_falls_through: starting");
        // Empty actor should fall through to env/USER/LOGNAME/USERNAME/unknown
        // Since we can't easily control env, just test that it doesn't panic
        // and returns something non-empty
        let result = resolve_author(None, Some(""));
        assert!(!result.is_empty());
        info!("test_resolve_author_empty_actor_falls_through: assertions passed");
    }

    #[test]
    fn test_resolve_author_env_helper_checks_windows_username() {
        init_test_logging();
        info!("test_resolve_author_env_helper_checks_windows_username: starting");
        let result = resolve_author_from_env(|name| match name {
            "USERNAME" => Some("windows-user".to_string()),
            _ => None,
        });
        assert_eq!(result.as_deref(), Some("windows-user"));
        info!("test_resolve_author_env_helper_checks_windows_username: assertions passed");
    }

    #[test]
    fn test_read_comment_text_from_message_flag() {
        init_test_logging();
        info!("test_read_comment_text_from_message_flag: starting");
        let args = CommentAddArgs {
            id: "test-id".to_string(),
            text: vec![],
            file: None,
            author: None,
            message: Some("message flag content".to_string()),
        };
        let result = read_comment_text(&args).unwrap();
        assert_eq!(result, "message flag content");
        info!("test_read_comment_text_from_message_flag: assertions passed");
    }

    #[test]
    fn test_read_comment_text_from_positional_args() {
        init_test_logging();
        info!("test_read_comment_text_from_positional_args: starting");
        let args = CommentAddArgs {
            id: "test-id".to_string(),
            text: vec!["hello".to_string(), "world".to_string()],
            file: None,
            author: None,
            message: None,
        };
        let result = read_comment_text(&args).unwrap();
        assert_eq!(result, "hello world");
        info!("test_read_comment_text_from_positional_args: assertions passed");
    }

    #[test]
    fn test_read_comment_text_from_file() {
        init_test_logging();
        info!("test_read_comment_text_from_file: starting");
        let mut file = NamedTempFile::new().unwrap();
        writeln!(file, "Comment from file").unwrap();
        file.flush().unwrap();

        let args = CommentAddArgs {
            id: "test-id".to_string(),
            text: vec![],
            file: Some(file.path().to_path_buf()),
            author: None,
            message: None,
        };
        let result = read_comment_text(&args).unwrap();
        assert!(result.contains("Comment from file"));
        info!("test_read_comment_text_from_file: assertions passed");
    }

    #[test]
    fn test_read_comment_text_file_takes_precedence() {
        init_test_logging();
        info!("test_read_comment_text_file_takes_precedence: starting");
        let mut file = NamedTempFile::new().unwrap();
        writeln!(file, "File content").unwrap();
        file.flush().unwrap();

        let args = CommentAddArgs {
            id: "test-id".to_string(),
            text: vec!["text content".to_string()],
            file: Some(file.path().to_path_buf()),
            author: None,
            message: Some("message content".to_string()),
        };
        let result = read_comment_text(&args).unwrap();
        // File should take precedence
        assert!(result.contains("File content"));
        info!("test_read_comment_text_file_takes_precedence: assertions passed");
    }

    #[test]
    fn test_read_comment_text_no_input_fails() {
        init_test_logging();
        info!("test_read_comment_text_no_input_fails: starting");
        let args = CommentAddArgs {
            id: "test-id".to_string(),
            text: vec![],
            file: None,
            author: None,
            message: None,
        };
        let result = read_comment_text(&args);
        assert!(result.is_err());
        info!("test_read_comment_text_no_input_fails: assertions passed");
    }

    #[test]
    fn test_read_limited_string_accepts_content_within_limit() {
        init_test_logging();
        info!("test_read_limited_string_accepts_content_within_limit: starting");
        let payload = "a".repeat(32);
        let mut reader = payload.as_bytes();
        let result = read_limited_string(&mut reader, 32, "text").expect("read within limit");
        assert_eq!(result.len(), 32);
        info!("test_read_limited_string_accepts_content_within_limit: assertions passed");
    }

    #[test]
    fn test_read_limited_string_rejects_oversized_input() {
        init_test_logging();
        info!("test_read_limited_string_rejects_oversized_input: starting");
        let payload = "a".repeat(33);
        let mut reader = payload.as_bytes();
        let err = read_limited_string(&mut reader, 32, "text").expect_err("oversized stdin");
        assert!(matches!(err, BeadsError::Validation { .. }));
        info!("test_read_limited_string_rejects_oversized_input: assertions passed");
    }
}