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
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
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
# WebAssembly (WASM) Features in PMAT

## Table of Contents
- [Overview]#overview
- [Quick Start]#quick-start
- [Core Features]#core-features
- [Usage Guide]#usage-guide
- [Integration Examples]#integration-examples
- [Technical Architecture]#technical-architecture
- [API Reference]#api-reference

## Overview

PMAT v2.77.0 introduces comprehensive WebAssembly module analysis capabilities, providing enterprise-grade quality assurance for WASM binaries. This feature suite is designed to analyze, verify, and optimize WebAssembly modules, with special support for Ruchy language notebooks and other WASM-based applications.

### Key Capabilities
- 🔍 **Deep Analysis**: Function-level complexity metrics and instruction profiling
- 🔒 **Formal Verification**: Mathematical proof of memory safety and type correctness
- 🛡️ **Security Scanning**: Pattern-based vulnerability detection
- 📊 **Performance Profiling**: Non-intrusive shadow stack profiling
- 📈 **Quality Baselines**: Multi-anchor regression detection system

## Quick Start

### Basic Analysis
```bash
# Analyze a WASM module
pmat analyze wasm module.wasm

# Output:
# WASM Analysis Summary
# ====================
# Functions: 42
# Instructions: 1337
# Binary Size: 65536 bytes
# Max Complexity: 15
```

### Complete Analysis Suite
```bash
# Run all analysis features
pmat analyze wasm module.wasm \
  --verify \      # Formal verification
  --security \    # Security scanning
  --profile \     # Performance profiling
  --baseline reference.wasm  # Quality comparison
```

## Core Features

### 1. Streaming Analysis Pipeline

PMAT uses a streaming parser to handle WASM files of any size efficiently:

```rust
// Internal architecture
WasmAnalyzer {
    parser: StreamingParser,      // Handles GB-sized files
    validator: IncrementalValidator,
    profiler: ShadowStackProfiler,
    detector: PatternDetector,
}
```

**Benefits:**
- Memory-efficient processing
- Real-time analysis feedback
- Support for large WASM binaries (>100MB)
- Progressive results reporting

### 2. Formal Verification

Mathematical verification of WASM module safety properties:

```bash
pmat analyze wasm module.wasm --verify
```

**Verification Checks:**
- **Memory Bounds**: All memory accesses proven within allocated bounds
- **Type Safety**: Stack operations maintain type consistency
- **Stack Balance**: Functions preserve stack discipline
- **Integer Safety**: Arithmetic operations checked for overflow
- **Control Flow**: Indirect calls validated against function table

**Example Output:**
```
Verification Result: ✅ SAFE
- Memory accesses: All bounded
- Type consistency: Maintained
- Stack balance: Verified
- Integer operations: No overflows detected
```

### 3. Security Vulnerability Scanning

Pattern-based detection of common WASM security issues:

```bash
pmat analyze wasm module.wasm --security
```

**Detected Patterns:**

| Pattern | Severity | Description |
|---------|----------|-------------|
| Buffer Overflow | Critical | Unchecked memory access that could exceed bounds |
| Integer Overflow | High | Arithmetic operations without overflow checks |
| Memory Growth | High | Unbounded memory.grow operations |
| Indirect Call | Medium | Unvalidated function pointer usage |
| Stack Overflow | Medium | Recursive calls without depth limits |
| Uninitialized Memory | Low | Reading memory before initialization |

**SARIF Output for CI/CD:**
```bash
pmat analyze wasm module.wasm --security --format sarif --output security.sarif
```

### 4. Performance Profiling

Non-intrusive shadow stack profiling for performance analysis:

```bash
pmat analyze wasm module.wasm --profile
```

**Profiling Metrics:**

```
Performance Profile
===================
Instruction Mix:
  Control Flow: 15% (branches, loops)
  Memory Ops: 25% (loads, stores)
  Arithmetic: 40% (math operations)
  Function Calls: 20% (direct, indirect)

Hot Functions (>5% time):
  1. process_data - 18.5% (4,231 samples)
  2. validate_input - 12.3% (2,812 samples)
  3. compute_hash - 8.7% (1,987 samples)

Memory Profile:
  Peak Usage: 4.2 MB
  Growth Events: 3
  Average Allocation: 256 KB
```

### 5. Quality Baselines

Compare WASM modules against reference baselines:

```bash
pmat analyze wasm current.wasm --baseline stable.wasm
```

**Multi-Anchor System:**

```yaml
Baselines:
  release:       # Stable production version
    complexity: 15
    size: 64KB
    performance: 100ms
    
  preview:       # Beta version
    complexity: 18
    size: 68KB
    performance: 95ms
    
  experimental:  # Development version
    complexity: 22
    size: 72KB
    performance: 90ms
```

**Quality Assessment:**
```
Quality Comparison
==================
Current vs Baseline (stable.wasm):
  ✅ Complexity: 14 (-1, improved)
  ⚠️ Size: 66KB (+2KB, increased)
  ✅ Performance: 98ms (-2ms, faster)
  
Overall: PASSING (no regressions)
Recommendation: Safe to deploy
```

## Usage Guide

### Analyzing Ruchy Notebooks

Ruchy language notebooks compile to WASM for execution. PMAT provides specialized analysis:

```bash
# Analyze Ruchy notebook WASM
pmat analyze wasm ../ruchy/notebooks/data_analysis.wasm \
  --verify \
  --profile \
  --output analysis.md

# Compare notebook versions
pmat analyze wasm ../ruchy/notebooks/v2/analysis.wasm \
  --baseline ../ruchy/notebooks/v1/analysis.wasm
```

### CI/CD Integration

#### GitHub Actions
```yaml
name: WASM Quality Gate
on: [push, pull_request]

jobs:
  wasm-analysis:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      
      - name: Install PMAT
        run: cargo install pmat
      
      - name: Build WASM
        run: cargo build --target wasm32-unknown-unknown
      
      - name: Analyze WASM Security
        run: |
          pmat analyze wasm target/wasm32-unknown-unknown/release/app.wasm \
            --security \
            --format sarif \
            --output wasm-security.sarif
      
      - name: Upload SARIF
        uses: github/codeql-action/upload-sarif@v2
        with:
          sarif_file: wasm-security.sarif
      
      - name: Quality Gate
        run: |
          pmat analyze wasm target/wasm32-unknown-unknown/release/app.wasm \
            --verify \
            --baseline .github/baseline.wasm
```

#### Pre-commit Hook
```bash
#!/bin/bash
# .git/hooks/pre-commit

# Check all WASM files
for wasm in $(git diff --cached --name-only | grep "\.wasm$"); do
  echo "Analyzing $wasm..."
  
  # Security check
  pmat analyze wasm "$wasm" --security --verify
  if [ $? -ne 0 ]; then
    echo "❌ WASM analysis failed for $wasm"
    exit 1
  fi
done

echo "✅ All WASM files passed quality checks"
```

### Makefile Integration

```makefile
# WASM analysis targets
.PHONY: wasm-check wasm-security wasm-profile wasm-baseline

WASM_FILE := build/module.wasm
BASELINE_WASM := releases/stable.wasm

wasm-check: $(WASM_FILE)
	@echo "Running comprehensive WASM analysis..."
	pmat analyze wasm $(WASM_FILE) \
	  --verify \
	  --security \
	  --profile \
	  --baseline $(BASELINE_WASM)

wasm-security: $(WASM_FILE)
	@echo "Security scanning WASM module..."
	pmat analyze wasm $(WASM_FILE) \
	  --security \
	  --format sarif \
	  --output reports/wasm-security.sarif

wasm-profile: $(WASM_FILE)
	@echo "Profiling WASM performance..."
	pmat analyze wasm $(WASM_FILE) \
	  --profile \
	  --format json \
	  --output reports/wasm-profile.json

wasm-baseline: $(WASM_FILE)
	@echo "Comparing against baseline..."
	pmat analyze wasm $(WASM_FILE) \
	  --baseline $(BASELINE_WASM) \
	  --format detailed \
	  --verbose
```

## Integration Examples

### 1. Automated Security Scanning

```python
#!/usr/bin/env python3
"""Automated WASM security scanner"""

import subprocess
import json
import sys

def scan_wasm(wasm_file):
    """Run security scan on WASM file"""
    result = subprocess.run([
        'pmat', 'analyze', 'wasm', wasm_file,
        '--security', '--format', 'json'
    ], capture_output=True, text=True)
    
    if result.returncode != 0:
        print(f"Error scanning {wasm_file}: {result.stderr}")
        return None
    
    return json.loads(result.stdout)

def main():
    wasm_files = sys.argv[1:]
    
    for wasm_file in wasm_files:
        print(f"Scanning {wasm_file}...")
        results = scan_wasm(wasm_file)
        
        if results and results.get('security'):
            critical = [v for v in results['security'] 
                       if v['severity'] == 'Critical']
            if critical:
                print(f"❌ {len(critical)} critical vulnerabilities found!")
                for vuln in critical:
                    print(f"  - {vuln['pattern']} at {vuln['location']}")
                sys.exit(1)
    
    print("✅ All WASM files passed security scan")

if __name__ == '__main__':
    main()
```

### 2. Performance Regression Detection

```bash
#!/bin/bash
# detect_performance_regression.sh

CURRENT_WASM=$1
BASELINE_WASM=$2
THRESHOLD=10  # 10% regression threshold

# Run performance comparison
OUTPUT=$(pmat analyze wasm "$CURRENT_WASM" \
  --profile \
  --baseline "$BASELINE_WASM" \
  --format json)

# Extract performance metrics
CURRENT_TIME=$(echo "$OUTPUT" | jq '.profiling.estimated_runtime_ms')
BASELINE_TIME=$(echo "$OUTPUT" | jq '.baseline.estimated_runtime_ms')

# Calculate regression percentage
REGRESSION=$(echo "scale=2; (($CURRENT_TIME - $BASELINE_TIME) / $BASELINE_TIME) * 100" | bc)

if (( $(echo "$REGRESSION > $THRESHOLD" | bc -l) )); then
  echo "❌ Performance regression detected: ${REGRESSION}%"
  echo "Current: ${CURRENT_TIME}ms, Baseline: ${BASELINE_TIME}ms"
  exit 1
fi

echo "✅ Performance acceptable: ${REGRESSION}% change"
```

### 3. Quality Dashboard Integration

```javascript
// wasm-quality-dashboard.js
const { exec } = require('child_process');
const express = require('express');
const app = express();

app.get('/api/wasm/analyze/:module', async (req, res) => {
  const module = req.params.module;
  
  exec(`pmat analyze wasm ${module} --format json`, (error, stdout) => {
    if (error) {
      return res.status(500).json({ error: error.message });
    }
    
    const analysis = JSON.parse(stdout);
    
    // Calculate quality score
    const score = calculateQualityScore(analysis);
    
    res.json({
      module,
      score,
      grade: getGrade(score),
      analysis
    });
  });
});

function calculateQualityScore(analysis) {
  let score = 100;
  
  // Deduct for complexity
  score -= Math.max(0, analysis.max_complexity - 10) * 2;
  
  // Deduct for security issues
  if (analysis.security) {
    analysis.security.forEach(vuln => {
      if (vuln.severity === 'Critical') score -= 10;
      if (vuln.severity === 'High') score -= 5;
      if (vuln.severity === 'Medium') score -= 2;
    });
  }
  
  // Deduct for verification failures
  if (analysis.verification && !analysis.verification.is_safe) {
    score -= 20;
  }
  
  return Math.max(0, score);
}

function getGrade(score) {
  if (score >= 90) return 'A+';
  if (score >= 80) return 'A';
  if (score >= 70) return 'B';
  if (score >= 60) return 'C';
  return 'F';
}

app.listen(3000, () => {
  console.log('WASM Quality Dashboard running on port 3000');
});
```

## Technical Architecture

### Component Overview

```
┌─────────────────────────────────────────────┐
│            WASM Analysis Pipeline           │
├─────────────────────────────────────────────┤
│                                             │
│  ┌─────────────┐      ┌─────────────┐      │
│  │   Binary    │─────▶│  Streaming  │      │
│  │   Input     │      │   Parser    │      │
│  └─────────────┘      └─────────────┘      │
│                              │              │
│                              ▼              │
│                    ┌─────────────────┐     │
│                    │    Validator    │     │
│                    │  (Incremental)  │     │
│                    └─────────────────┘     │
│                              │              │
│          ┌───────────────────┼───────────┐  │
│          ▼                   ▼           ▼  │
│   ┌──────────┐     ┌──────────┐  ┌──────────┐
│   │Security  │     │ Profiler │  │Baseline  │
│   │ Scanner  │     │  Shadow  │  │Comparator│
│   └──────────┘     └──────────┘  └──────────┘
│          │                   │           │  │
│          └───────────────────┼───────────┘  │
│                              ▼              │
│                    ┌─────────────────┐     │
│                    │  Output Format  │     │
│                    │  (JSON/SARIF)   │     │
│                    └─────────────────┘     │
│                                             │
└─────────────────────────────────────────────┘
```

### Key Components

1. **Streaming Parser** (`wasm/analyzer.rs`)
   - Uses `wasmparser` crate for efficient parsing
   - Processes modules incrementally
   - Maintains minimal memory footprint

2. **Incremental Verifier** (`wasm/verifier.rs`)
   - Function-by-function verification
   - Shadow stack for type checking
   - SMT solver integration ready

3. **Pattern Detector** (`wasm/security.rs`)
   - AST pattern matching
   - Vulnerability signature database
   - Confidence scoring system

4. **Shadow Stack Profiler** (`wasm/profiler.rs`)
   - Non-intrusive profiling
   - Statistical sampling
   - Call graph construction

5. **Baseline Comparator** (`wasm/baseline.rs`)
   - Multi-anchor system
   - Fuzzy matching for hardware differences
   - Regression detection algorithms

### Performance Characteristics

| Operation | Time Complexity | Space Complexity |
|-----------|----------------|------------------|
| Parsing | O(n) | O(1) streaming |
| Verification | O(n*m) | O(m) per function |
| Security Scan | O(n*p) | O(p) patterns |
| Profiling | O(n*s) | O(s) samples |
| Baseline | O(n) | O(1) comparison |

Where:
- n = module size
- m = function complexity
- p = pattern count
- s = sample rate

## API Reference

### CLI Commands

#### `pmat analyze wasm`

Analyze WebAssembly modules for quality, security, and performance.

**Syntax:**
```bash
pmat analyze wasm <wasm_file> [OPTIONS]
```

**Options:**
| Option | Description | Default |
|--------|-------------|---------|
| `--verify` | Enable formal verification | false |
| `--security` | Enable security scanning | false |
| `--profile` | Enable performance profiling | false |
| `--baseline <path>` | Compare against baseline WASM | none |
| `--format <format>` | Output format (summary/json/detailed/sarif) | summary |
| `--output <path>` | Write output to file | stdout |
| `--verbose` | Enable verbose output | false |

**Examples:**
```bash
# Basic analysis
pmat analyze wasm app.wasm

# Security focus
pmat analyze wasm app.wasm --security --format sarif

# Performance analysis
pmat analyze wasm app.wasm --profile --verbose

# Full suite
pmat analyze wasm app.wasm --verify --security --profile
```

### Output Formats

#### Summary Format
Human-readable summary of key metrics:
```
WASM Analysis Summary
====================
Functions: 42
Instructions: 1337
Binary Size: 65536 bytes
Memory Pages: 4
Max Complexity: 15

Verification: ✅ SAFE
Security: ⚠️ 3 medium issues
Performance: 95/100
```

#### JSON Format
Machine-readable complete analysis:
```json
{
  "analysis": {
    "function_count": 42,
    "instruction_count": 1337,
    "binary_size": 65536,
    "memory_pages": 4,
    "max_complexity": 15
  },
  "verification": {
    "is_safe": true,
    "checks": {
      "memory_bounds": "passed",
      "type_safety": "passed",
      "stack_balance": "passed"
    }
  },
  "security": [
    {
      "severity": "Medium",
      "pattern": "unchecked_memory_access",
      "location": "function[5]",
      "confidence": 0.85
    }
  ],
  "profiling": {
    "instruction_mix": {
      "control_flow": 0.15,
      "memory_ops": 0.25,
      "arithmetic": 0.40,
      "calls": 0.20
    },
    "hot_functions": [
      {
        "name": "process_data",
        "percentage": 18.5,
        "samples": 4231
      }
    ]
  }
}
```

#### SARIF Format
Static Analysis Results Interchange Format for CI/CD:
```json
{
  "$schema": "https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json",
  "version": "2.1.0",
  "runs": [{
    "tool": {
      "driver": {
        "name": "pmat-wasm-analyzer",
        "version": "2.77.0",
        "rules": [...]
      }
    },
    "results": [...]
  }]
}
```

### Error Codes

| Code | Description | Resolution |
|------|-------------|------------|
| `WASM001` | Invalid WASM magic number | Ensure file is valid WASM binary |
| `WASM002` | Unsupported WASM version | Update to WASM version 1 |
| `WASM003` | Parsing error | Check WASM binary integrity |
| `WASM004` | Verification timeout | Simplify module or increase timeout |
| `WASM005` | Pattern database missing | Update PMAT installation |

## Best Practices

### 1. Regular Analysis
- Run analysis on every build
- Track metrics over time
- Set quality thresholds

### 2. Security First
- Always run security scanning
- Fix critical issues immediately
- Review medium/low issues regularly

### 3. Performance Monitoring
- Profile before optimization
- Compare against baselines
- Track regression trends

### 4. CI/CD Integration
- Automate quality gates
- Fail builds on regressions
- Generate reports for review

### 5. Baseline Management
- Maintain stable baselines
- Update baselines carefully
- Document baseline changes

## Troubleshooting

### Common Issues

**Issue: "Invalid WASM magic number"**
- Ensure file is a valid WebAssembly binary
- Check file hasn't been corrupted
- Verify build process generates WASM

**Issue: "Verification timeout"**
- Module may be too complex
- Try analyzing smaller functions
- Increase timeout with `--timeout`

**Issue: "No baseline found"**
- Ensure baseline file exists
- Check file path is correct
- Verify baseline is valid WASM

**Issue: "Security pattern not found"**
- Update PMAT to latest version
- Pattern database may be outdated
- Report issue if persists

## Related Documentation

- [WASM Analysis Guide]./wasm-analysis-guide.md - Detailed usage guide
- [WASM Quality Assurance Specification]./specifications/components/wasm.md - Technical specification
- [Quality Gates Guide]./quality-gates.md - Integration with quality gates
- [MCP Integration]./mcp-integration.md - Using WASM analysis via MCP

## Support

For issues, questions, or feature requests:
- GitHub Issues: [paiml/paiml-mcp-agent-toolkit]https://github.com/paiml/paiml-mcp-agent-toolkit/issues
- Documentation: [docs.paiml.com]https://docs.paiml.com
- Community: [Discord]https://discord.gg/paiml