pmat 3.14.0

PMAT - Zero-config AI context generation and code quality toolkit (CLI, MCP, HTTP)
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
#![cfg_attr(coverage_nightly, coverage(off))]
//! Coverage boost tests for cli/handlers/work_handlers/ticket_handlers.rs
//!
//! Tests for ticket management handler functions including:
//! - handle_work_validate
//! - handle_work_migrate
//! - handle_work_list_statuses
//! - handle_work_add
//! - handle_work_list
//! - handle_work_edit
//! - handle_work_delete
//! - handle_work_annotate
//! - Helper functions (generate_next_id, find_item_fuzzy, extract_line_from_yaml_error, etc.)

use crate::cli::commands::AnnotateOutputFormat;
use crate::cli::commands::WorkPriority;
use crate::models::roadmap::{ItemStatus, Priority, Roadmap, RoadmapItem};
use crate::services::roadmap_service::RoadmapService;
use std::path::PathBuf;
use tempfile::TempDir;

/// Helper to create a temp directory with a roadmap
fn setup_temp_roadmap() -> (TempDir, PathBuf) {
    let temp_dir = TempDir::new().expect("Failed to create temp dir");
    let roadmap_dir = temp_dir.path().join("docs/roadmaps");
    std::fs::create_dir_all(&roadmap_dir).expect("Failed to create roadmap dir");
    let roadmap_path = roadmap_dir.join("roadmap.yaml");
    (temp_dir, roadmap_path)
}

/// Helper to write a valid roadmap
fn write_valid_roadmap(path: &std::path::Path) {
    let content = r#"roadmap_version: '1.0'
github_enabled: true
github_repo: test/repo
roadmap:
  - id: PMAT-001
    title: "First ticket"
    status: planned
    priority: medium
    created: "2024-01-01T00:00:00Z"
    updated: "2024-01-01T00:00:00Z"
    acceptance_criteria:
      - Test criterion 1
  - id: PMAT-002
    title: "Second ticket"
    status: inprogress
    priority: high
    created: "2024-01-01T00:00:00Z"
    updated: "2024-01-01T00:00:00Z"
    acceptance_criteria: []
"#;
    std::fs::write(path, content).expect("Failed to write roadmap");
}

// ============================================================================
// Tests for extract_line_from_yaml_error
// ============================================================================

#[test]
fn test_extract_line_from_yaml_error_with_line_info() {
    // Simulate a YAML error message that includes "at line X"
    let error = "expected a mapping value at line 5 column 3";
    let result = extract_line_from_yaml_error_test(error);
    assert_eq!(result, Some(5));
}

#[test]
fn test_extract_line_from_yaml_error_without_line_info() {
    let error = "invalid type: expected string";
    let result = extract_line_from_yaml_error_test(error);
    assert_eq!(result, None);
}

#[test]
fn test_extract_line_from_yaml_error_edge_case() {
    // Error with line info but no space after the number
    let error = "at line 42column 1";
    let result = extract_line_from_yaml_error_test(error);
    // This case doesn't match our expected pattern (needs space after line number)
    assert!(result.is_none() || result == Some(42));
}

#[test]
fn test_extract_line_from_yaml_error_at_line_0() {
    let error = "at line 0 column 1";
    let result = extract_line_from_yaml_error_test(error);
    assert_eq!(result, Some(0));
}

#[test]
fn test_extract_line_from_yaml_error_large_line_number() {
    let error = "at line 9999 column 1";
    let result = extract_line_from_yaml_error_test(error);
    assert_eq!(result, Some(9999));
}

/// Test helper that mimics the logic of extract_line_from_yaml_error
fn extract_line_from_yaml_error_test(error: &str) -> Option<usize> {
    if let Some(pos) = error.find("at line ") {
        let rest = &error[pos + 8..];
        if let Some(end) = rest.find(' ') {
            return rest[..end].parse().ok();
        }
    }
    None
}

// ============================================================================
// Tests for generate_next_id
// ============================================================================

#[test]
fn test_generate_next_id_empty_roadmap() {
    let roadmap = Roadmap::new(None);
    let next_id = generate_next_id_test(&roadmap);
    assert_eq!(next_id, "PMAT-001");
}

#[test]
fn test_generate_next_id_with_existing_items() {
    let mut roadmap = Roadmap::new(None);
    roadmap.upsert_item(RoadmapItem::new("PMAT-001".to_string(), "Test".to_string()));
    roadmap.upsert_item(RoadmapItem::new("PMAT-005".to_string(), "Test".to_string()));
    let next_id = generate_next_id_test(&roadmap);
    assert_eq!(next_id, "PMAT-006");
}

#[test]
fn test_generate_next_id_with_mixed_prefixes() {
    let mut roadmap = Roadmap::new(None);
    roadmap.upsert_item(RoadmapItem::new("GH-100".to_string(), "Test".to_string()));
    roadmap.upsert_item(RoadmapItem::new("PMAT-003".to_string(), "Test".to_string()));
    roadmap.upsert_item(RoadmapItem::new("TASK-050".to_string(), "Test".to_string()));
    let next_id = generate_next_id_test(&roadmap);
    // Should find max number across all prefixes (100) and add 1
    assert_eq!(next_id, "PMAT-101");
}

#[test]
fn test_generate_next_id_with_non_numeric_ids() {
    let mut roadmap = Roadmap::new(None);
    roadmap.upsert_item(RoadmapItem::new(
        "no-number".to_string(),
        "Test".to_string(),
    ));
    roadmap.upsert_item(RoadmapItem::new(
        "also-no-number".to_string(),
        "Test".to_string(),
    ));
    let next_id = generate_next_id_test(&roadmap);
    // No numeric suffixes found, so starts from 1
    assert_eq!(next_id, "PMAT-001");
}

/// Test helper that mimics generate_next_id logic
fn generate_next_id_test(roadmap: &Roadmap) -> String {
    let mut max_num = 0u32;
    for item in &roadmap.roadmap {
        if let Some(num_str) = item.id.split('-').next_back() {
            if let Ok(num) = num_str.parse::<u32>() {
                max_num = max_num.max(num);
            }
        }
    }
    format!("PMAT-{:03}", max_num + 1)
}

// ============================================================================
// Tests for tdg_severity_label
// ============================================================================

#[test]
fn test_tdg_severity_label_excellent() {
    assert_eq!(tdg_severity_label_test(0.5), "Excellent");
    assert_eq!(tdg_severity_label_test(1.0), "Excellent");
}

#[test]
fn test_tdg_severity_label_good() {
    assert_eq!(tdg_severity_label_test(1.5), "Good");
    assert_eq!(tdg_severity_label_test(2.0), "Good");
}

#[test]
fn test_tdg_severity_label_moderate() {
    assert_eq!(tdg_severity_label_test(2.5), "Moderate");
    assert_eq!(tdg_severity_label_test(3.0), "Moderate");
}

#[test]
fn test_tdg_severity_label_critical() {
    assert_eq!(tdg_severity_label_test(3.5), "Critical");
    assert_eq!(tdg_severity_label_test(5.0), "Critical");
}

/// Test helper that mimics tdg_severity_label logic
fn tdg_severity_label_test(score: f64) -> &'static str {
    if score <= 1.0 {
        "Excellent"
    } else if score <= 2.0 {
        "Good"
    } else if score <= 3.0 {
        "Moderate"
    } else {
        "Critical"
    }
}

// ============================================================================
// Tests for calculate_spec_score_simple
// ============================================================================

#[test]
fn test_calculate_spec_score_empty_spec() {
    let spec = TestParsedSpec {
        issue_refs: vec![],
        code_examples: vec![],
        acceptance_criteria: vec![],
        claims: vec![],
        title: String::new(),
        test_requirements: vec![],
    };
    assert_eq!(calculate_spec_score_test(&spec), 0.0);
}

#[test]
fn test_calculate_spec_score_with_issue_refs() {
    let spec = TestParsedSpec {
        issue_refs: vec!["GH-123".to_string()],
        code_examples: vec![],
        acceptance_criteria: vec![],
        claims: vec![],
        title: String::new(),
        test_requirements: vec![],
    };
    assert_eq!(calculate_spec_score_test(&spec), 10.0);
}

#[test]
fn test_calculate_spec_score_with_title() {
    let spec = TestParsedSpec {
        issue_refs: vec![],
        code_examples: vec![],
        acceptance_criteria: vec![],
        claims: vec![],
        title: "Test Title".to_string(),
        test_requirements: vec![],
    };
    assert_eq!(calculate_spec_score_test(&spec), 5.0);
}

#[test]
fn test_calculate_spec_score_max_code_examples() {
    let spec = TestParsedSpec {
        issue_refs: vec![],
        code_examples: vec!["ex".to_string(); 10], // More than max (5)
        acceptance_criteria: vec![],
        claims: vec![],
        title: String::new(),
        test_requirements: vec![],
    };
    // Max 5 code examples * 4 points = 20
    assert_eq!(calculate_spec_score_test(&spec), 20.0);
}

#[test]
fn test_calculate_spec_score_max_score() {
    let spec = TestParsedSpec {
        issue_refs: vec!["GH-1".to_string()],            // +10
        code_examples: vec!["ex".to_string(); 5],        // +20 (5*4)
        acceptance_criteria: vec!["ac".to_string(); 10], // +30 (10*3)
        claims: vec!["cl".to_string(); 20],              // +20 (20*1)
        title: "Title".to_string(),                      // +5
        test_requirements: vec!["tr".to_string(); 5],    // +15 (5*3)
    };
    // Total: 10+20+30+20+5+15 = 100
    assert_eq!(calculate_spec_score_test(&spec), 100.0);
}

#[test]
fn test_calculate_spec_score_capped_at_100() {
    let spec = TestParsedSpec {
        issue_refs: vec!["GH-1".to_string()],
        code_examples: vec!["ex".to_string(); 20], // Way over max
        acceptance_criteria: vec!["ac".to_string(); 50],
        claims: vec!["cl".to_string(); 100],
        title: "Title".to_string(),
        test_requirements: vec!["tr".to_string(); 50],
    };
    assert_eq!(calculate_spec_score_test(&spec), 100.0);
}

/// Simplified test struct for spec
struct TestParsedSpec {
    issue_refs: Vec<String>,
    code_examples: Vec<String>,
    acceptance_criteria: Vec<String>,
    claims: Vec<String>,
    title: String,
    test_requirements: Vec<String>,
}

/// Test helper that mimics calculate_spec_score_simple logic
fn calculate_spec_score_test(spec: &TestParsedSpec) -> f64 {
    let mut score = 0.0;
    if !spec.issue_refs.is_empty() {
        score += 10.0;
    }
    score += (spec.code_examples.len().min(5) * 4) as f64;
    score += (spec.acceptance_criteria.len().min(10) * 3) as f64;
    score += (spec.claims.len().min(20)) as f64;
    if !spec.title.is_empty() {
        score += 5.0;
    }
    score += (spec.test_requirements.len().min(5) * 3) as f64;
    score.min(100.0)
}

// ============================================================================
// Tests for WorkPriority conversion
// ============================================================================

#[test]
fn test_work_priority_to_roadmap_priority_low() {
    let wp = WorkPriority::Low;
    assert_eq!(wp.to_roadmap_priority(), Priority::Low);
}

#[test]
fn test_work_priority_to_roadmap_priority_medium() {
    let wp = WorkPriority::Medium;
    assert_eq!(wp.to_roadmap_priority(), Priority::Medium);
}

#[test]
fn test_work_priority_to_roadmap_priority_high() {
    let wp = WorkPriority::High;
    assert_eq!(wp.to_roadmap_priority(), Priority::High);
}

#[test]
fn test_work_priority_to_roadmap_priority_critical() {
    let wp = WorkPriority::Critical;
    assert_eq!(wp.to_roadmap_priority(), Priority::Critical);
}

#[test]
fn test_work_priority_default() {
    let wp = WorkPriority::default();
    assert_eq!(wp, WorkPriority::Medium);
}

// ============================================================================
// Tests for AnnotateOutputFormat
// ============================================================================

#[test]
fn test_annotate_output_format_default() {
    let fmt = AnnotateOutputFormat::default();
    // Use Debug format to compare since PartialEq might not be derived
    assert_eq!(format!("{:?}", fmt), "Text");
}

#[test]
fn test_annotate_output_format_variants() {
    let text = AnnotateOutputFormat::Text;
    let json = AnnotateOutputFormat::Json;
    let md = AnnotateOutputFormat::Markdown;

    // Use Debug format to compare since PartialEq might not be derived
    assert_eq!(format!("{:?}", text), "Text");
    assert_eq!(format!("{:?}", json), "Json");
    assert_eq!(format!("{:?}", md), "Markdown");
}

// ============================================================================
// Tests for RoadmapService integration with ticket handlers
// ============================================================================

#[test]
fn test_roadmap_service_exists() {
    let (temp_dir, roadmap_path) = setup_temp_roadmap();

    let service = RoadmapService::new(&roadmap_path);
    assert!(!service.exists());

    // Write a roadmap
    write_valid_roadmap(&roadmap_path);
    assert!(service.exists());

    drop(temp_dir);
}

#[test]
fn test_roadmap_service_load_valid() {
    let (temp_dir, roadmap_path) = setup_temp_roadmap();
    write_valid_roadmap(&roadmap_path);

    let service = RoadmapService::new(&roadmap_path);
    let roadmap = service.load().expect("Failed to load roadmap");

    assert_eq!(roadmap.roadmap_version, "1.0");
    assert!(roadmap.github_enabled);
    assert_eq!(roadmap.github_repo, Some("test/repo".to_string()));
    assert_eq!(roadmap.roadmap.len(), 2);

    drop(temp_dir);
}

#[test]
fn test_roadmap_service_upsert_and_find() {
    let (temp_dir, roadmap_path) = setup_temp_roadmap();

    let service = RoadmapService::new(&roadmap_path);
    let item = RoadmapItem::new("TEST-001".to_string(), "Test ticket".to_string());

    service.upsert_item(item.clone()).expect("Failed to upsert");

    let found = service
        .find_item("TEST-001")
        .expect("Failed to find")
        .expect("Item not found");

    assert_eq!(found.id, "TEST-001");
    assert_eq!(found.title, "Test ticket");

    drop(temp_dir);
}

#[test]
fn test_roadmap_service_remove() {
    let (temp_dir, roadmap_path) = setup_temp_roadmap();

    let service = RoadmapService::new(&roadmap_path);
    let item = RoadmapItem::new("TEST-001".to_string(), "Test ticket".to_string());
    service.upsert_item(item).expect("Failed to upsert");

    let removed = service.remove_item("TEST-001").expect("Failed to remove");
    assert!(removed.is_some());
    assert_eq!(removed.unwrap().id, "TEST-001");

    let not_found = service.find_item("TEST-001").expect("Failed to find");
    assert!(not_found.is_none());

    drop(temp_dir);
}

// ============================================================================
// Tests for fuzzy ID matching logic
// ============================================================================

#[test]
fn test_fuzzy_matching_exact() {
    let mut roadmap = Roadmap::new(None);
    roadmap.upsert_item(RoadmapItem::new("PMAT-001".to_string(), "Test".to_string()));

    let found = roadmap.find_item("PMAT-001");
    assert!(found.is_some());
    assert_eq!(found.unwrap().id, "PMAT-001");
}

#[test]
fn test_fuzzy_matching_case_insensitive() {
    let mut roadmap = Roadmap::new(None);
    roadmap.upsert_item(RoadmapItem::new("PMAT-001".to_string(), "Test".to_string()));

    let found = roadmap.find_item("pmat-001");
    assert!(found.is_some());
    assert_eq!(found.unwrap().id, "PMAT-001");
}

#[test]
fn test_fuzzy_matching_prefix() {
    let mut roadmap = Roadmap::new(None);
    roadmap.upsert_item(RoadmapItem::new("PMAT-001".to_string(), "Test".to_string()));

    let found = roadmap.find_item("PMAT-0");
    assert!(found.is_some());
    assert_eq!(found.unwrap().id, "PMAT-001");
}

#[test]
fn test_fuzzy_matching_contains() {
    let mut roadmap = Roadmap::new(None);
    roadmap.upsert_item(RoadmapItem::new("PMAT-001".to_string(), "Test".to_string()));

    let found = roadmap.find_item("001");
    assert!(found.is_some());
    assert_eq!(found.unwrap().id, "PMAT-001");
}

// Continuation of tests in separate files for file health compliance
include!("coverage_boost_ticket_handlers_part2.rs");
include!("coverage_boost_ticket_handlers_part3.rs");