beads_rust 0.2.20

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
//! Property-based tests for issue validation.
//!
//! Uses proptest to verify that:
//! - Valid issues always pass validation
//! - Invalid priorities fail validation
//! - Empty titles fail validation
//! - Timestamp invariants are enforced

use chrono::{TimeZone, Utc};
use proptest::prelude::*;
use tracing::info;

use beads_rust::error::{BeadsError, ErrorCode, StructuredError};
use beads_rust::model::{Issue, IssueType, Priority, Status};
use beads_rust::validation::{IssueValidator, LabelValidator};

/// Initialize test logging for proptest
fn init_test_logging() {
    let _ = tracing_subscriber::fmt()
        .with_env_filter("info")
        .with_test_writer()
        .try_init();
}

/// Create a valid test issue with the given title
fn make_valid_issue(title: &str) -> Issue {
    let now = Utc::now();
    Issue {
        id: "bd-test123".to_string(),
        content_hash: None,
        title: 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: now,
        created_by: None,
        updated_at: 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,
        source_repo_path: None,
        agent_context: 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![],
    }
}

fn assert_validation_error_for_field(
    result: Result<(), Vec<beads_rust::error::ValidationError>>,
    expected_field: &str,
) {
    let errors = result.expect_err("issue should fail validation");
    assert!(
        errors.iter().any(|e| e.field == expected_field),
        "expected {expected_field} error, got {errors:?}"
    );
    let structured = StructuredError::from_error(&BeadsError::from_validation_errors(errors));
    assert_eq!(structured.code, ErrorCode::ValidationFailed);
}

proptest! {
    #![proptest_config(ProptestConfig {
        cases: 100,
        ..Default::default()
    })]

    /// Property: Valid issues with good titles always pass validation
    #[test]
    fn valid_issue_passes(title in "[a-zA-Z0-9 ]{1,100}") {
        init_test_logging();
        info!("proptest_valid_issue: title_len={len}", len = title.len());

        // Skip if title is whitespace-only after generation
        prop_assume!(!title.trim().is_empty());

        let issue = make_valid_issue(&title);
        let result = IssueValidator::validate(&issue);

        prop_assert!(
            result.is_ok(),
            "Valid issue should pass validation: {result:?}"
        );
    }

    /// Property: Invalid priority (> 4) fails validation
    #[test]
    fn invalid_priority_fails(priority in 5i32..100i32) {
        init_test_logging();
        info!("proptest_invalid_priority: priority={priority}");

        let mut issue = make_valid_issue("Test Issue");
        issue.priority = Priority(priority);

        let result = IssueValidator::validate(&issue);

        prop_assert!(result.is_err(), "Priority {priority} should fail validation");
        let errors = result.unwrap_err();
        prop_assert!(
            errors.iter().any(|e| e.field == "priority"),
            "Should have priority error"
        );
    }

    /// Property: Negative priority fails validation
    #[test]
    fn negative_priority_fails(priority in -100i32..-1i32) {
        init_test_logging();
        info!("proptest_negative_priority: priority={priority}");

        let mut issue = make_valid_issue("Test Issue");
        issue.priority = Priority(priority);

        let result = IssueValidator::validate(&issue);

        prop_assert!(result.is_err(), "Priority {priority} should fail validation");
    }

    /// Property: Valid priority (0-4) passes validation
    #[test]
    fn valid_priority_passes(priority in 0i32..=4i32) {
        init_test_logging();
        info!("proptest_valid_priority: priority={priority}");

        let mut issue = make_valid_issue("Test Issue");
        issue.priority = Priority(priority);

        let result = IssueValidator::validate(&issue);

        prop_assert!(result.is_ok(), "Priority {priority} should pass validation");
    }

    /// Property: Empty title fails validation
    #[test]
    fn empty_title_fails(whitespace in "\\s{0,10}") {
        init_test_logging();
        info!(
            "proptest_empty_title: whitespace_len={len}",
            len = whitespace.len()
        );

        let mut issue = make_valid_issue("Valid");
        issue.title = whitespace;

        let result = IssueValidator::validate(&issue);

        prop_assert!(result.is_err(), "Empty/whitespace title should fail");
        let errors = result.unwrap_err();
        prop_assert!(
            errors.iter().any(|e| e.field == "title"),
            "Should have title error"
        );
    }

    /// Property: Title over 500 chars fails validation
    #[test]
    fn long_title_fails(len in 501usize..600usize) {
        init_test_logging();
        info!("proptest_long_title: len={len}");

        let mut issue = make_valid_issue("Valid");
        issue.title = "x".repeat(len);

        let result = IssueValidator::validate(&issue);

        prop_assert!(result.is_err(), "Title with {len} chars should fail");
        let errors = result.unwrap_err();
        prop_assert!(
            errors.iter().any(|e| e.field == "title"),
            "Should have title error"
        );
    }

    /// Property: Title up to 500 chars passes validation
    #[test]
    fn title_at_limit_passes(len in 1usize..=500usize) {
        init_test_logging();
        info!("proptest_title_limit: len={len}");

        let mut issue = make_valid_issue("Valid");
        issue.title = "x".repeat(len);

        let result = IssueValidator::validate(&issue);

        prop_assert!(result.is_ok(), "Title with {len} chars should pass");
    }

    /// Property: long descriptions pass validation cleanly (no size cap).
    #[test]
    fn large_description_validates(extra_bytes in 1usize..1000usize) {
        init_test_logging();
        // Sample size well past the prior 100KB cap to lock in the
        // unbounded contract.
        let len = 600_000 + extra_bytes;
        info!("proptest_large_desc: len={len}");

        let mut issue = make_valid_issue("Test Issue");
        issue.description = Some("x".repeat(len));

        let result = IssueValidator::validate(&issue);
        prop_assert!(result.is_ok(), "Description with {len} bytes must validate (long-text fields are unbounded)");
    }

    /// Property: long rich-text fields pass validation cleanly (no size cap).
    #[test]
    fn large_rich_text_fields_validate(
        field_index in 0usize..3usize,
        extra_bytes in 1usize..1000usize,
    ) {
        init_test_logging();
        let len = 600_000 + extra_bytes;
        let payload = "x".repeat(len);

        let mut issue = make_valid_issue("Test Issue");
        match field_index {
            0 => issue.design = Some(payload),
            1 => issue.acceptance_criteria = Some(payload),
            _ => issue.notes = Some(payload),
        }

        IssueValidator::validate(&issue).expect("long rich-text fields must validate cleanly");
    }

    /// Property: actor/source metadata over 200 chars fails validation.
    #[test]
    fn long_actor_fields_fail(
        field_index in 0usize..4usize,
        extra_chars in 1usize..50usize,
    ) {
        init_test_logging();
        let payload = "x".repeat(200 + extra_chars);

        let mut issue = make_valid_issue("Test Issue");
        let expected_field = match field_index {
            0 => {
                issue.assignee = Some(payload);
                "assignee"
            }
            1 => {
                issue.owner = Some(payload);
                "owner"
            }
            2 => {
                issue.created_by = Some(payload);
                "created_by"
            }
            _ => {
                issue.source_system = Some(payload);
                "source_system"
            }
        };

        assert_validation_error_for_field(IssueValidator::validate(&issue), expected_field);
    }

    /// Property: custom status/type variants over 50 chars fail validation.
    #[test]
    fn long_custom_status_and_type_fail(
        field_index in 0usize..2usize,
        extra_chars in 1usize..50usize,
    ) {
        init_test_logging();
        let payload = "x".repeat(50 + extra_chars);

        let mut issue = make_valid_issue("Test Issue");
        let expected_field = if field_index == 0 {
            issue.status = Status::Custom(payload);
            "status"
        } else {
            issue.issue_type = IssueType::Custom(payload);
            "issue_type"
        };

        assert_validation_error_for_field(IssueValidator::validate(&issue), expected_field);
    }

    /// Property: pathological label arrays and label payloads fail validation.
    #[test]
    fn unbounded_labels_fail(
        label_count in 65usize..80usize,
        long_label_extra in 1usize..50usize,
    ) {
        init_test_logging();

        let mut too_many = make_valid_issue("Test Issue");
        too_many.labels = (0..label_count).map(|i| format!("label{i}")).collect();
        assert_validation_error_for_field(IssueValidator::validate(&too_many), "labels");

        let mut too_long = make_valid_issue("Test Issue");
        too_long.labels = vec!["x".repeat(50 + long_label_extra)];
        assert_validation_error_for_field(IssueValidator::validate(&too_long), "labels");
    }

    /// Property: updated_at before created_at fails validation
    #[test]
    fn updated_before_created_fails(days_before in 1u32..100u32) {
        init_test_logging();
        info!("proptest_timestamp_order: days_before={days_before}");

        let mut issue = make_valid_issue("Test Issue");
        issue.created_at = Utc.with_ymd_and_hms(2026, 6, 15, 12, 0, 0).unwrap();
        issue.updated_at = issue.created_at - chrono::Duration::days(i64::from(days_before));

        let result = IssueValidator::validate(&issue);

        prop_assert!(result.is_err(), "updated_at before created_at should fail");
        let errors = result.unwrap_err();
        prop_assert!(
            errors.iter().any(|e| e.field == "updated_at"),
            "Should have updated_at error"
        );
    }

    /// Property: Valid label format passes validation
    #[test]
    fn valid_label_passes(label in "[a-zA-Z0-9_:-]{1,50}") {
        init_test_logging();
        info!("proptest_valid_label: label={label}");

        let result = LabelValidator::validate(&label);

        prop_assert!(result.is_ok(), "Label '{label}' should pass validation");
    }

    /// Property: Label with spaces fails validation
    #[test]
    fn label_with_space_fails(
        prefix in "[a-z]{1,10}",
        suffix in "[a-z]{1,10}",
    ) {
        init_test_logging();
        let label = format!("{prefix} {suffix}");
        info!("proptest_label_space: label={label}");

        let result = LabelValidator::validate(&label);

        prop_assert!(result.is_err(), "Label with space should fail: '{label}'");
    }

    /// Property: Empty label fails validation
    #[test]
    fn empty_label_fails(_dummy in 0..1u8) {
        init_test_logging();

        let result = LabelValidator::validate("");

        prop_assert!(result.is_err(), "Empty label should fail");
    }

    /// Property: Label over 50 chars fails validation
    #[test]
    fn long_label_fails(len in 51usize..100usize) {
        init_test_logging();
        let label = "x".repeat(len);
        info!("proptest_long_label: len={len}");

        let result = LabelValidator::validate(&label);

        prop_assert!(result.is_err(), "Label with {len} chars should fail");
    }

    /// Property: External ref with whitespace fails validation
    #[test]
    fn external_ref_whitespace_fails(
        prefix in "[a-z]{1,10}",
        suffix in "[a-z]{1,10}",
    ) {
        init_test_logging();
        let external_ref = format!("{prefix} {suffix}");
        info!("proptest_external_ref: external_ref={external_ref}");

        let mut issue = make_valid_issue("Test Issue");
        issue.external_ref = Some(external_ref);

        let result = IssueValidator::validate(&issue);

        prop_assert!(result.is_err(), "External ref with whitespace should fail");
        let errors = result.unwrap_err();
        prop_assert!(
            errors.iter().any(|e| e.field == "external_ref"),
            "Should have external_ref error"
        );
    }

    /// Property: Valid external ref without whitespace passes validation
    #[test]
    fn valid_external_ref_passes(external_ref in "[a-zA-Z0-9_/-]{1,50}") {
        init_test_logging();
        info!("proptest_valid_external_ref: external_ref={external_ref}");

        let mut issue = make_valid_issue("Test Issue");
        issue.external_ref = Some(external_ref.clone());

        let result = IssueValidator::validate(&issue);

        prop_assert!(result.is_ok(), "Valid external ref should pass: '{external_ref}'");
    }
}

/// Property: All standard statuses are valid for issues
#[test]
fn all_standard_statuses_valid() {
    init_test_logging();
    info!("proptest_statuses: testing all standard statuses");

    let statuses = [
        Status::Open,
        Status::InProgress,
        Status::Blocked,
        Status::Deferred,
        Status::Closed,
        Status::Tombstone,
        Status::Pinned,
    ];

    for status in statuses {
        let mut issue = make_valid_issue("Test Issue");
        issue.status = status.clone();
        if status == Status::Closed {
            issue.closed_at = Some(issue.updated_at);
        }

        let result = IssueValidator::validate(&issue);
        assert!(result.is_ok(), "Status {status:?} should be valid");
    }

    info!("proptest_statuses: PASS - all standard statuses valid");
}

/// Property: All standard issue types are valid
#[test]
fn all_standard_types_valid() {
    init_test_logging();
    info!("proptest_types: testing all standard issue types");

    let types = [
        IssueType::Task,
        IssueType::Bug,
        IssueType::Feature,
        IssueType::Epic,
        IssueType::Chore,
        IssueType::Docs,
        IssueType::Question,
    ];

    for issue_type in types {
        let mut issue = make_valid_issue("Test Issue");
        issue.issue_type = issue_type.clone();

        let result = IssueValidator::validate(&issue);
        assert!(result.is_ok(), "IssueType {issue_type:?} should be valid");
    }

    info!("proptest_types: PASS - all standard types valid");
}