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
502
503
504
505
506
507
508
509
510
511
512
513
514
515
#![cfg_attr(coverage_nightly, coverage(off))]
//! Progress indicator utilities for long-running operations
//!
//! Provides spinners and progress feedback for operations >5s.
//! Automatically detects TTY and disables in CI environments.
//!
//! # Usage
//!
//! ## Simple Progress Spinner
//!
//! ```rust
//! use pmat::cli::progress::ProgressIndicator;
//!
//! let progress = ProgressIndicator::new("Analyzing files...");
//! // Perform long-running operation
//! progress.set_message("Processing results...");
//! progress.finish_with_message("Complete");
//! ```
//!
//! ## Multi-Stage Progress
//!
//! ```rust
//! use pmat::cli::progress::MultiStageProgress;
//!
//! let stages = vec![
//!     "Extracting data".to_string(),
//!     "Processing".to_string(),
//!     "Finalizing".to_string(),
//! ];
//! let mut progress = MultiStageProgress::new(stages);
//!
//! progress.next_stage("Extracting data");
//! progress.set_progress(10, 100);  // 10% complete
//! // ... work ...
//!
//! progress.next_stage("Processing");
//! progress.set_progress(50, 100);  // 50% complete
//! // ... work ...
//!
//! let eta = progress.get_eta();
//! println!("ETA: {:?}", eta);
//!
//! progress.finish("Done");
//! ```
//!
//! ## Category-Based Progress
//!
//! ```rust
//! use pmat::cli::progress::CategoryProgress;
//!
//! let categories = vec![
//!     "Code Quality".to_string(),
//!     "Testing".to_string(),
//!     "Documentation".to_string(),
//! ];
//! let mut progress = CategoryProgress::new(categories);
//!
//! progress.next_category("Code Quality");
//! progress.set_file_progress(50, 100);  // 50 of 100 files
//! println!("Category: {:.1}%", progress.category_percent());
//! println!("Overall: {:.1}%", progress.overall_percent());
//!
//! progress.finish();
//! ```
//!
//! ## Environment Detection
//!
//! Progress indicators automatically respect:
//! - **TTY Detection**: Only shows in interactive terminals
//! - **CI Environments**: Disabled when `CI=true`
//! - **NO_COLOR**: Respects `NO_COLOR` environment variable
//! - **Quiet Mode**: Disabled when `PMAT_QUIET=1`

// NOTE: indicatif dependency removed to reduce transitive deps
// Using local SimpleProgressBar implementation from services::progress
use crate::services::progress::{ProgressBar, ProgressStyle};
use std::io::IsTerminal;
use std::time::{Duration, Instant};

/// The name of the process-wide quiet-mode channel.
///
/// `--quiet` is parsed by clap in `cli::run`, but the code that prints progress
/// banners lives in ~60 handler modules that never see the parsed `Cli`. The env
/// var is how the flag reaches them. It is written in exactly one place
/// ([`set_quiet_mode`], called from `apply_ux_settings`) and read in exactly one
/// place ([`quiet_mode_enabled`]) so there is one rule with one implementation.
const QUIET_ENV: &str = "PMAT_QUIET";

/// Record `--quiet` for the rest of the process.
///
/// Also *clears* the variable when quiet is off. It used only ever to be set,
/// never unset, so a second `cli::run` in the same process (embedders, and the
/// integration tests that call it directly) inherited quiet mode from the first.
///
/// # Safety / threading
///
/// Called once from `cli::run` before any command dispatch, i.e. before the
/// process spawns worker threads that read it.
pub fn set_quiet_mode(quiet: bool) {
    if quiet {
        std::env::set_var(QUIET_ENV, "1");
    } else {
        std::env::remove_var(QUIET_ENV);
    }
}

/// Whether `--quiet` is in effect.
///
/// **This is the one suppression check.** Anything that prints progress,
/// spinners, banners, "Analyzing …" / "✓ … complete" status chatter, or any
/// other output that is not the report itself and not an error must be guarded
/// by this (directly, or via [`status_eprintln!`](crate::status_eprintln) /
/// [`status_println!`](crate::status_println)) rather than by a new per-handler
/// flag.
#[must_use]
pub fn quiet_mode_enabled() -> bool {
    std::env::var_os(QUIET_ENV).is_some_and(|v| !v.is_empty())
}

/// `eprintln!` for status/progress chatter: silent under `--quiet`.
///
/// Errors must keep using plain `eprintln!` — `--quiet` is documented as
/// "errors only", not "silent".
#[macro_export]
macro_rules! status_eprintln {
    ($($arg:tt)*) => {
        if !$crate::cli::progress::quiet_mode_enabled() {
            eprintln!($($arg)*);
        }
    };
}

/// `println!` for status/progress chatter: silent under `--quiet`.
///
/// Only for chatter. Report content on stdout is what the user asked for and
/// must print regardless — `--quiet` suppresses noise, not results.
#[macro_export]
macro_rules! status_println {
    ($($arg:tt)*) => {
        if !$crate::cli::progress::quiet_mode_enabled() {
            println!($($arg)*);
        }
    };
}

/// Progress indicator for long-running operations
pub struct ProgressIndicator {
    progress_bar: Option<ProgressBar>,
}

impl ProgressIndicator {
    /// Create a new progress spinner
    ///
    /// CC=2: Simple initialization
    #[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
    pub fn new(message: &str) -> Self {
        let progress_bar = if Self::should_show_progress() {
            let pb = ProgressBar::new_spinner();
            pb.set_style(
                ProgressStyle::default_spinner()
                    .tick_chars("⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏")
                    .template("{spinner:.cyan} {msg}")
                    .expect("internal error"),
            );
            pb.set_message(message.to_string());
            pb.enable_steady_tick(Duration::from_millis(100));
            Some(pb)
        } else {
            None
        };

        Self { progress_bar }
    }

    /// Check if we should show progress indicators
    ///
    /// CC=5: TTY check + env checks (TICKET-PMAT-6006)
    fn should_show_progress() -> bool {
        // Don't show in CI environments
        if std::env::var("CI").is_ok() {
            return false;
        }

        // Don't show if NO_COLOR is set
        if std::env::var("NO_COLOR").is_ok() {
            return false;
        }

        // Don't show in quiet mode (TICKET-PMAT-6006)
        if quiet_mode_enabled() {
            return false;
        }

        // Only show if we have a TTY
        std::io::stdout().is_terminal()
    }

    /// Update the progress message
    ///
    /// CC=1: Simple delegation
    #[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
    pub fn set_message(&self, message: &str) {
        if let Some(ref pb) = self.progress_bar {
            pb.set_message(message.to_string());
        }
    }

    /// Finish with success message
    ///
    /// CC=2: Conditional finish
    #[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
    pub fn finish_with_message(&self, message: &str) {
        if let Some(ref pb) = self.progress_bar {
            pb.finish_with_message(format!("{}", message));
        }
    }

    /// Finish with error message
    ///
    /// CC=2: Conditional finish
    #[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
    pub fn finish_with_error(&self, message: &str) {
        if let Some(ref pb) = self.progress_bar {
            pb.finish_with_message(format!("{}", message));
        }
    }

    /// Clear the progress indicator
    ///
    /// CC=1: Simple delegation
    #[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
    pub fn clear(&self) {
        if let Some(ref pb) = self.progress_bar {
            pb.finish_and_clear();
        }
    }

    /// Check if progress is enabled
    #[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
    pub fn is_enabled(&self) -> bool {
        self.progress_bar.is_some()
    }

    /// Check if colors are being used
    #[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
    pub fn uses_color(&self) -> bool {
        Self::should_show_progress() && std::env::var("NO_COLOR").is_err()
    }

    /// Check if running in a TTY
    #[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
    pub fn is_tty() -> bool {
        std::io::stdout().is_terminal()
    }
}

impl Drop for ProgressIndicator {
    /// CC=1: Simple cleanup
    fn drop(&mut self) {
        self.clear();
    }
}

/// Multi-stage progress indicator for operations with distinct phases
pub struct MultiStageProgress {
    stages: Vec<String>,
    current_stage_index: usize,
    progress_bar: Option<ProgressBar>,
    start_time: Instant,
    completed_items: u64,
    total_items: u64,
}

impl MultiStageProgress {
    #[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
    /// Create a new instance.
    pub fn new(stages: Vec<String>) -> Self {
        Self {
            stages,
            current_stage_index: 0,
            progress_bar: None,
            start_time: Instant::now(),
            completed_items: 0,
            total_items: 0,
        }
    }

    #[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
    /// Next stage.
    pub fn next_stage(&mut self, _message: &str) {
        if self.current_stage_index < self.stages.len() - 1 {
            self.current_stage_index += 1;
        }
    }

    #[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
    /// Current stage.
    pub fn current_stage(&self) -> &str {
        &self.stages[self.current_stage_index]
    }

    /// Current stage index.
    pub fn current_stage_index(&self) -> usize {
        self.current_stage_index
    }

    #[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
    /// Set progress.
    pub fn set_progress(&mut self, current: u64, total: u64) {
        self.completed_items = current;
        self.total_items = total;
    }

    #[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
    /// Completed items.
    pub fn completed_items(&self) -> u64 {
        self.completed_items
    }

    /// Total items.
    pub fn total_items(&self) -> u64 {
        self.total_items
    }

    #[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
    /// Get eta.
    pub fn get_eta(&self) -> Duration {
        if self.completed_items == 0 || self.total_items == 0 {
            return Duration::from_secs(0);
        }

        let elapsed = self.start_time.elapsed();
        let items_remaining = self.total_items.saturating_sub(self.completed_items);
        let time_per_item = elapsed.as_secs_f64() / self.completed_items as f64;
        let estimated_seconds = (items_remaining as f64 * time_per_item) as u64;

        Duration::from_secs(estimated_seconds)
    }

    #[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
    /// Finalize the operation.
    pub fn finish(&self, _message: &str) {
        if let Some(ref pb) = self.progress_bar {
            pb.finish_and_clear();
        }
    }
}

/// Category-based progress for operations analyzing multiple categories
pub struct CategoryProgress {
    categories: Vec<String>,
    current_category_index: usize,
    files_processed: usize,
    total_files: usize,
    progress_bar: Option<ProgressBar>,
    start_time: Instant,
}

impl CategoryProgress {
    #[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
    /// Create a new instance.
    pub fn new(categories: Vec<String>) -> Self {
        Self {
            categories,
            current_category_index: 0,
            files_processed: 0,
            total_files: 0,
            progress_bar: None,
            start_time: Instant::now(),
        }
    }

    #[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
    /// Next category.
    pub fn next_category(&mut self, _name: &str) {
        if self.current_category_index < self.categories.len() - 1 {
            self.current_category_index += 1;
        }
        // Reset file progress for new category
        self.files_processed = 0;
        self.total_files = 0;
    }

    #[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
    /// Current category.
    pub fn current_category(&self) -> &str {
        &self.categories[self.current_category_index]
    }

    /// Current category index.
    pub fn current_category_index(&self) -> usize {
        self.current_category_index
    }

    #[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
    /// Set file progress.
    pub fn set_file_progress(&mut self, current: usize, total: usize) {
        self.files_processed = current;
        self.total_files = total;
    }

    #[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
    /// Files processed.
    pub fn files_processed(&self) -> usize {
        self.files_processed
    }

    /// Total files.
    pub fn total_files(&self) -> usize {
        self.total_files
    }

    #[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
    /// Category percent.
    pub fn category_percent(&self) -> f64 {
        if self.total_files == 0 {
            return 0.0;
        }
        (self.files_processed as f64 / self.total_files as f64) * 100.0
    }

    #[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
    /// Overall percent.
    pub fn overall_percent(&self) -> f64 {
        if self.categories.is_empty() {
            return 0.0;
        }

        // Calculate progress: completed categories + current category progress
        let completed_categories = self.current_category_index as f64;
        let current_category_progress = self.category_percent() / 100.0;
        let total_progress = completed_categories + current_category_progress;

        (total_progress / self.categories.len() as f64) * 100.0
    }

    #[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
    /// Elapsed.
    pub fn elapsed(&self) -> Duration {
        self.start_time.elapsed()
    }

    /// Finalize the operation.
    pub fn finish(&self) {
        if let Some(ref pb) = self.progress_bar {
            pb.finish_and_clear();
        }
    }
}

/// Spinner animation for indeterminate progress
pub struct Spinner {
    frames: Vec<char>,
    current_frame_index: usize,
}

impl Spinner {
    #[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
    /// Create a new instance.
    pub fn new() -> Self {
        Self {
            frames: vec!['', '', '', '', '', '', '', '', '', ''],
            current_frame_index: 0,
        }
    }

    #[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
    /// Advance one frame or step.
    pub fn tick(&mut self) {
        self.current_frame_index = (self.current_frame_index + 1) % self.frames.len();
    }

    /// Current frame.
    pub fn current_frame(&self) -> char {
        self.frames[self.current_frame_index]
    }
}

impl Default for Spinner {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg_attr(coverage_nightly, coverage(off))]
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_progress_indicator_creation() {
        let progress = ProgressIndicator::new("Testing...");
        assert!(progress.progress_bar.is_none() || progress.progress_bar.is_some());
    }

    #[test]
    fn test_progress_indicator_messages() {
        let progress = ProgressIndicator::new("Initial");
        progress.set_message("Updated");
        progress.finish_with_message("Done");
    }

    #[test]
    fn test_progress_indicator_error() {
        let progress = ProgressIndicator::new("Working");
        progress.finish_with_error("Failed");
    }

    #[test]
    fn test_should_show_progress_respects_ci() {
        // This test documents behavior, actual result depends on environment
        let _should_show = ProgressIndicator::should_show_progress();
        // No assertion - environment dependent
    }
}