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
// help_generator_formatting.rs — included by help_generator.rs
// Contains HelpGenerator constructor, generation, and formatting methods.

impl HelpGenerator {
    /// Create a new HelpGenerator
    #[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
    pub fn new(registry: CommandRegistry) -> Self {
        Self {
            registry,
            // `std::io::stdout().is_terminal()` was a SECOND colour policy: it
            // is the `--color auto` half only, so `--color never` (NO_COLOR) and
            // `--color always` (CLICOLOR_FORCE) moved nothing here.
            // `colors_enabled()` is the one rule, and it already contains the
            // is_terminal fallback.
            color: crate::cli::colors::colors_enabled(),
            width: 80, // Default width, could use terminal_size crate if needed
        }
    }

    /// Create with explicit color setting
    #[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
    pub fn with_color(mut self, color: bool) -> Self {
        self.color = color;
        self
    }

    /// Create with explicit width
    #[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
    pub fn with_width(mut self, width: usize) -> Self {
        self.width = width;
        self
    }

    /// Generate help for a specific command path.
    ///
    /// # Arguments
    /// * `path` - Command path like "analyze complexity" or "context"
    ///
    /// # Returns
    /// Formatted help text string
    #[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
    pub fn generate(&self, path: &str) -> String {
        match self.registry.find_command(path) {
            Some(metadata) => self.format_command_help(metadata),
            None => self.format_command_not_found(path),
        }
    }

    /// Generate top-level help (all commands overview)
    #[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
    pub fn generate_overview(&self) -> String {
        let mut out = String::new();

        // Header
        out.push_str(&format!("pmat {}\n", self.registry.version));
        out.push_str("Professional project quantitative scaffolding and analysis toolkit\n\n");

        // Usage
        out.push_str("USAGE:\n");
        out.push_str("    pmat [OPTIONS] <COMMAND>\n\n");

        // Global flags
        if !self.registry.global_flags.is_empty() {
            out.push_str("OPTIONS:\n");
            for flag in &self.registry.global_flags {
                out.push_str(&self.format_flag(flag));
            }
            out.push('\n');
        }

        // Commands by category
        let mut categories: std::collections::HashMap<&str, Vec<&CommandMetadata>> =
            std::collections::HashMap::new();

        for cmd in self.registry.commands.values() {
            let category = if cmd.category.is_empty() {
                "Other"
            } else {
                &cmd.category
            };
            categories.entry(category).or_default().push(cmd);
        }

        out.push_str("COMMANDS:\n");
        let mut sorted_categories: Vec<_> = categories.keys().collect();
        sorted_categories.sort();

        for category in sorted_categories {
            let cmds = categories.get(category).expect("internal error");
            let mut sorted_cmds: Vec<_> = cmds.iter().collect();
            sorted_cmds.sort_by_key(|c| &c.name);

            for cmd in sorted_cmds {
                let name_with_aliases = if cmd.aliases.is_empty() {
                    cmd.name.clone()
                } else {
                    format!("{} ({})", cmd.name, cmd.aliases.join(", "))
                };
                out.push_str(&format!(
                    "    {:30} {}\n",
                    name_with_aliases,
                    truncate_str(&cmd.short_description, 45)
                ));
            }
        }

        out.push_str("\nUse 'pmat <COMMAND> --help' for more information about a command.\n");

        out
    }

    /// Generate help for a specific command
    fn format_command_help(&self, cmd: &CommandMetadata) -> String {
        let mut out = String::new();

        // Header with name and description
        out.push_str(&format!("{}\n", cmd.name));
        if !cmd.short_description.is_empty() {
            out.push_str(&format!("{}\n", cmd.short_description));
        }
        out.push('\n');

        // Long description if available
        if !cmd.long_description.is_empty() {
            out.push_str(&format!("{}\n\n", cmd.long_description));
        }

        // Deprecation warning
        if let Some(dep) = &cmd.deprecated {
            out.push_str(&format!(
                "DEPRECATED: {} (since {})\n",
                dep.reason, dep.since_version
            ));
            if let Some(replacement) = &dep.replacement {
                out.push_str(&format!("Use '{}' instead.\n", replacement));
            }
            out.push('\n');
        }

        // Usage
        out.push_str("USAGE:\n");
        out.push_str(&format!("    pmat {}", self.format_usage(cmd)));
        out.push_str("\n\n");

        // Subcommands
        if !cmd.subcommands.is_empty() {
            out.push_str("SUBCOMMANDS:\n");
            for sub in &cmd.subcommands {
                let name_with_aliases = if sub.aliases.is_empty() {
                    sub.name.clone()
                } else {
                    format!("{} ({})", sub.name, sub.aliases.join(", "))
                };
                out.push_str(&format!(
                    "    {:30} {}\n",
                    name_with_aliases,
                    truncate_str(&sub.short_description, 45)
                ));
            }
            out.push('\n');
        }

        // Arguments
        let positional: Vec<_> = cmd.arguments.iter().filter(|a| a.positional).collect();
        let flags: Vec<_> = cmd.arguments.iter().filter(|a| !a.positional).collect();

        if !positional.is_empty() {
            out.push_str("ARGUMENTS:\n");
            for arg in &positional {
                out.push_str(&self.format_argument(arg));
            }
            out.push('\n');
        }

        if !flags.is_empty() {
            out.push_str("OPTIONS:\n");
            for arg in &flags {
                out.push_str(&self.format_argument(arg));
            }
            out.push('\n');
        }

        // Examples
        if !cmd.examples.is_empty() {
            out.push_str("EXAMPLES:\n");
            for ex in &cmd.examples {
                out.push_str(&format!("    # {}\n", ex.description));
                out.push_str(&format!("    $ {}\n\n", ex.command));
            }
        }

        // Related commands
        if !cmd.related.is_empty() {
            out.push_str("SEE ALSO:\n");
            out.push_str(&format!("    {}\n", cmd.related.join(", ")));
        }

        // Execution time hint
        match cmd.execution_time {
            ExecutionTime::Slow => {
                out.push_str("\nNote: This command may take several seconds to complete.\n");
            }
            _ => {}
        }

        out
    }

    /// Format command not found message with suggestions
    fn format_command_not_found(&self, path: &str) -> String {
        let mut out = String::new();
        out.push_str(&format!("error: unrecognized command '{}'\n\n", path));

        // Find similar commands
        let suggestions = self.find_similar_commands(path, 3);
        if !suggestions.is_empty() {
            out.push_str("Did you mean:\n");
            for (cmd, _score) in suggestions {
                out.push_str(&format!("    pmat {}\n", cmd));
            }
            out.push('\n');
        }

        out.push_str("Use 'pmat --help' to see all available commands.\n");
        out
    }

    /// Format usage string for a command
    fn format_usage(&self, cmd: &CommandMetadata) -> String {
        let mut usage = cmd.name.clone();

        // Add subcommands indicator
        if !cmd.subcommands.is_empty() {
            usage.push_str(" <COMMAND>");
        }

        // Add positional arguments
        for arg in cmd.arguments.iter().filter(|a| a.positional) {
            if arg.required {
                usage.push_str(&format!(" <{}>", arg.name.to_uppercase()));
            } else {
                usage.push_str(&format!(" [{}]", arg.name.to_uppercase()));
            }
        }

        // Indicate options if any
        let has_options = cmd.arguments.iter().any(|a| !a.positional);
        if has_options {
            usage.push_str(" [OPTIONS]");
        }

        usage
    }

    /// Format a single argument for help output
    fn format_argument(&self, arg: &ArgumentMetadata) -> String {
        let mut line = String::new();

        // Build flag/name part
        let flag_part = if arg.positional {
            format!("<{}>", arg.name.to_uppercase())
        } else {
            let short = arg.short.map(|s| format!("-{}", s));
            let long = arg.long.as_ref().map(|l| format!("--{}", l));
            match (short, long) {
                (Some(s), Some(l)) => format!("{}, {}", s, l),
                (Some(s), None) => s,
                (None, Some(l)) => l,
                (None, None) => arg.name.clone(),
            }
        };

        // Add value type indicator
        let value_indicator = match arg.value_type {
            ValueType::Boolean => String::new(),
            ValueType::Enum => {
                if !arg.possible_values.is_empty() {
                    format!(" <{}>", arg.possible_values.join("|"))
                } else {
                    " <VALUE>".to_string()
                }
            }
            _ => format!(" <{}>", arg.name.to_uppercase()),
        };

        let full_flag = format!("{}{}", flag_part, value_indicator);
        line.push_str(&format!("    {:30} ", full_flag));

        // Description
        line.push_str(&arg.description);

        // Default value
        if let Some(default) = &arg.default {
            line.push_str(&format!(" [default: {}]", default));
        }

        // Required indicator
        if arg.required {
            line.push_str(" (required)");
        }

        // Environment variable
        if let Some(env) = &arg.env_var {
            line.push_str(&format!(" [env: {}]", env));
        }

        line.push('\n');
        line
    }

    /// Format a global flag
    fn format_flag(&self, flag: &crate::cli::registry::FlagMetadata) -> String {
        let mut line = String::new();

        let flag_part = match (&flag.short, &flag.long) {
            (Some(s), Some(l)) => format!("-{}, --{}", s, l),
            (Some(s), None) => format!("-{}", s),
            (None, Some(l)) => format!("--{}", l),
            (None, None) => flag.name.clone(),
        };

        line.push_str(&format!("    {:30} ", flag_part));
        line.push_str(&flag.description);

        if let Some(default) = &flag.default {
            line.push_str(&format!(" [default: {}]", default));
        }

        line.push('\n');
        line
    }

    /// Find commands similar to the query using edit distance
    fn find_similar_commands(&self, query: &str, limit: usize) -> Vec<(String, usize)> {
        let all_paths = self.registry.all_command_paths();
        let mut scored: Vec<(String, usize)> = all_paths
            .into_iter()
            .map(|path| {
                let distance = levenshtein(&path, query);
                (path, distance)
            })
            .collect();

        scored.sort_by_key(|(_, score)| *score);
        scored.truncate(limit);

        // Filter out very dissimilar results
        scored
            .into_iter()
            .filter(|(_, score)| *score <= query.len())
            .collect()
    }

    /// Print help to stdout with colors
    #[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
    pub fn print_help(&self, path: Option<&str>) -> std::io::Result<()> {
        let help = match path {
            Some(p) => self.generate(p),
            None => self.generate_overview(),
        };

        if self.color {
            self.print_colored(&help)
        } else {
            print!("{}", help);
            Ok(())
        }
    }

    /// Print with ANSI colors
    fn print_colored(&self, text: &str) -> std::io::Result<()> {
        // A private copy of the palette used to live here as `const &str`, which
        // is precisely the shape that cannot consult `colors_enabled()`. These
        // are the shared `Sgr` values: with colour off each renders to the empty
        // string, so this branch degrades to plain text instead of leaking.
        use crate::cli::colors::{BOLD, CYAN, GREEN, RED, RESET, YELLOW};

        for line in text.lines() {
            if line.starts_with("USAGE:")
                || line.starts_with("COMMANDS:")
                || line.starts_with("OPTIONS:")
                || line.starts_with("ARGUMENTS:")
                || line.starts_with("EXAMPLES:")
                || line.starts_with("SEE ALSO:")
                || line.starts_with("SUBCOMMANDS:")
            {
                println!("{BOLD}{YELLOW}{line}{RESET}");
            } else if line.starts_with("DEPRECATED:") {
                println!("{BOLD}{RED}{line}{RESET}");
            } else if line.starts_with("    #") {
                // Comment in examples
                println!("{CYAN}{line}{RESET}");
            } else if line.starts_with("    $") {
                // Command in examples
                println!("{GREEN}{line}{RESET}");
            } else if line.starts_with("error:") {
                println!("{BOLD}{RED}{line}{RESET}");
            } else {
                println!("{line}");
            }
        }

        Ok(())
    }
}