pmat 3.17.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
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
//! Roadmap update utilities for TICKET-PMAT-5013
//!
//! Automatically updates roadmap with commit information.

#![cfg_attr(coverage_nightly, coverage(off))]
use super::git::{extract_ticket_ids, get_current_commit, ticket_file_updated, CommitInfo};
use super::roadmap::{Roadmap, RoadmapError};
use super::ticket::{TicketFile, TicketStatus};
use std::path::Path;

/// Update roadmap with commit information
///
/// # Complexity
/// - Time: O(n*m) where n=sprints, m=tickets
/// - Cyclomatic: 5
#[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
pub fn update_roadmap_ticket(
    roadmap: &mut Roadmap,
    ticket_id: &str,
    commit_hash: &str,
) -> Result<bool, RoadmapError> {
    let mut updated = false;

    for sprint in &mut roadmap.sprints {
        for ticket in &mut sprint.tickets {
            if ticket.id == ticket_id && !ticket.completed {
                ticket.completed = true;
                ticket.commit = Some(commit_hash.to_string());
                updated = true;
                break;
            }
        }
        if updated {
            break;
        }
    }

    Ok(updated)
}

/// Write updated roadmap back to file
///
/// # Complexity
/// - Time: O(n) where n is roadmap size
/// - Cyclomatic: 2
#[provable_contracts_macros::contract("pmat-core.yaml", equation = "path_exists")]
pub fn write_roadmap(roadmap: &Roadmap, path: &Path) -> Result<(), std::io::Error> {
    let content = format_roadmap_markdown(roadmap);
    std::fs::write(path, content)?;
    Ok(())
}

/// Format roadmap as markdown
///
/// # Complexity
/// - Time: O(n*m) where n=sprints, m=tickets
/// - Cyclomatic: 5
fn format_roadmap_markdown(roadmap: &Roadmap) -> String {
    let mut output = String::new();

    output.push_str("# PMAT Agent System Roadmap\n\n");
    output.push_str(&format!("## 📋 Planned: {}\n\n", roadmap.version));

    for sprint in &roadmap.sprints {
        // Sprint header
        let status_marker = if sprint.is_complete() {
            "COMPLETE ✅"
        } else {
            "IN PROGRESS"
        };

        output.push_str(&format!(
            "### Sprint {}: {} ({}) - {}\n",
            sprint.number, sprint.name, sprint.duration, status_marker
        ));

        output.push_str(&format!("**Focus:** {}\n\n", sprint.focus));

        // Tickets
        for ticket in &sprint.tickets {
            let checkbox = if ticket.completed { "[x]" } else { "[ ]" };
            let commit_ref = if let Some(ref commit) = ticket.commit {
                format!(
                    " (commit: {})",
                    commit.get(..7.min(commit.len())).unwrap_or(commit)
                )
            } else {
                String::new()
            };

            output.push_str(&format!(
                "- {} {}: {}{}\n",
                checkbox, ticket.id, ticket.description, commit_ref
            ));
        }

        output.push('\n');

        // Quality gates
        if !sprint.quality_gates.is_empty() {
            output.push_str("**Quality Gates:**\n");
            for gate in &sprint.quality_gates {
                output.push_str(&format!("- {}\n", gate));
            }
            output.push('\n');
        }
    }

    output
}

/// Update roadmap from current commit
///
/// # TICKET-PMAT-5013
///
/// # Complexity
/// - Time: O(n*m) where n=sprints, m=tickets
/// - Cyclomatic: 7 (reduced from 12 via Extract Method refactoring)
#[provable_contracts_macros::contract("pmat-core.yaml", equation = "path_exists")]
pub fn update_roadmap_from_commit(
    roadmap_path: &Path,
    tickets_dir: &Path,
) -> Result<(), Box<dyn std::error::Error>> {
    // Get current commit info
    let commit = get_current_commit()?;

    // Extract ticket IDs from commit message
    let ticket_ids = extract_ticket_ids(&commit.message);

    if ticket_ids.is_empty() {
        return Ok(()); // No tickets in commit
    }

    // Load roadmap
    let mut roadmap = Roadmap::from_file(roadmap_path)?;
    let mut updated = false;

    // Process each ticket
    for ticket_id in ticket_ids {
        if process_ticket_update(&mut roadmap, &commit, &ticket_id, tickets_dir)? {
            updated = true;
        }
    }

    // Write roadmap if updated
    if updated {
        write_roadmap(&roadmap, roadmap_path)?;
        println!(
            "✓ Updated roadmap with commit {}",
            commit
                .hash
                .get(..7.min(commit.hash.len()))
                .unwrap_or(&commit.hash)
        );
    }

    Ok(())
}

/// Process a single ticket update and return whether roadmap was modified
///
/// # Complexity
/// - Cyclomatic: 5 (reduced via Extract Method)
fn process_ticket_update(
    roadmap: &mut Roadmap,
    commit: &CommitInfo,
    ticket_id: &str,
    tickets_dir: &Path,
) -> Result<bool, Box<dyn std::error::Error>> {
    // Only update if ticket file was modified
    if !ticket_file_updated(commit, ticket_id) {
        return Ok(false);
    }

    // Check if ticket is now GREEN or COMPLETE
    let ticket_path = tickets_dir.join(format!("{}.md", ticket_id));
    let ticket_file = match TicketFile::from_file(&ticket_path) {
        Ok(file) => file,
        Err(_) => return Ok(false),
    };

    if !matches!(
        ticket_file.status,
        TicketStatus::Green | TicketStatus::Complete
    ) {
        return Ok(false);
    }

    // Update roadmap
    Ok(update_roadmap_ticket(roadmap, ticket_id, &commit.hash)?)
}

#[cfg_attr(coverage_nightly, coverage(off))]
#[cfg(test)]
mod tests {
    use super::*;
    use crate::maintenance::roadmap::{Sprint, SprintStatus, Ticket};

    fn create_test_roadmap() -> Roadmap {
        Roadmap {
            version: "v2.139.0".into(),
            sprints: vec![Sprint {
                number: 17,
                name: "Test Sprint".into(),
                focus: "Testing".into(),
                status: SprintStatus::InProgress,
                duration: "2 days".into(),
                tickets: vec![
                    Ticket {
                        id: "TICKET-PMAT-5013".into(),
                        description: "Auto-update hooks".into(),
                        completed: false,
                        commit: None,
                    },
                    Ticket {
                        id: "TICKET-PMAT-5014".into(),
                        description: "Health score".into(),
                        completed: false,
                        commit: None,
                    },
                ],
                quality_gates: vec!["Coverage >80%".into()],
            }],
        }
    }

    #[test]
    fn test_update_roadmap_ticket_success() {
        let mut roadmap = create_test_roadmap();

        let updated = update_roadmap_ticket(&mut roadmap, "TICKET-PMAT-5013", "abc1234").unwrap();

        assert!(updated);
        assert!(roadmap.sprints[0].tickets[0].completed);
        assert_eq!(roadmap.sprints[0].tickets[0].commit, Some("abc1234".into()));
    }

    #[test]
    fn test_update_roadmap_ticket_not_found() {
        let mut roadmap = create_test_roadmap();

        let updated = update_roadmap_ticket(&mut roadmap, "TICKET-PMAT-9999", "abc1234").unwrap();

        assert!(!updated);
    }

    #[test]
    fn test_update_roadmap_ticket_already_completed() {
        let mut roadmap = create_test_roadmap();
        roadmap.sprints[0].tickets[0].completed = true;
        roadmap.sprints[0].tickets[0].commit = Some("old123".into());

        let updated = update_roadmap_ticket(&mut roadmap, "TICKET-PMAT-5013", "abc1234").unwrap();

        assert!(!updated);
        assert_eq!(roadmap.sprints[0].tickets[0].commit, Some("old123".into()));
    }

    #[test]
    fn test_format_roadmap_markdown_structure() {
        let roadmap = create_test_roadmap();
        let markdown = format_roadmap_markdown(&roadmap);

        assert!(markdown.contains("# PMAT Agent System Roadmap"));
        assert!(markdown.contains("## 📋 Planned: v2.139.0"));
        assert!(markdown.contains("Sprint 17"));
        assert!(markdown.contains("Test Sprint"));
    }

    #[test]
    fn test_format_roadmap_markdown_uncompleted_ticket() {
        let roadmap = create_test_roadmap();
        let markdown = format_roadmap_markdown(&roadmap);

        assert!(markdown.contains("[ ] TICKET-PMAT-5013"));
        assert!(!markdown.contains("(commit:"));
    }

    #[test]
    fn test_format_roadmap_markdown_completed_ticket() {
        let mut roadmap = create_test_roadmap();
        roadmap.sprints[0].tickets[0].completed = true;
        roadmap.sprints[0].tickets[0].commit = Some("abc1234567".into());

        let markdown = format_roadmap_markdown(&roadmap);

        assert!(markdown.contains("[x] TICKET-PMAT-5013"));
        assert!(markdown.contains("(commit: abc1234)"));
    }

    #[test]
    fn test_format_roadmap_markdown_quality_gates() {
        let roadmap = create_test_roadmap();
        let markdown = format_roadmap_markdown(&roadmap);

        assert!(markdown.contains("**Quality Gates:**"));
        assert!(markdown.contains("- Coverage >80%"));
    }

    #[test]
    fn test_format_roadmap_markdown_short_commit_hash() {
        let mut roadmap = create_test_roadmap();
        roadmap.sprints[0].tickets[0].completed = true;
        roadmap.sprints[0].tickets[0].commit = Some("abc".into());

        let markdown = format_roadmap_markdown(&roadmap);

        assert!(markdown.contains("(commit: abc)"));
    }

    #[test]
    fn test_write_roadmap_creates_file() {
        use tempfile::NamedTempFile;

        let roadmap = create_test_roadmap();
        let temp_file = NamedTempFile::new().unwrap();
        let temp_path = temp_file.path().to_path_buf();

        // Close the file so we can write to it
        drop(temp_file);

        write_roadmap(&roadmap, &temp_path).unwrap();

        let content = std::fs::read_to_string(&temp_path).unwrap();
        assert!(content.contains("# PMAT Agent System Roadmap"));
        assert!(content.contains("TICKET-PMAT-5013"));
    }

    /// updater.rs:66-67 — the `"COMPLETE ✅"` arm of format_roadmap_markdown
    /// fires only when Sprint::is_complete() returns true. The existing
    /// fixtures all have `completed: false`, so this arm stayed uncovered.
    #[test]
    fn test_format_roadmap_markdown_sprint_complete_marker() {
        let mut roadmap = create_test_roadmap();
        for ticket in &mut roadmap.sprints[0].tickets {
            ticket.completed = true;
            ticket.commit = Some("abcdef1".into());
        }

        let markdown = format_roadmap_markdown(&roadmap);
        assert!(
            markdown.contains("COMPLETE ✅"),
            "all-tickets-completed sprint must render the COMPLETE ✅ marker"
        );
    }

    fn write_green_ticket(dir: &Path, ticket_id: &str) {
        let content = format!(
            "# {}: Coverage Fixture\n\n\
             **Status**: GREEN\n\
             **Priority**: P1\n\
             **Complexity**: 3\n\
             **Estimated Time**: 1 hour\n\
             **Dependencies**: None\n\
             **Sprint**: Sprint 17\n\n\
             ## Objective\n\n\
             Exercise process_ticket_update.\n\n\
             ## Success Criteria\n\n\
             - [ ] Criterion one\n",
            ticket_id
        );
        std::fs::write(dir.join(format!("{}.md", ticket_id)), content).unwrap();
    }

    /// updater.rs:170-173 — `if !ticket_file_updated(..) { return Ok(false); }`.
    /// Commit that doesn't touch docs/tickets/{id}.md takes this short-circuit.
    #[test]
    fn test_process_ticket_update_returns_false_when_ticket_file_not_in_commit() {
        let tickets_dir = tempfile::tempdir().unwrap();
        write_green_ticket(tickets_dir.path(), "TICKET-PMAT-5013");
        let mut roadmap = create_test_roadmap();
        let commit = CommitInfo {
            hash: "deadbee".into(),
            message: "random".into(),
            files: vec!["src/lib.rs".into()], // no ticket file
        };

        let result = process_ticket_update(
            &mut roadmap,
            &commit,
            "TICKET-PMAT-5013",
            tickets_dir.path(),
        )
        .unwrap();
        assert!(!result, "must short-circuit when ticket file not in commit");
        assert!(!roadmap.sprints[0].tickets[0].completed);
    }

    /// updater.rs:177-180 — `TicketFile::from_file(..) Err => Ok(false)`.
    /// Commit references the file, but the file doesn't exist on disk.
    #[test]
    fn test_process_ticket_update_returns_false_when_ticket_file_missing() {
        let tickets_dir = tempfile::tempdir().unwrap();
        let mut roadmap = create_test_roadmap();
        let commit = CommitInfo {
            hash: "deadbee".into(),
            message: "fix: TICKET-PMAT-5013".into(),
            files: vec!["docs/tickets/TICKET-PMAT-5013.md".into()],
        };

        let result = process_ticket_update(
            &mut roadmap,
            &commit,
            "TICKET-PMAT-5013",
            tickets_dir.path(),
        )
        .unwrap();
        assert!(
            !result,
            "missing ticket file must return Ok(false), not error"
        );
        assert!(!roadmap.sprints[0].tickets[0].completed);
    }

    /// updater.rs:182-187 — status is neither Green nor Complete (here: RED),
    /// so the `!matches!` arm returns Ok(false) without updating the roadmap.
    #[test]
    fn test_process_ticket_update_returns_false_when_status_not_green_or_complete() {
        let tickets_dir = tempfile::tempdir().unwrap();
        let red_content = "# TICKET-PMAT-5013: RED Fixture\n\n\
             **Status**: RED\n\
             **Priority**: P1\n\
             **Complexity**: 3\n\
             **Estimated Time**: 1 hour\n\
             **Dependencies**: None\n\
             **Sprint**: Sprint 17\n\n\
             ## Objective\n\n\
             Still failing.\n\n\
             ## Success Criteria\n\n\
             - [ ] One\n";
        std::fs::write(tickets_dir.path().join("TICKET-PMAT-5013.md"), red_content).unwrap();
        let mut roadmap = create_test_roadmap();
        let commit = CommitInfo {
            hash: "deadbee".into(),
            message: "wip: TICKET-PMAT-5013".into(),
            files: vec!["docs/tickets/TICKET-PMAT-5013.md".into()],
        };

        let result = process_ticket_update(
            &mut roadmap,
            &commit,
            "TICKET-PMAT-5013",
            tickets_dir.path(),
        )
        .unwrap();
        assert!(!result, "RED ticket must not mark roadmap completed");
        assert!(!roadmap.sprints[0].tickets[0].completed);
    }

    /// updater.rs:189-190 — happy path: commit touches the ticket file,
    /// parse succeeds, status is GREEN, so update_roadmap_ticket runs and
    /// returns Ok(true) with the roadmap actually mutated.
    #[test]
    fn test_process_ticket_update_success_marks_roadmap_completed() {
        let tickets_dir = tempfile::tempdir().unwrap();
        write_green_ticket(tickets_dir.path(), "TICKET-PMAT-5013");
        let mut roadmap = create_test_roadmap();
        let commit = CommitInfo {
            hash: "cafef00d".into(),
            message: "feat: TICKET-PMAT-5013 done".into(),
            files: vec!["docs/tickets/TICKET-PMAT-5013.md".into()],
        };

        let result = process_ticket_update(
            &mut roadmap,
            &commit,
            "TICKET-PMAT-5013",
            tickets_dir.path(),
        )
        .unwrap();
        assert!(result, "GREEN ticket must flip roadmap entry");
        assert!(roadmap.sprints[0].tickets[0].completed);
        assert_eq!(
            roadmap.sprints[0].tickets[0].commit,
            Some("cafef00d".into())
        );
    }

    #[test]
    fn test_update_multiple_sprints() {
        let mut roadmap = Roadmap {
            version: "v2.139.0".into(),
            sprints: vec![
                Sprint {
                    number: 16,
                    name: "Sprint 16".into(),
                    focus: "Scaffolding".into(),
                    status: SprintStatus::Complete,
                    duration: "2 days".into(),
                    tickets: vec![Ticket {
                        id: "TICKET-PMAT-5001".into(),
                        description: "Core scaffold".into(),
                        completed: true,
                        commit: Some("old123".into()),
                    }],
                    quality_gates: vec![],
                },
                Sprint {
                    number: 17,
                    name: "Sprint 17".into(),
                    focus: "Maintenance".into(),
                    status: SprintStatus::InProgress,
                    duration: "3 days".into(),
                    tickets: vec![Ticket {
                        id: "TICKET-PMAT-5013".into(),
                        description: "Auto-update hooks".into(),
                        completed: false,
                        commit: None,
                    }],
                    quality_gates: vec![],
                },
            ],
        };

        let updated = update_roadmap_ticket(&mut roadmap, "TICKET-PMAT-5013", "new456").unwrap();

        assert!(updated);
        assert!(roadmap.sprints[1].tickets[0].completed);
        assert_eq!(roadmap.sprints[1].tickets[0].commit, Some("new456".into()));
        // First sprint should be unchanged
        assert_eq!(roadmap.sprints[0].tickets[0].commit, Some("old123".into()));
    }
}