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
#![cfg_attr(coverage_nightly, coverage(off))]
// TRACE-009: Variable Diff Highlighting
// Sprint 73 - GREEN Phase
//
// Visual comparison of variables between execution snapshots.
// Provides colored diff output and side-by-side comparisons.

use super::types::ExecutionSnapshot;
use std::collections::HashMap;

/// Represents a change in a variable's value
#[derive(Debug, Clone)]
pub struct VariableChange {
    pub old_value: serde_json::Value,
    pub new_value: serde_json::Value,
    pub type_changed: bool,
}

/// Statistics about variable differences
#[derive(Debug, Clone)]
pub struct DiffStatistics {
    pub changed_count: usize,
    pub added_count: usize,
    pub removed_count: usize,
    pub unchanged_count: usize,
    pub total_variables_before: usize,
    pub total_variables_after: usize,
}

/// Diff between two execution snapshots
#[derive(Debug, Clone)]
pub struct VariableDiff {
    /// Variables that changed values
    pub changed: HashMap<String, VariableChange>,
    /// Variables that were added
    pub added: HashMap<String, serde_json::Value>,
    /// Variables that were removed
    pub removed: HashMap<String, serde_json::Value>,
    /// Variables that stayed the same
    pub unchanged: Vec<String>,
}

impl VariableDiff {
    /// Compute diff between two snapshots
    #[provable_contracts_macros::contract("pmat-core.yaml", equation = "score_range")]
    pub fn compute(before: &ExecutionSnapshot, after: &ExecutionSnapshot) -> Self {
        let mut changed = HashMap::new();
        let mut added = HashMap::new();
        let mut removed = HashMap::new();
        let mut unchanged = Vec::new();

        // Find changed and unchanged variables
        for (name, old_value) in &before.variables {
            if let Some(new_value) = after.variables.get(name) {
                if old_value != new_value {
                    // Variable changed
                    let type_changed =
                        Self::value_type_name(old_value) != Self::value_type_name(new_value);

                    changed.insert(
                        name.clone(),
                        VariableChange {
                            old_value: old_value.clone(),
                            new_value: new_value.clone(),
                            type_changed,
                        },
                    );
                } else {
                    // Variable unchanged
                    unchanged.push(name.clone());
                }
            } else {
                // Variable removed
                removed.insert(name.clone(), old_value.clone());
            }
        }

        // Find added variables
        for (name, new_value) in &after.variables {
            if !before.variables.contains_key(name) {
                added.insert(name.clone(), new_value.clone());
            }
        }

        Self {
            changed,
            added,
            removed,
            unchanged,
        }
    }

    /// Render diff with ANSI colors.
    ///
    /// "With ANSI colors" is now conditional on [`crate::cli::colors`] saying
    /// colour is on. The escapes here were raw literals, so a redirected debug
    /// log and `--color never` both received them regardless (the GH #684
    /// class); an `Sgr` renders nothing when colour is off.
    #[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
    pub fn render_colored(&self) -> String {
        use crate::cli::colors as c;
        let mut output = String::new();

        output.push_str("=== Variable Diff ===\n\n");

        // Changed variables (yellow)
        if !self.changed.is_empty() {
            output.push_str(&format!("{}\n", c::colored(c::YELLOW, "Changed:")));
            for (name, change) in &self.changed {
                if change.type_changed {
                    output.push_str(&format!(
                        "  {}: {} -> {} {}\n",
                        c::colored(c::YELLOW, name),
                        change.old_value,
                        change.new_value,
                        c::colored(c::MAGENTA, "(type changed)")
                    ));
                } else {
                    output.push_str(&format!(
                        "  {}: {} -> {}\n",
                        c::colored(c::YELLOW, name),
                        change.old_value,
                        change.new_value
                    ));
                }
            }
            output.push('\n');
        }

        // Added variables (green)
        if !self.added.is_empty() {
            output.push_str(&format!("{}\n", c::colored(c::GREEN, "Added:")));
            for (name, value) in &self.added {
                output.push_str(&format!(
                    "  {}: {}\n",
                    c::colored(c::GREEN, &format!("+{name}")),
                    value
                ));
            }
            output.push('\n');
        }

        // Removed variables (red)
        if !self.removed.is_empty() {
            output.push_str(&format!("{}\n", c::colored(c::RED, "Removed:")));
            for (name, value) in &self.removed {
                output.push_str(&format!(
                    "  {}: {}\n",
                    c::colored(c::RED, &format!("-{name}")),
                    value
                ));
            }
            output.push('\n');
        }

        // Unchanged variables (dim)
        if !self.unchanged.is_empty() {
            output.push_str(&format!("{} ", c::dim("Unchanged:")));
            output.push_str(&self.unchanged.join(", "));
            output.push('\n');
        }

        output
    }

    /// Render side-by-side comparison
    #[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
    pub fn render_side_by_side(&self) -> String {
        let mut output = String::new();

        output.push_str("=== Side-by-Side Comparison ===\n\n");
        output.push_str(&format!(
            "{:<30} | {:<30}\n",
            "Snapshot #0 (Before)", "Snapshot #1 (After)"
        ));
        output.push_str(&"-".repeat(63));
        output.push('\n');

        // Show changed variables
        for (name, change) in &self.changed {
            let old_display = format!("{}: {}", name, change.old_value);
            let new_display = format!("{}: {}", name, change.new_value);
            output.push_str(&format!("{:<30} | {:<30}\n", old_display, new_display));
        }

        // Show removed variables (only in before)
        for (name, value) in &self.removed {
            let old_display = format!("{}: {}", name, value);
            output.push_str(&format!("{:<30} | {:<30}\n", old_display, "(removed)"));
        }

        // Show added variables (only in after)
        for (name, value) in &self.added {
            let new_display = format!("{}: {}", name, value);
            output.push_str(&format!("{:<30} | {:<30}\n", "(new)", new_display));
        }

        output
    }

    /// Get statistics about the diff
    #[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
    pub fn get_statistics(&self) -> DiffStatistics {
        let total_before = self.changed.len() + self.removed.len() + self.unchanged.len();
        let total_after = self.changed.len() + self.added.len() + self.unchanged.len();

        DiffStatistics {
            changed_count: self.changed.len(),
            added_count: self.added.len(),
            removed_count: self.removed.len(),
            unchanged_count: self.unchanged.len(),
            total_variables_before: total_before,
            total_variables_after: total_after,
        }
    }

    /// Export diff to JSON
    #[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
    pub fn to_json(&self) -> String {
        let mut json = serde_json::Map::new();

        // Changed variables
        let changed_obj: serde_json::Map<String, serde_json::Value> = self
            .changed
            .iter()
            .map(|(name, change)| {
                let mut change_obj = serde_json::Map::new();
                change_obj.insert("old".to_string(), change.old_value.clone());
                change_obj.insert("new".to_string(), change.new_value.clone());
                change_obj.insert(
                    "type_changed".to_string(),
                    serde_json::Value::Bool(change.type_changed),
                );
                (name.clone(), serde_json::Value::Object(change_obj))
            })
            .collect();
        json.insert(
            "changed".to_string(),
            serde_json::Value::Object(changed_obj),
        );

        // Added variables
        let added_obj: serde_json::Map<String, serde_json::Value> = self
            .added
            .iter()
            .map(|(name, value)| (name.clone(), value.clone()))
            .collect();
        json.insert("added".to_string(), serde_json::Value::Object(added_obj));

        // Removed variables
        let removed_obj: serde_json::Map<String, serde_json::Value> = self
            .removed
            .iter()
            .map(|(name, value)| (name.clone(), value.clone()))
            .collect();
        json.insert(
            "removed".to_string(),
            serde_json::Value::Object(removed_obj),
        );

        // Unchanged variables
        let unchanged_arr: Vec<serde_json::Value> = self
            .unchanged
            .iter()
            .map(|name| serde_json::Value::String(name.clone()))
            .collect();
        json.insert(
            "unchanged".to_string(),
            serde_json::Value::Array(unchanged_arr),
        );

        // Statistics
        let stats = self.get_statistics();
        let mut stats_obj = serde_json::Map::new();
        stats_obj.insert(
            "changed".to_string(),
            serde_json::Value::Number(stats.changed_count.into()),
        );
        stats_obj.insert(
            "added".to_string(),
            serde_json::Value::Number(stats.added_count.into()),
        );
        stats_obj.insert(
            "removed".to_string(),
            serde_json::Value::Number(stats.removed_count.into()),
        );
        stats_obj.insert(
            "unchanged".to_string(),
            serde_json::Value::Number(stats.unchanged_count.into()),
        );
        stats_obj.insert(
            "total_before".to_string(),
            serde_json::Value::Number(stats.total_variables_before.into()),
        );
        stats_obj.insert(
            "total_after".to_string(),
            serde_json::Value::Number(stats.total_variables_after.into()),
        );
        json.insert(
            "statistics".to_string(),
            serde_json::Value::Object(stats_obj),
        );

        serde_json::to_string_pretty(&json).expect("internal error")
    }

    /// Get type name of a JSON value
    fn value_type_name(value: &serde_json::Value) -> &'static str {
        match value {
            serde_json::Value::Null => "null",
            serde_json::Value::Bool(_) => "boolean",
            serde_json::Value::Number(_) => "number",
            serde_json::Value::String(_) => "string",
            serde_json::Value::Array(_) => "array",
            serde_json::Value::Object(_) => "object",
        }
    }
}

#[cfg_attr(coverage_nightly, coverage(off))]
#[cfg(test)]
mod tests {
    use super::*;
    use crate::services::dap::types::{SourceLocation, StackFrame};

    fn create_test_snapshot(sequence: usize) -> ExecutionSnapshot {
        ExecutionSnapshot {
            timestamp: 1000000 + (sequence as u64 * 1000),
            sequence,
            variables: std::collections::HashMap::new(),
            call_stack: vec![StackFrame {
                id: 1,
                name: "main".to_string(),
                source: None,
                line: 10,
                column: 0,
            }],
            location: SourceLocation {
                file: "test.rs".to_string(),
                line: 10,
                column: Some(0),
            },
            delta: None,
        }
    }

    #[test]
    fn test_basic_diff_computation() {
        let mut before = create_test_snapshot(0);
        before
            .variables
            .insert("x".to_string(), serde_json::json!(10));

        let mut after = create_test_snapshot(1);
        after
            .variables
            .insert("x".to_string(), serde_json::json!(15));

        let diff = VariableDiff::compute(&before, &after);

        assert_eq!(diff.changed.len(), 1);
        assert!(diff.changed.contains_key("x"));
    }

    /// `render_colored` must move in BOTH directions with `--color`.
    ///
    /// The integration test `tests/modules/variable_diff_tests.rs` can only
    /// assert the plain half — `ForcedColor` is a crate-internal test seam — and
    /// a plain-only assertion is satisfied by a renderer with no colour at all.
    /// This is the half that would catch that.
    #[test]
    fn render_colored_honours_color() {
        use crate::cli::colors::ForcedColor;

        let mut before = create_test_snapshot(0);
        before
            .variables
            .insert("x".to_string(), serde_json::json!(10));
        before
            .variables
            .insert("gone".to_string(), serde_json::json!(1));
        let mut after = create_test_snapshot(1);
        after
            .variables
            .insert("x".to_string(), serde_json::json!(15));
        after
            .variables
            .insert("new".to_string(), serde_json::json!(2));

        let diff = VariableDiff::compute(&before, &after);

        {
            let _on = ForcedColor::on();
            let coloured = diff.render_colored();
            assert!(
                coloured.contains('\u{1b}'),
                "--color always must colour the diff: {coloured:?}"
            );
        }

        let _off = ForcedColor::off();
        let plain = diff.render_colored();
        assert!(
            !plain.contains('\u{1b}'),
            "--color never must leave the diff plain: {plain:?}"
        );
        // Not vacuous: the diff body is still rendered.
        assert!(plain.contains("Changed:"), "{plain:?}");
        assert!(plain.contains("Added:"), "{plain:?}");
        assert!(plain.contains("Removed:"), "{plain:?}");
    }

    #[test]
    fn test_type_detection() {
        assert_eq!(
            VariableDiff::value_type_name(&serde_json::json!(42)),
            "number"
        );
        assert_eq!(
            VariableDiff::value_type_name(&serde_json::json!("hello")),
            "string"
        );
        assert_eq!(
            VariableDiff::value_type_name(&serde_json::json!(true)),
            "boolean"
        );
        assert_eq!(
            VariableDiff::value_type_name(&serde_json::json!([1, 2, 3])),
            "array"
        );
        assert_eq!(
            VariableDiff::value_type_name(&serde_json::json!({"key": "value"})),
            "object"
        );
    }
}