pmat 3.15.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
// Analysis rendering and stub execution methods for AdvancedUnifiedContextBuilder.
// Contains: add_big_o_analysis(), add_entropy_analysis(), add_provability_analysis(),
// add_graph_metrics(), add_tdg_analysis(), add_dead_code_analysis(), add_satd_analysis(),
// add_quality_insights(), add_recommendations(), and all run_*() stub methods.

impl AdvancedUnifiedContextBuilder {
    async fn add_big_o_analysis(&mut self) -> Result<()> {
        self.output.push_str("## Big-O Complexity Analysis\n\n");

        match self.run_big_o_analysis().await {
            Ok(analysis) => {
                if analysis.is_empty() {
                    self.output
                        .push_str("*No complexity patterns detected*\n\n");
                } else {
                    for (function, complexity) in analysis {
                        self.output
                            .push_str(&format!("- `{}`: {}\n", function, complexity));
                    }
                    self.output.push('\n');
                }
            }
            Err(e) => {
                warn!("Big-O analysis failed: {}", e);
                self.output.push_str("*Big-O analysis unavailable*\n\n");
            }
        }

        Ok(())
    }

    async fn add_entropy_analysis(&mut self) -> Result<()> {
        self.output.push_str("## Entropy Analysis\n\n");

        match self.run_entropy_analysis().await {
            Ok(entropy_data) => {
                self.output.push_str(&format!(
                    "- **Pattern Entropy**: {:.3}\n",
                    entropy_data.pattern_entropy
                ));
                self.output.push_str(&format!(
                    "- **Code Duplication**: {:.1}%\n",
                    entropy_data.duplication_percentage
                ));
                self.output.push_str(&format!(
                    "- **Structural Entropy**: {:.3}\n",
                    entropy_data.structural_entropy
                ));

                if !entropy_data.actionable_items.is_empty() {
                    self.output.push_str("\n### Actionable Improvements:\n");
                    for item in &entropy_data.actionable_items {
                        self.output.push_str(&format!("- {}\n", item));
                    }
                }
                self.output.push('\n');
            }
            Err(e) => {
                warn!("Entropy analysis failed: {}", e);
                self.output.push_str("*Entropy analysis unavailable*\n\n");
            }
        }

        Ok(())
    }

    async fn add_provability_analysis(&mut self) -> Result<()> {
        self.output.push_str("## Provability Analysis\n\n");

        match self.run_provability_analysis().await {
            Ok(provability_data) => {
                self.output.push_str("### Invariants\n");
                for invariant in &provability_data.invariants {
                    self.output.push_str(&format!("- {}\n", invariant));
                }

                self.output.push_str("\n### Pre-conditions\n");
                for pre in &provability_data.preconditions {
                    self.output.push_str(&format!("- {}\n", pre));
                }

                self.output.push_str("\n### Post-conditions\n");
                for post in &provability_data.postconditions {
                    self.output.push_str(&format!("- {}\n", post));
                }

                self.output.push_str(&format!(
                    "\n### Verification Status: {}\n",
                    if provability_data.verified {
                        "✓ Verified"
                    } else {
                        "⚠ Unverified"
                    }
                ));
                self.output.push('\n');
            }
            Err(e) => {
                warn!("Provability analysis failed: {}", e);
                self.output
                    .push_str("*Provability analysis unavailable*\n\n");
            }
        }

        Ok(())
    }

    async fn add_graph_metrics(&mut self) -> Result<()> {
        self.output.push_str("## Graph Metrics\n\n");

        match self.run_graph_metrics_analysis().await {
            Ok(graph_data) => {
                self.output.push_str("### Centrality Measures\n");
                self.output.push_str(&format!(
                    "- **Betweenness Centrality**: {:.3}\n",
                    graph_data.betweenness
                ));
                self.output.push_str(&format!(
                    "- **Closeness Centrality**: {:.3}\n",
                    graph_data.closeness
                ));
                self.output.push_str(&format!(
                    "- **Degree Centrality**: {:.3}\n",
                    graph_data.degree
                ));

                self.output.push_str("\n### Graph Structure\n");
                self.output
                    .push_str(&format!("- **Nodes**: {}\n", graph_data.node_count));
                self.output
                    .push_str(&format!("- **Edges**: {}\n", graph_data.edge_count));
                self.output
                    .push_str(&format!("- **Density**: {:.3}\n", graph_data.density));

                if !graph_data.critical_paths.is_empty() {
                    self.output.push_str("\n### Critical Paths\n");
                    for path in &graph_data.critical_paths {
                        self.output.push_str(&format!("- {}\n", path));
                    }
                }
                self.output.push('\n');
            }
            Err(e) => {
                warn!("Graph metrics analysis failed: {}", e);
                self.output.push_str("*Graph metrics unavailable*\n\n");
            }
        }

        Ok(())
    }

    async fn add_tdg_analysis(&mut self) -> Result<()> {
        self.output.push_str("## Technical Debt Gradient (TDG)\n\n");

        match self.run_tdg_analysis().await {
            Ok(tdg_data) => {
                self.output.push_str(&format!(
                    "### Overall TDG Score: {:.2}\n\n",
                    tdg_data.overall_score
                ));

                if !tdg_data.file_scores.is_empty() {
                    self.output.push_str("### File-level TDG Scores\n");
                    for (file, score) in &tdg_data.file_scores {
                        self.output
                            .push_str(&format!("- `{}`: {:.2}\n", file, score));
                    }
                }

                if !tdg_data.hotspots.is_empty() {
                    self.output.push_str("\n### Debt Hotspots\n");
                    for hotspot in &tdg_data.hotspots {
                        self.output.push_str(&format!(
                            "- {} (Score: {:.2})\n",
                            hotspot.location, hotspot.score
                        ));
                    }
                }

                if !tdg_data.priorities.is_empty() {
                    self.output.push_str("\n### Refactoring Priorities\n");
                    for (i, priority) in tdg_data.priorities.iter().enumerate().take(5) {
                        self.output.push_str(&format!("{}. {}\n", i + 1, priority));
                    }
                }
                self.output.push('\n');
            }
            Err(e) => {
                warn!("TDG analysis failed: {}", e);
                self.output.push_str("*TDG analysis unavailable*\n\n");
            }
        }

        Ok(())
    }

    async fn add_dead_code_analysis(&mut self) -> Result<()> {
        self.output.push_str("## Dead Code Analysis\n\n");

        match self.run_dead_code_analysis().await {
            Ok(dead_code_data) => {
                let total_dead = dead_code_data.total_dead_items();

                if total_dead == 0 {
                    self.output.push_str("✓ No dead code detected\n\n");
                } else {
                    self.output
                        .push_str(&format!("⚠ Total dead code items: {}\n\n", total_dead));

                    if !dead_code_data.unreachable_functions.is_empty() {
                        self.output.push_str("### Unreachable Functions\n");
                        for func in &dead_code_data.unreachable_functions {
                            self.output.push_str(&format!("- `{}`\n", func));
                        }
                    }

                    if !dead_code_data.unused_variables.is_empty() {
                        self.output.push_str("\n### Unused Variables\n");
                        for var in &dead_code_data.unused_variables {
                            self.output.push_str(&format!("- `{}`\n", var));
                        }
                    }

                    if !dead_code_data.unused_imports.is_empty() {
                        self.output.push_str("\n### Unused Imports\n");
                        for import in &dead_code_data.unused_imports {
                            self.output.push_str(&format!("- `{}`\n", import));
                        }
                    }
                }
                self.output.push('\n');
            }
            Err(e) => {
                warn!("Dead code analysis failed: {}", e);
                self.output.push_str("*Dead code analysis unavailable*\n\n");
            }
        }

        Ok(())
    }

    async fn add_satd_analysis(&mut self) -> Result<()> {
        self.output
            .push_str("## Self-Admitted Technical Debt (SATD)\n\n");

        match self.run_satd_analysis().await {
            Ok(satd_data) => {
                let total_satd = satd_data.total_satd_count();

                self.output
                    .push_str(&format!("### Total SATD Comments: {}\n\n", total_satd));

                if !satd_data.todos.is_empty() {
                    self.output
                        .push_str(&format!("### TODO Comments ({})\n", satd_data.todos.len()));
                    for todo in satd_data.todos.iter().take(5) {
                        self.output
                            .push_str(&format!("- {}: {}\n", todo.location, todo.comment));
                    }
                    if satd_data.todos.len() > 5 {
                        self.output
                            .push_str(&format!("- ... and {} more\n", satd_data.todos.len() - 5));
                    }
                }

                if !satd_data.fixmes.is_empty() {
                    self.output.push_str(&format!(
                        "\n### FIXME Comments ({})\n",
                        satd_data.fixmes.len()
                    ));
                    for fixme in satd_data.fixmes.iter().take(3) {
                        self.output
                            .push_str(&format!("- {}: {}\n", fixme.location, fixme.comment));
                    }
                }

                if !satd_data.hacks.is_empty() {
                    self.output.push_str(&format!(
                        "\n### HACK Comments ({})\n",
                        satd_data.hacks.len()
                    ));
                    for hack in satd_data.hacks.iter().take(3) {
                        self.output
                            .push_str(&format!("- {}: {}\n", hack.location, hack.comment));
                    }
                }

                self.output.push_str("\n### Debt Categories\n");
                self.output
                    .push_str(&format!("- **Design Debt**: {}\n", satd_data.design_debt));
                self.output
                    .push_str(&format!("- **Code Debt**: {}\n", satd_data.code_debt));
                self.output
                    .push_str(&format!("- **Test Debt**: {}\n", satd_data.test_debt));
                self.output.push_str(&format!(
                    "- **Documentation Debt**: {}\n",
                    satd_data.doc_debt
                ));
                self.output.push('\n');
            }
            Err(e) => {
                warn!("SATD analysis failed: {}", e);
                self.output.push_str("*SATD analysis unavailable*\n\n");
            }
        }

        Ok(())
    }

    fn add_quality_insights(&mut self, context: &ProjectContext) {
        self.output.push_str("## Quality Insights\n\n");

        let total_functions = context.summary.total_functions;
        let total_files = context.summary.total_files;

        if total_functions > 0 {
            let avg_functions_per_file = total_functions as f64 / total_files.max(1) as f64;

            self.output.push_str(&format!(
                "- **Codebase Size**: {} functions across {} files\n",
                total_functions, total_files
            ));
            self.output.push_str(&format!(
                "- **Average Functions per File**: {:.1}\n",
                avg_functions_per_file
            ));

            if avg_functions_per_file > 10.0 {
                self.output
                    .push_str("- ⚠ High function density - consider modularization\n");
            }

            // Calculate complexity insights
            let mut high_complexity_count = 0;
            for file in &context.files {
                if let Some(complexity) = &file.complexity_metrics {
                    // Count based on cyclomatic complexity threshold
                    if complexity.total_complexity.cyclomatic > 10 {
                        high_complexity_count += 1;
                    }
                }
            }

            if high_complexity_count > 0 {
                self.output.push_str(&format!(
                    "- ⚠ High complexity functions: {}\n",
                    high_complexity_count
                ));
            }
        }

        self.output.push('\n');
    }

    fn add_recommendations(&mut self, context: &ProjectContext) {
        self.output.push_str("## Recommendations\n\n");

        let mut recommendations = Vec::new();

        // Based on function count
        if context.summary.total_functions > 100 {
            recommendations
                .push("Consider breaking down large modules into smaller, focused components");
        }

        // Based on complexity
        let mut total_complexity: usize = 0;
        let mut file_count = 0;
        for file in &context.files {
            if let Some(complexity) = &file.complexity_metrics {
                total_complexity += complexity.total_complexity.cyclomatic as usize;
                file_count += 1;
            }
        }

        if file_count > 0 {
            let avg_complexity = total_complexity as f64 / file_count as f64;
            if avg_complexity > 10.0 {
                recommendations
                    .push("High average complexity detected - refactor complex functions");
            }
        }

        // Always add these recommendations
        recommendations.push("Enable all analysis features for comprehensive insights");
        recommendations.push("Review identified technical debt and create action items");
        recommendations.push("Monitor TDG scores over time to track improvement");

        for rec in recommendations {
            self.output.push_str(&format!("- {}\n", rec));
        }

        self.output.push('\n');
    }

    // Analysis execution methods (stubs)
    async fn run_big_o_analysis(&self) -> Result<HashMap<String, String>> {
        // Stub - integrate with actual BigOAnalyzer
        Ok(HashMap::new())
    }

    async fn run_entropy_analysis(&self) -> Result<EntropyData> {
        // Stub - integrate with actual entropy analyzer
        Ok(EntropyData {
            pattern_entropy: 0.75,
            duplication_percentage: 16.4,
            structural_entropy: 0.82,
            actionable_items: vec![],
        })
    }

    async fn run_provability_analysis(&self) -> Result<ProvabilityData> {
        // Stub - integrate with actual provability analyzer
        Ok(ProvabilityData {
            invariants: vec![],
            preconditions: vec![],
            postconditions: vec![],
            verified: false,
        })
    }

    async fn run_graph_metrics_analysis(&self) -> Result<GraphMetricsData> {
        // Stub - integrate with actual graph analyzer
        Ok(GraphMetricsData {
            betweenness: 0.0,
            closeness: 0.0,
            degree: 0.0,
            node_count: 0,
            edge_count: 0,
            density: 0.0,
            critical_paths: vec![],
        })
    }

    async fn run_tdg_analysis(&self) -> Result<TdgData> {
        // Stub - integrate with actual TDG analyzer
        Ok(TdgData {
            overall_score: 0.0,
            file_scores: HashMap::new(),
            hotspots: vec![],
            priorities: vec![],
        })
    }

    async fn run_dead_code_analysis(&self) -> Result<DeadCodeData> {
        // Stub - integrate with actual dead code analyzer
        Ok(DeadCodeData {
            unreachable_functions: vec![],
            unused_variables: vec![],
            unused_imports: vec![],
        })
    }

    async fn run_satd_analysis(&self) -> Result<SatdData> {
        // Stub - integrate with actual SATD analyzer
        Ok(SatdData {
            todos: vec![],
            fixmes: vec![],
            hacks: vec![],
            design_debt: 0,
            code_debt: 0,
            test_debt: 0,
            doc_debt: 0,
        })
    }
}