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
# TypeScript/JavaScript Mutation Testing

**Status:** โœ… Production Ready (v2.144.0+)
**Languages:** TypeScript, JavaScript (ES6+, JSX, TSX)
**Quality:** 80%+ mutation score achievable

---

## Overview

PMAT provides **AST-based mutation testing** for TypeScript and JavaScript projects, helping you validate test suite quality by introducing controlled bugs (mutations) and checking if your tests catch them.

**Key Benefits:**
- ๐ŸŽฏ Quantify test quality with mutation scores
- ๐Ÿ” Identify gaps in test coverage
- โšก Fast generation (14ms for 67 mutants)
- ๐Ÿงฌ 5 mutation operators covering common bug patterns
- ๐Ÿ”„ Works with jest, vitest, and mocha

---

## Quick Start

### 1. Install Dependencies

```bash
cd fixtures/typescript
npm install  # Install vitest/jest
```

### 2. Run Mutation Testing

```bash
# From project root
cargo run --example typescript_mutation_workflow --features typescript-ast

# Or build the example first
cargo build --example typescript_mutation_workflow --features typescript-ast
./target/debug/examples/typescript_mutation_workflow
```

### 3. View Results

```
๐Ÿงฌ TypeScript Mutation Testing Workflow

๐Ÿ“ Reading source file: fixtures/typescript/calculator.ts
   Size: 1,776 bytes

๐Ÿ”ง Generating mutants...
   Generated: 67 mutants
   Time: 14ms

โœ… Running baseline tests...
   Baseline tests passed โœ…

๐Ÿงช Testing mutants (67 total)...
   [Progress updates...]

๐Ÿ“Š Mutation Testing Results
   Total Mutants:    67
   Killed:           54 (80%)
   Survived:         13 (19%)
   Timeout/Error:    0

๐ŸŽฏ Mutation Score: 80% โœ… EXCELLENT!
```

---

## Mutation Operators

### 1. Arithmetic Operator Replacement (AOR)

**Replaces:** `+`, `-`, `*`, `/`, `%`

```typescript
// Original
function add(a: number, b: number) {
    return a + b;
}

// Mutants
return a - b;  // + โ†’ -
return a * b;  // + โ†’ *
return a / b;  // + โ†’ /
```

**Tests should fail** when arithmetic operators are changed.

### 2. Strict Equality Mutation

**Replaces:** `===`, `!==` with `==`, `!=`

```typescript
// Original
if (value === 0) {
    return true;
}

// Mutants
if (value == 0) {   // === โ†’ ==  (type coercion!)
if (value !== 0) {  // === โ†’ !== (negation)
```

**Tests should fail** when type-safe equality is weakened.

### 3. Optional Chaining Mutation

**Replaces:** `?.` with `.`

```typescript
// Original
return obj?.nested?.value;

// Mutant
return obj.nested.value;  // ?. โ†’ . (will throw if null!)
```

**Tests should fail** when null safety is removed.

### 4. Nullish Coalescing Mutation

**Replaces:** `??` with `||`

```typescript
// Original
return value ?? defaultValue;

// Mutant
return value || defaultValue;  // ?? โ†’ || (falsy vs nullish!)
```

**Tests should fail** when nullish behavior changes.

### 5. Async/Await Mutation

**Removes:** `async` and `await` keywords

```typescript
// Original
async function fetchValue(): Promise<number> {
    return await Promise.resolve(42);
}

// Mutants
function fetchValue(): Promise<number> {    // Remove async
    return Promise.resolve(42);             // Remove await
}
```

**Tests should fail** when Promise handling is broken.

---

## Understanding Mutation Scores

### Score Interpretation

| Score | Quality | Recommendation |
|-------|---------|----------------|
| **90-100%** | Excellent | Maintain current quality |
| **80-89%** | Good | Minor improvements needed |
| **70-79%** | Acceptable | Add targeted tests |
| **60-69%** | Weak | Significant gaps exist |
| **< 60%** | Poor | Major test suite overhaul needed |

### What Mutation Scores Tell You

**High Score (80%+):**
- โœ… Tests catch most bugs
- โœ… Good coverage of edge cases
- โœ… Type safety validated
- โœ… Error conditions tested

**Low Score (<70%):**
- โŒ Tests miss common bug patterns
- โŒ Weak edge case coverage
- โŒ Type coercion not tested
- โŒ Happy path bias

---

## Surviving Mutants (Test Weaknesses)

Surviving mutants indicate **real gaps** in your test suite:

### Example: Type Coercion Gap

**Mutant:** `===` โ†’ `==` (survives)

```typescript
// Code
if (b === 0) {
    throw new Error("Division by zero");
}

// Test (weak!)
expect(() => divide(10, 0)).toThrow();
// Passes even with b == 0 because all inputs are numbers!

// Better test
expect(() => divide(10, "0")).toThrow();  // Would fail with ==
```

### Example: Boundary Condition Gap

**Mutant:** `>` โ†’ `>=` (survives)

```typescript
// Code
return a > b ? a : b;

// Test (weak!)
expect(max(5, 3)).toBe(5);
// Passes even with >= because 5 > 3

// Better test
expect(max(5, 5)).toBe(5);  // Would fail with >= edge case
```

### Example: Async Testing Gap

**Mutant:** Remove `await` (survives)

```typescript
// Code
return await Promise.resolve(42);

// Test (weak!)
const result = fetchValue();
expect(result).resolves.toBeDefined();
// Passes even without await (returns Promise)

// Better test
const result = await fetchValue();
expect(typeof result).toBe('number');  // Would fail without await
```

---

## Example Project Structure

```
my-typescript-project/
โ”œโ”€โ”€ src/
โ”‚   โ”œโ”€โ”€ calculator.ts          # Source code
โ”‚   โ””โ”€โ”€ calculator.test.ts     # Tests
โ”œโ”€โ”€ package.json               # Test framework config
โ”œโ”€โ”€ tsconfig.json
โ””โ”€โ”€ node_modules/              # Must run npm install
```

### Minimal package.json

```json
{
  "scripts": {
    "test": "vitest run"
  },
  "devDependencies": {
    "vitest": "^2.0.0",
    "typescript": "^5.0.0"
  }
}
```

---

## Advanced Usage

### Parallel Execution (Experimental)

```bash
cargo run --example typescript_mutation_workflow_parallel --features typescript-ast
```

**Benefits:**
- Uses multiple CPU cores
- Potential 8x speedup
- Same mutation score

**Note:** File locking prevents conflicts but serializes file I/O.

### Programmatic Usage

```rust
use pmat::services::mutation::TypeScriptMutationGenerator;

// Generate mutants
let generator = TypeScriptMutationGenerator::with_default_operators();
let mutants = generator.generate_mutants(&source, "test.ts")?;

// Process mutants
for mutant in mutants {
    println!("Mutant: {} at line {}", mutant.id, mutant.location.line);
}
```

---

## Limitations & Known Issues

### Current Limitations

1. **Single-file testing** - Multi-file projects not yet supported
2. **npm startup overhead** - Each mutant restarts test framework (~1.8s)
3. **No test selection** - Runs all tests for each mutant
4. **Sequential execution** - No true parallel testing yet

### Workarounds

**Speed up testing:**
```json
{
  "scripts": {
    "test": "vitest run --reporter=basic"  // Minimal output
  }
}
```

**Reduce mutants:**
- Focus on critical files
- Use smaller test suites during development
- Run full mutation testing in CI

### Future Enhancements

- [ ] Multi-file project support
- [ ] Test framework keep-alive (3-4x speedup)
- [ ] Smart test selection (2-5x speedup)
- [ ] Parallel execution (8x speedup)
- [ ] HTML reports
- [ ] CI/CD integration

---

## Troubleshooting

### "No package.json found"

**Problem:** Project root not detected

**Solution:**
```bash
# Ensure package.json exists
cd your-project
npm init -y
npm install --save-dev vitest

# Or specify project root explicitly in code
```

### "Baseline tests failed"

**Problem:** Tests fail on original code

**Solution:**
```bash
# Fix tests first
npm test

# Then run mutation testing
cargo run --example typescript_mutation_workflow
```

### "Test execution timeout"

**Problem:** Tests take too long

**Solution:**
```typescript
// Add timeout in test
test('slow operation', async () => {
    // ...
}, 30000);  // 30 second timeout
```

### "No mutants generated"

**Problem:** Code doesn't match mutation patterns

**Solution:**
- Ensure code has arithmetic operators (+, -, *, /)
- Check for === comparisons
- Verify TypeScript syntax is valid

---

## Best Practices

### 1. Start with Small Files

```bash
# Good: Single file, focused tests
calculator.ts + calculator.test.ts (67 mutants, 2 minutes)

# Avoid: Large files initially
entire-app.ts (1000+ mutants, 30+ minutes)
```

### 2. Interpret Surviving Mutants

**Don't just aim for 100%** - some mutants are equivalent:

```typescript
// These might be equivalent:
return a > b ? a : b;
return a >= b ? a : b;  // Same behavior when a > b
```

Focus on **meaningful survivors** that reveal test gaps.

### 3. Add Tests Iteratively

```typescript
// 1. Run mutation testing
// 2. Identify surviving mutants
// 3. Add tests to kill them
// 4. Re-run to verify

// Example: Add type coercion test
test('strict equality with type coercion', () => {
    expect(isEqual(0, "0")).toBe(false);  // Kills === โ†’ == mutant
});
```

### 4. Use in CI/CD

```yaml
# .github/workflows/mutation-testing.yml
name: Mutation Testing
on: [pull_request]

jobs:
  mutation:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - run: npm install
      - run: cargo run --example typescript_mutation_workflow
      - run: |
          # Fail if mutation score < 70%
          if [ $MUTATION_SCORE -lt 70 ]; then exit 1; fi
```

---

## Performance Expectations

### Typical Performance

| Mutants | Sequential | Optimized (Future) |
|---------|------------|-------------------|
| 10 | ~18s | ~2s |
| 50 | ~90s | ~7s |
| 100 | ~180s | ~12s |
| 500 | ~900s (15min) | ~60s |

**Note:** Times assume ~1.8s per mutant (current) or ~0.12s (optimized)

### Scaling Recommendations

**Small projects (<50 mutants):** Run on every commit
**Medium projects (50-200 mutants):** Run on PRs
**Large projects (200+ mutants):** Run nightly or on main branch

---

## Related Documentation

- [Complete Implementation Summary]../tickets/PMAT-7010-COMPLETE-SUMMARY.md
- [REFACTOR Phase Day 1]../tickets/PMAT-7010-REFACTOR-DAY1-COMPLETE.md
- [Performance Optimization Plan]../tickets/PMAT-7010-REFACTOR-DAY2-PLAN.md
- [Original Specification]../tickets/TICKET-PMAT-7010.md

---

## Support & Contributing

### Getting Help

1. Check [Troubleshooting]#troubleshooting section
2. Review examples in the project repository for working code
3. Open issue on GitHub with reproduction steps

### Contributing

Contributions welcome for:
- Additional mutation operators
- Performance optimizations
- Test framework integrations
- Documentation improvements

See [CONTRIBUTING.md](../../CONTRIBUTING.md) for guidelines.

---

## License

MIT OR Apache-2.0 (same as PMAT)

---

**Last Updated:** 2025-10-08
**Version:** 2.144.0
**Status:** Production Ready
**Maintainer:** PMAT Team