pmat 3.30.1

PMAT - Zero-config AI context generation and code quality toolkit (CLI, MCP)
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
// pdmt_service_generation.rs — requirement-to-todo conversion and helper methods
// Included by pdmt_service.rs — shares parent module scope (no `use` imports here)

impl PdmtService {
    /// Derive a stable, uuid-formatted todo id from the deterministic seed,
    /// the requirement text, its index, and the todo role (base/test/doc).
    ///
    /// Identical inputs always produce the same id (RFC 9562 UUIDv8 over an
    /// FNV-1a 128-bit hash), which keeps `pdmt_deterministic_todos` honest:
    /// no `Uuid::new_v4()` randomness in the output.
    fn deterministic_todo_id(
        &self,
        requirement: &str,
        requirement_idx: usize,
        role: &str,
    ) -> String {
        let input = format!(
            "pdmt:{seed}:{requirement_idx}:{role}:{requirement}",
            seed = self.deterministic_seed
        );
        let mut bytes = fnv1a_128(input.as_bytes()).to_be_bytes();
        bytes[6] = (bytes[6] & 0x0f) | 0x80; // version 8 (custom, RFC 9562)
        bytes[8] = (bytes[8] & 0x3f) | 0x80; // RFC 4122 variant
        Uuid::from_bytes(bytes).to_string()
    }

    /// Convert a single requirement into detailed todos
    fn requirement_to_todos(
        &self,
        requirement: &str,
        granularity: &str,
        quality_config: &PdmtQualityConfig,
        requirement_idx: usize,
        dependency_map: &mut HashMap<String, Vec<String>>,
    ) -> Result<Vec<PdmtTodo>> {
        let mut todos = Vec::new();

        // Determine task breakdown based on granularity
        let task_count = match granularity {
            "low" => 1,
            "medium" => 2,
            "high" => 3,
            _ => 2,
        };

        // Analyze requirement to determine appropriate tasks
        let requirement_lower = requirement.to_lowercase();
        let is_feature = requirement_lower.contains("implement")
            || requirement_lower.contains("add")
            || requirement_lower.contains("create");
        let is_fix = requirement_lower.contains("fix") || requirement_lower.contains("bug");
        let is_refactor = requirement_lower.contains("refactor")
            || requirement_lower.contains("improve")
            || requirement_lower.contains("optimize");
        let needs_tests = !requirement_lower.contains("test");

        // Create base implementation task
        let base_id = self.deterministic_todo_id(requirement, requirement_idx, "base");
        let base_todo = PdmtTodo {
            id: base_id.clone(),
            content: self.generate_action_content(requirement, is_feature, is_fix, is_refactor),
            status: TodoStatus::Pending,
            priority: self.determine_priority(&requirement_lower),
            estimated_hours: self.estimate_hours(requirement, task_count as f32),
            dependencies: Vec::new(),
            quality_gates: TodoQualityGates {
                coverage_requirement: quality_config.coverage_threshold,
                doctest_requirement: quality_config.require_doctests,
                property_test_requirement: quality_config.require_property_tests,
                example_requirement: quality_config.require_examples,
                complexity_limit: quality_config.max_complexity,
                satd_tolerance: false, // Always zero tolerance
            },
            validation_commands: self.generate_validation_commands(requirement, quality_config),
            success_criteria: self.generate_success_criteria(quality_config),
            implementation_specs: self.generate_implementation_specs(requirement),
        };

        todos.push(base_todo.clone());

        // Include test task when granularity permits
        if needs_tests && task_count >= 2 {
            let test_id = self.deterministic_todo_id(requirement, requirement_idx, "test");
            dependency_map
                .entry(test_id.clone())
                .or_default()
                .push(base_id.clone());

            let test_todo = PdmtTodo {
                id: test_id,
                content: format!("Write comprehensive tests for: {requirement}"),
                status: TodoStatus::Pending,
                priority: base_todo.priority.clone(),
                estimated_hours: base_todo.estimated_hours * 0.5,
                dependencies: vec![base_id.clone()],
                quality_gates: base_todo.quality_gates.clone(),
                validation_commands: ValidationCommands {
                    unit_tests: "cargo test".to_string(),
                    doctests: if quality_config.require_doctests {
                        "cargo test --doc".to_string()
                    } else {
                        String::new()
                    },
                    property_tests: if quality_config.require_property_tests {
                        "cargo test --features property-tests".to_string()
                    } else {
                        String::new()
                    },
                    examples: vec![],
                    coverage_check: format!(
                        "cargo llvm-cov --fail-under-lines {}",
                        quality_config.coverage_threshold
                    ),
                    // `pmat quality-gate --file` with no argument is not a runnable
                    // command; point it at the file this todo actually produces.
                    quality_proxy: format!("pmat quality-gate --file tests/{base_id}_test.rs"),
                },
                success_criteria: vec![
                    format!(
                        "Tests achieve >{}% coverage",
                        quality_config.coverage_threshold
                    ),
                    "All test cases pass".to_string(),
                    "Property tests validate invariants".to_string(),
                ],
                implementation_specs: ImplementationSpecs {
                    primary_files: vec![],
                    test_files: vec![format!("tests/{}_test.rs", base_id)],
                    doc_files: vec![],
                    example_files: vec![],
                },
            };
            todos.push(test_todo);
        }

        // Include documentation task for detailed granularity
        if task_count >= 3 {
            let doc_id = self.deterministic_todo_id(requirement, requirement_idx, "doc");
            dependency_map
                .entry(doc_id.clone())
                .or_default()
                .push(base_id.clone());

            // The doc todo used to hardcode `examples/demo.rs` and `cargo run
            // --example demo` while the base todo for the SAME requirement named
            // `examples/add_a_demo.rs`: two todos disagreeing about the file, and
            // a command naming an example neither of them creates. Take the
            // example from the requirement's own specs.
            let doc_specs = self.generate_implementation_specs(requirement);
            let doc_examples: Vec<String> = doc_specs
                .example_files
                .iter()
                .filter_map(|file| example_target_name(file))
                .map(|name| format!("cargo run --example {name}"))
                .collect();

            let doc_todo = PdmtTodo {
                id: doc_id,
                content: format!("Document and create examples for: {requirement}"),
                status: TodoStatus::Pending,
                priority: TodoPriority::Low,
                estimated_hours: 2.0,
                dependencies: vec![base_id],
                quality_gates: base_todo.quality_gates,
                validation_commands: ValidationCommands {
                    unit_tests: String::new(),
                    doctests: "cargo test --doc".to_string(),
                    property_tests: String::new(),
                    examples: doc_examples,
                    coverage_check: String::new(),
                    quality_proxy: "pmat quality-gate --file README.md".to_string(),
                },
                success_criteria: vec![
                    "Documentation is comprehensive".to_string(),
                    "Examples run without errors".to_string(),
                    "Doctests pass".to_string(),
                ],
                implementation_specs: ImplementationSpecs {
                    primary_files: vec![],
                    test_files: vec![],
                    doc_files: doc_specs.doc_files,
                    example_files: doc_specs.example_files,
                },
            };
            todos.push(doc_todo);
        }

        Ok(todos)
    }

    /// Generate specific action content for a todo
    fn generate_action_content(
        &self,
        requirement: &str,
        is_feature: bool,
        is_fix: bool,
        is_refactor: bool,
    ) -> String {
        let action_verb = if is_feature {
            "Implement"
        } else if is_fix {
            "Fix"
        } else if is_refactor {
            "Refactor"
        } else {
            "Create"
        };

        format!("{action_verb} {requirement}")
    }

    /// Determine priority based on requirement keywords
    fn determine_priority(&self, requirement: &str) -> TodoPriority {
        if requirement.contains("critical") || requirement.contains("urgent") {
            TodoPriority::Critical
        } else if requirement.contains("bug") || requirement.contains("fix") {
            TodoPriority::High
        } else if requirement.contains("refactor") || requirement.contains("improve") {
            TodoPriority::Medium
        } else {
            TodoPriority::Low
        }
    }

    /// Estimate hours based on requirement complexity
    fn estimate_hours(&self, requirement: &str, base_multiplier: f32) -> f32 {
        let complexity_score = if requirement.len() > 100 {
            3.0
        } else if requirement.len() > 50 {
            2.0
        } else {
            1.0
        };

        (complexity_score * base_multiplier * 2.0).clamp(0.5, 8.0)
    }

    /// Generate validation commands for a todo
    ///
    /// This used to ignore the caller's `PdmtQualityConfig` entirely: it took only
    /// the requirement text and returned a struct literal with a hardcoded
    /// `--fail-under-lines 80`, plus doctest/property/example commands even when
    /// the request had `require_doctests`/`require_property_tests`/`require_examples`
    /// set to false. A single response therefore contained both the requested
    /// threshold (in `quality_gates` and `success_criteria`) and the constant 80
    /// in the command the user was told to run. The commands now come from the
    /// same config as the gates they are supposed to enforce.
    fn generate_validation_commands(
        &self,
        requirement: &str,
        config: &PdmtQualityConfig,
    ) -> ValidationCommands {
        let specs = self.generate_implementation_specs(requirement);
        let quality_proxy = specs
            .primary_files
            .first()
            .map_or_else(
                || "pmat quality-gate".to_string(),
                |file| format!("pmat quality-gate --file {file}"),
            );

        ValidationCommands {
            unit_tests: "cargo test".to_string(),
            doctests: if config.require_doctests {
                "cargo test --doc".to_string()
            } else {
                String::new()
            },
            property_tests: if config.require_property_tests {
                "cargo test --features property-tests".to_string()
            } else {
                String::new()
            },
            // The example command must name the example this same todo tells the
            // user to write. It was the literal `cargo run --example demo` while
            // `implementation_specs.example_files` said `examples/add_a_demo.rs`,
            // so the command in the response could not run in the project the
            // response describes.
            examples: if config.require_examples {
                specs
                    .example_files
                    .iter()
                    .filter_map(|file| example_target_name(file))
                    .map(|name| format!("cargo run --example {name}"))
                    .collect()
            } else {
                vec![]
            },
            coverage_check: format!(
                "cargo llvm-cov --fail-under-lines {}",
                config.coverage_threshold
            ),
            quality_proxy,
        }
    }

    /// Generate success criteria based on quality config
    fn generate_success_criteria(&self, config: &PdmtQualityConfig) -> Vec<String> {
        let mut criteria = vec![
            format!(
                "Unit tests pass with >{}% coverage",
                config.coverage_threshold
            ),
            "Quality proxy approves all changes".to_string(),
            "Zero SATD comments present".to_string(),
            format!("Complexity stays under {} limit", config.max_complexity),
        ];

        if config.require_doctests {
            criteria.push("All doctests execute successfully".to_string());
        }
        if config.require_property_tests {
            criteria.push("Property tests validate invariants".to_string());
        }
        if config.require_examples {
            criteria.push("Examples run without errors".to_string());
        }

        criteria
    }

    /// Generate implementation specs for a requirement
    fn generate_implementation_specs(&self, requirement: &str) -> ImplementationSpecs {
        let base_name = requirement
            .split_whitespace()
            .take(2)
            .collect::<Vec<_>>()
            .join("_")
            .to_lowercase()
            .replace(|c: char| !c.is_alphanumeric() && c != '_', "");

        ImplementationSpecs {
            primary_files: vec![format!("src/{}.rs", base_name)],
            test_files: vec![format!("tests/{}_test.rs", base_name)],
            doc_files: vec!["README.md".to_string()],
            example_files: vec![format!("examples/{}_demo.rs", base_name)],
        }
    }

    /// Set dependencies between todos based on logical ordering
    fn set_dependencies(
        &self,
        todos: &mut [PdmtTodo],
        dependency_map: &HashMap<String, Vec<String>>,
    ) {
        debug!("Setting dependencies for {} todos", todos.len());

        for todo in todos.iter_mut() {
            if let Some(deps) = dependency_map.get(&todo.id) {
                todo.dependencies = deps.clone();
            }
        }
    }
}

/// `examples/add_a_demo.rs` -> `add_a_demo`, the name `cargo run --example`
/// actually takes. Returns `None` for a path with no usable stem so a bad spec
/// drops the command rather than emitting an unrunnable one.
fn example_target_name(example_file: &str) -> Option<String> {
    std::path::Path::new(example_file)
        .file_stem()
        .and_then(|stem| stem.to_str())
        .filter(|stem| !stem.is_empty())
        .map(str::to_string)
}

#[cfg(test)]
mod validation_command_config_tests {
    use super::*;

    fn strict_config(coverage: f32) -> PdmtQualityConfig {
        PdmtQualityConfig {
            coverage_threshold: coverage,
            require_doctests: false,
            require_property_tests: false,
            require_examples: false,
            ..PdmtQualityConfig::default()
        }
    }

    /// The coverage command a todo tells you to run must enforce the coverage
    /// threshold that todo's own quality gate demands — it used to be the
    /// constant 80 regardless of the request.
    #[test]
    fn coverage_check_uses_requested_threshold() {
        let service = PdmtService::new();
        let list = service
            .generate_todos(
                vec!["Add a caching layer".to_string()],
                Some("demo".to_string()),
                "medium",
                strict_config(99.0),
            )
            .expect("generation succeeds");

        for todo in &list.todos {
            if todo.validation_commands.coverage_check.is_empty() {
                continue;
            }
            assert!(
                todo.validation_commands
                    .coverage_check
                    .contains("--fail-under-lines 99"),
                "todo {} reported coverage_check {:?} for a 99% requirement",
                todo.id,
                todo.validation_commands.coverage_check
            );
            assert!(
                !todo.validation_commands.coverage_check.contains("80"),
                "todo {} still carries the hardcoded 80 threshold",
                todo.id
            );
        }
    }

    /// Doctest/property/example commands must not be emitted when the caller
    /// explicitly said they are not required.
    #[test]
    fn optional_commands_omitted_when_not_required() {
        let service = PdmtService::new();
        let list = service
            .generate_todos(
                vec!["Add a caching layer".to_string()],
                Some("demo".to_string()),
                "medium",
                strict_config(99.0),
            )
            .expect("generation succeeds");

        let base = &list.todos[0];
        assert_eq!(base.validation_commands.doctests, "");
        assert_eq!(base.validation_commands.property_tests, "");
        assert!(base.validation_commands.examples.is_empty());
    }

    /// `pmat quality-gate --file` with no argument is not a runnable command.
    #[test]
    fn quality_proxy_names_a_file() {
        let service = PdmtService::new();
        let list = service
            .generate_todos(
                vec!["Add a caching layer".to_string()],
                Some("demo".to_string()),
                "high",
                PdmtQualityConfig::default(),
            )
            .expect("generation succeeds");

        for todo in &list.todos {
            let proxy = &todo.validation_commands.quality_proxy;
            assert_ne!(
                proxy.trim(),
                "pmat quality-gate --file",
                "todo {} emits an argument-less quality-gate command",
                todo.id
            );
        }

        // The Default impl is the other place the dangling flag shipped from.
        assert_eq!(
            ValidationCommands::default().quality_proxy,
            "pmat quality-gate --file src/lib.rs"
        );
    }

    /// `cargo run --example demo` was a literal, while the same todo's
    /// `implementation_specs.example_files` said `examples/add_a_demo.rs` — the
    /// command named an example the response never asks anyone to create.
    #[test]
    fn example_commands_name_the_example_the_todo_creates() {
        let service = PdmtService::new();
        let list = service
            .generate_todos(
                vec!["Add a caching layer".to_string()],
                Some("demo".to_string()),
                "high",
                PdmtQualityConfig::default(),
            )
            .expect("generation succeeds");

        let mut checked = 0;
        for todo in &list.todos {
            for command in &todo.validation_commands.examples {
                checked += 1;
                let target = command
                    .strip_prefix("cargo run --example ")
                    .unwrap_or_else(|| panic!("unexpected example command {command}"));
                assert!(
                    todo.implementation_specs
                        .example_files
                        .iter()
                        .any(|file| file == &format!("examples/{target}.rs")),
                    "todo {} runs example '{target}' but creates {:?}",
                    todo.id,
                    todo.implementation_specs.example_files
                );
            }
        }
        assert!(checked > 0, "no example command was generated to check");
    }
}