pmat 3.11.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
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
# Go Mutation Testing

**Status:** โœ… Production Ready (v2.153.0+)
**Languages:** Go 1.21+
**Quality:** 80%+ mutation score achievable

---

## Overview

PMAT provides **AST-based mutation testing** for Go 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
- โšก Ultra-fast generation (<3ms for ~60 mutants) - **Fastest yet!**
- ๐Ÿงฌ 6 mutation operators covering common bug patterns
- ๐Ÿ”„ Works with standard `go test`
- ๐Ÿ”ท Go-specific operators: bitwise, assignment, unary

---

## Quick Start

### 1. Create Go Module

```bash
# In your project
go mod init myproject
```

### 2. Run Mutation Testing

```bash
# From server directory
cargo run --example go_mutation_workflow --features go-ast

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

### 3. View Results

```
๐Ÿ”ท Go Mutation Testing Workflow

๐Ÿ“ Reading source file: ../fixtures/go/calculator.go
   Size: 2,847 bytes

๐Ÿ”ง Generating mutants...
   Generated: 62 mutants
   Time: 2.8ms

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

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

๐Ÿ“Š Mutation Testing Results
   Total Mutants:    62
   Killed:           50 (80%)
   Survived:         12 (19%)
   Timeout/Error:    0

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

---

## Mutation Operators

### 1. Arithmetic Operator Replacement (AOR)

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

```go
// Original
func Add(a, b int) int {
    return a + b
}

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

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

### 2. Relational Operator Replacement (ROR)

**Replaces:** `<`, `>`, `<=`, `>=`, `==`, `!=`

```go
// Original
func IsPositive(value int) bool {
    return value > 0
}

// Mutants
return value < 0   // > โ†’ <
return value >= 0  // > โ†’ >=
return value <= 0  // > โ†’ <=
return value == 0  // > โ†’ ==
return value != 0  // > โ†’ !=
```

**Tests should fail** when comparison logic changes.

### 3. Logical Operator Replacement (LOR)

**Replaces:** `&&` โ†” `||`

```go
// Original
func BothPositive(a, b int) bool {
    return a > 0 && b > 0
}

// Mutant
return a > 0 || b > 0  // && โ†’ ||

// Original
func EitherPositive(a, b int) bool {
    return a > 0 || b > 0
}

// Mutant
return a > 0 && b > 0  // || โ†’ &&
```

**Tests should fail** when logical operators are swapped.

### 4. Bitwise Operator Replacement (BOR) ๐Ÿ†•

**Replaces:** `&`, `|`, `^`, `<<`, `>>`

```go
// Original
func BitwiseAnd(a, b int) int {
    return a & b
}

// Mutants
return a | b   // & โ†’ |  (OR)
return a ^ b   // & โ†’ ^  (XOR)
return a << b  // & โ†’ << (left shift)
return a >> b  // & โ†’ >> (right shift)

// Original
func LeftShift(a, shift int) int {
    return a << shift
}

// Mutant
return a >> shift  // << โ†’ >>
```

**Tests should fail** when bitwise operations change.

**Use Cases:**
- Low-level bit manipulation
- Flag operations
- Performance-critical code
- Cryptographic operations

### 5. Unary Operator Replacement (UOR) ๐Ÿ†•

**Replaces:** `-` โ†” `+`, `!` (limited)

```go
// Original
func Negate(value int) int {
    return -value
}

// Mutant
return +value  // - โ†’ +

// Original
func Positive(value int) int {
    return +value
}

// Mutant
return -value  // + โ†’ -

// Note: ! operator not mutated (type safety)
func Not(flag bool) bool {
    return !flag  // No mutations (bool โ‰  int)
}
```

**Tests should fail** when sign changes.

### 6. Assignment Operator Replacement ๐Ÿ†•

**Replaces:** `+=`, `-=`, `*=`, `/=`, `%=`, `&=`, `|=`, `^=`, `<<=`, `>>=`

```go
// Original
func AddAssign(value, delta int) int {
    value += delta
    return value
}

// Mutants
value -= delta  // += โ†’ -=
value *= delta  // += โ†’ *=
value /= delta  // += โ†’ /=

// Original
func BitwiseOrAssign(value, mask int) int {
    value |= mask
    return value
}

// Mutants
value &= mask  // |= โ†’ &=
value ^= mask  // |= โ†’ ^=
```

**Tests should fail** when compound assignment changes.

---

## 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
- โœ… Operator behavior validated
- โœ… Error conditions tested

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

---

## Surviving Mutants (Test Weaknesses)

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

### Example: Boundary Condition Gap

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

```go
// Code
func IsPositive(value int) bool {
    return value > 0
}

// Test (weak!)
func TestIsPositive(t *testing.T) {
    if !IsPositive(5) {
        t.Error("Expected true for 5")
    }
    if IsPositive(-5) {
        t.Error("Expected false for -5")
    }
}
// Passes even with >= because 5 > 0 and -5 < 0

// Better test
func TestIsPositiveBoundary(t *testing.T) {
    if IsPositive(0) {  // Would fail with >=
        t.Error("Expected false for 0")
    }
}
```

### Example: Logical Operator Gap

**Mutant:** `&&` โ†’ `||` (survives)

```go
// Code
func BothPositive(a, b int) bool {
    return a > 0 && b > 0
}

// Test (weak!)
func TestBothPositive(t *testing.T) {
    if !BothPositive(5, 10) {
        t.Error("Expected true for (5, 10)")
    }
}
// Passes even with || because both are positive

// Better test
func TestBothPositiveOneNegative(t *testing.T) {
    tests := []struct {
        a, b     int
        expected bool
    }{
        {5, -1, false},  // Would fail with ||
        {-1, 5, false},  // Would fail with ||
        {5, 10, true},
    }
    for _, tt := range tests {
        if got := BothPositive(tt.a, tt.b); got != tt.expected {
            t.Errorf("BothPositive(%d, %d) = %v; want %v",
                tt.a, tt.b, got, tt.expected)
        }
    }
}
```

### Example: Bitwise Operation Gap

**Mutant:** `&` โ†’ `|` (survives)

```go
// Code
func BitwiseAnd(a, b int) int {
    return a & b
}

// Test (weak!)
func TestBitwiseAnd(t *testing.T) {
    result := BitwiseAnd(15, 15)  // 1111 & 1111 = 1111
    if result != 15 {
        t.Errorf("Expected 15, got %d", result)
    }
}
// Passes even with | because 15 & 15 == 15 | 15

// Better test
func TestBitwiseAndVsOr(t *testing.T) {
    result := BitwiseAnd(6, 3)  // 110 & 011 = 010 (2)
    if result != 2 {
        t.Errorf("Expected 2, got %d", result)  // Would fail with | (gives 7)
    }
}
```

### Example: Assignment Operator Gap

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

```go
// Code
func AddAssign(value, delta int) int {
    value += delta
    return value
}

// Test (weak!)
func TestAddAssign(t *testing.T) {
    result := AddAssign(0, 5)
    if result != 5 {
        t.Errorf("Expected 5, got %d", result)
    }
}
// Passes even with *= because 0 + 5 == 0 * 5 when value starts at 0

// Better test
func TestAddAssignNonZero(t *testing.T) {
    result := AddAssign(10, 5)  // 10 + 5 = 15
    if result != 15 {
        t.Errorf("Expected 15, got %d", result)  // Would fail with *= (gives 50)
    }
}
```

---

## Example Project Structure

```
my-go-project/
โ”œโ”€โ”€ calculator.go          # Source code
โ”œโ”€โ”€ calculator_test.go     # Tests
โ””โ”€โ”€ go.mod                 # Module definition
```

### Minimal go.mod

```
module myproject

go 1.21
```

### Test File Pattern

```go
package calculator

import "testing"

func TestAdd(t *testing.T) {
    tests := []struct {
        name     string
        a, b     int
        expected int
    }{
        {"positive numbers", 2, 3, 5},
        {"negative numbers", -1, -1, -2},
        {"zero", 0, 5, 5},
    }

    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            result := Add(tt.a, tt.b)
            if result != tt.expected {
                t.Errorf("Add(%d, %d) = %d; want %d",
                    tt.a, tt.b, result, tt.expected)
            }
        })
    }
}
```

---

## Advanced Usage

### Programmatic Usage

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

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

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

### Custom Operator Selection

```rust
use pmat::services::mutation::go_tree_sitter_mutations::*;

let generator = GoMutationGenerator {
    operators: vec![
        Box::new(GoBinaryOpMutation),      // Only arithmetic
        Box::new(GoRelationalOpMutation),  // Only comparisons
        Box::new(GoBitwiseOpMutation),     // Only bitwise
    ],
};
```

---

## Limitations & Known Issues

### Current Limitations

1. **Single-file testing** - Multi-file projects not yet supported
2. **`go test` startup overhead** - Each mutant restarts test framework (~5ms per mutant)
3. **No test selection** - Runs all tests for each mutant
4. **Sequential execution** - No parallel testing yet

### Workarounds

**Speed up testing:**
```bash
# Use -short flag for faster tests
go test -short

# Or create a separate test suite for mutation testing
go test -run TestMutation
```

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

### Future Enhancements

- [ ] Multi-file project support
- [ ] `go test` keep-alive (3-4x speedup)
- [ ] Smart test selection (2-5x speedup)
- [ ] Parallel execution (8x speedup)
- [ ] HTML reports
- [ ] CI/CD integration
- [ ] Additional operators (channel operations, goroutines, defer)

---

## Troubleshooting

### "Go not installed"

**Problem:** Go not found in environment

**Solution:**
```bash
# Install Go
# https://go.dev/dl/

# Verify installation
go version
```

### "Baseline tests failed"

**Problem:** Tests fail on original code

**Solution:**
```bash
# Fix tests first
go test -v

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

### "No mutants generated"

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

**Solution:**
- Ensure code has operators (+, -, *, /, &&, ||, etc.)
- Check for comparison operators (<, >, ==, etc.)
- Verify Go syntax is valid
- Check that file is valid Go 1.21+ code

### "Module not found" errors

**Problem:** go.mod missing or incorrect

**Solution:**
```bash
# Initialize module
go mod init myproject

# Download dependencies
go mod tidy
```

---

## Best Practices

### 1. Start with Small Files

```bash
# Good: Single file, focused tests
calculator.go + calculator_test.go (62 mutants, 30 seconds)

# Avoid: Large files initially
entire_app.go (1000+ mutants, 5+ minutes)
```

### 2. Use Table-Driven Tests

```go
// Good: Table-driven tests catch more mutants
func TestAdd(t *testing.T) {
    tests := []struct {
        a, b, expected int
    }{
        {2, 3, 5},
        {0, 0, 0},
        {-1, 1, 0},
    }

    for _, tt := range tests {
        if got := Add(tt.a, tt.b); got != tt.expected {
            t.Errorf("Add(%d, %d) = %d; want %d",
                tt.a, tt.b, got, tt.expected)
        }
    }
}

// Weak: Single test case
func TestAdd(t *testing.T) {
    if Add(2, 3) != 5 {
        t.Error("Addition failed")
    }
}
```

### 3. Test Boundary Conditions

```go
// Always test boundaries
func TestIsPositive(t *testing.T) {
    tests := []struct {
        value    int
        expected bool
    }{
        {1, true},   // Positive
        {0, false},  // Boundary - kills > โ†’ >= mutant
        {-1, false}, // Negative
    }
    // ...
}
```

### 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
      - uses: actions/setup-go@v2
        with:
          go-version: '1.21'
      - run: cargo run --example go_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 | ~0.05s | ~0.01s |
| 50 | ~0.25s | ~0.05s |
| 100 | ~0.5s | ~0.1s |
| 500 | ~2.5s | ~0.5s |

**Note:** Times assume ~5ms per mutant (current) or ~1ms (optimized)

Go mutation testing is **THE FASTEST** because:
- No interpreter startup (compiled language)
- `go test` has minimal overhead
- No npm/node.js delays
- Efficient binary execution
- Sub-3ms mutant generation

### Scaling Recommendations

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

---

## Go-Specific Features

### 1. Short Variable Declaration

```go
// Supported
result := a + b  // := mutation works

// Traditional declaration
var result int = a + b
```

### 2. Bitwise Operators

```go
// Bitwise AND, OR, XOR
flags := enable | disable
mask := flag & 0xFF

// Bit shifts
shifted := value << 8
```

### 3. Compound Assignment

```go
// All compound assignments supported
count += 1
value *= factor
bits &= mask
position <<= 1
```

### 4. Table-Driven Tests

```go
// Go idiom - perfect for mutation testing
tests := []struct {
    name     string
    input    int
    expected int
}{
    {"zero", 0, 0},
    {"positive", 5, 5},
    {"negative", -5, -5},
}
```

---

## Related Documentation

- [TypeScript Mutation Testing]TYPESCRIPT-MUTATION-TESTING.md - JavaScript/TypeScript implementation
- [Python Mutation Testing]PYTHON-MUTATION-TESTING.md - Python implementation
- [Original Specification]../tickets/TICKET-PMAT-7012.md
- [Multi-Language Mutation Testing Architecture]../tickets/PMAT-7007-SUB-AGENT-SCAFFOLDING.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 (channel ops, goroutines, defer)
- Performance optimizations
- Test framework integrations
- Documentation improvements

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

---

## Comparison with Other Tools

### vs go-mutesting

**PMAT Go:**
- โœ… AST-based mutations (preserves formatting)
- โœ… Tree-sitter parsing (fast, reliable)
- โœ… Rust performance
- โœ… 6 operators (including bitwise, assignment, unary)
- โœ… Multi-language support (TypeScript, Python, Go)

**go-mutesting:**
- โœ… Pure Go implementation
- โœ… Mature ecosystem
- โŒ Fewer operators
- โŒ Text-based mutations

### vs go-carpet

**PMAT Go:**
- โœ… Production-ready
- โœ… Fast generation (<3ms)
- โœ… Comprehensive operators

**go-carpet:**
- โœ… Visual coverage reports
- โŒ Limited mutation support
- โŒ Slower execution

---

## Technical Details

### AST Node Types

PMAT Go uses tree-sitter-go to parse and mutate these node types:

- `binary_expression` - Arithmetic, relational, logical, bitwise operators
- `unary_expression` - Unary operators (!, -, +)
- `assignment_statement` - Compound assignment operators

### Source Splicing

Mutations use byte-level source splicing:

```rust
let op_range = operator_node.byte_range();
let mut mutated = source.to_vec();
mutated.splice(op_range, new_op.bytes());
```

This preserves:
- Original formatting
- Comments
- Whitespace
- Indentation

---

## License

MIT OR Apache-2.0 (same as PMAT)

---

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