pmat 3.17.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
// Tests for Design by Contract types - Part 3: v5 Contracts + Checkpoints
// Spec: docs/specifications/dbc.md

// === WorkContract v5.0 ===

#[test]
fn test_work_contract_new_is_v4() {
    let contract = WorkContract::new("TEST-1".to_string(), "abc123".to_string());
    assert_eq!(contract.version, "4.0");
    assert!(!contract.is_dbc());
    assert!(contract.require.is_empty());
    assert!(contract.ensure.is_empty());
    assert!(contract.invariant.is_empty());
}

#[test]
fn test_work_contract_with_dbc_is_v5() {
    let dir = tempfile::tempdir().unwrap();
    // Create a minimal git repo to trigger Universal profile
    std::fs::create_dir_all(dir.path().join(".git")).unwrap();

    let contract =
        WorkContract::with_dbc("TEST-1".to_string(), "abc123".to_string(), dir.path(), &[], 1)
            .unwrap();

    assert_eq!(contract.version, "5.0");
    assert!(contract.is_dbc());
    assert_eq!(
        contract.profile,
        Some(ContractProfile::Universal)
    );
    assert_eq!(contract.require.len(), 2);
    assert_eq!(contract.invariant.len(), 2);
    assert_eq!(contract.ensure.len(), 2);
    assert_eq!(contract.triad_claim_count(), 6);
}

#[test]
fn test_work_contract_with_dbc_rust_profile() {
    let dir = tempfile::tempdir().unwrap();
    std::fs::create_dir_all(dir.path().join(".git")).unwrap();
    std::fs::write(dir.path().join("Cargo.toml"), "[package]\nname = \"test\"").unwrap();

    let result =
        WorkContract::with_dbc("TEST-2".to_string(), "abc123".to_string(), dir.path(), &[], 1);

    match result {
        Ok(contract) => {
            assert_eq!(
                contract.profile,
                Some(ContractProfile::Rust)
            );
            assert_eq!(contract.triad_claim_count(), 14);
        }
        Err(e) => {
            // Rust profile may fail if toolchain not available or tempdir race
            let msg = e.to_string();
            assert!(
                msg.contains("missing tool") || msg.contains("Toolchain") || msg.contains("No such file"),
                "Unexpected error: {}", msg
            );
        }
    }
}

#[test]
fn test_work_contract_with_dbc_pmat_profile() {
    let dir = tempfile::tempdir().unwrap();
    std::fs::create_dir_all(dir.path().join(".git")).unwrap();
    std::fs::write(dir.path().join("Cargo.toml"), "[package]\nname = \"test\"").unwrap();
    std::fs::create_dir_all(dir.path().join(".pmat")).unwrap();
    std::fs::write(dir.path().join(".pmat").join("context.db"), "").unwrap();

    let result =
        WorkContract::with_dbc("TEST-3".to_string(), "abc123".to_string(), dir.path(), &[], 1);

    match result {
        Ok(contract) => {
            assert_eq!(
                contract.profile,
                Some(ContractProfile::Pmat)
            );
            assert_eq!(contract.triad_claim_count(), 25);
        }
        Err(e) => {
            // Pmat profile requires cargo-llvm-cov; skip if not installed
            let msg = e.to_string();
            assert!(
                msg.contains("missing tool") || msg.contains("cargo-llvm-cov"),
                "Unexpected error: {}", msg
            );
        }
    }
}

#[test]
fn test_work_contract_with_dbc_exclusions() {
    let dir = tempfile::tempdir().unwrap();
    std::fs::create_dir_all(dir.path().join(".git")).unwrap();

    let without = vec!["ensure.git_sync".to_string()];
    let contract =
        WorkContract::with_dbc("TEST-4".to_string(), "abc123".to_string(), dir.path(), &without, 1)
            .unwrap();

    assert_eq!(contract.triad_claim_count(), 5); // 6 - 1 excluded
    assert_eq!(contract.excluded_claims.len(), 1);
    assert_eq!(contract.excluded_claims[0].id, "ensure.git_sync");

    // Contract quality should reflect exclusion
    let quality = contract.contract_quality.as_ref().unwrap();
    assert_eq!(quality.active_claims, 5);
    assert_eq!(quality.applicable_claims, 6);
    assert!(quality.score < 1.0);
}

#[test]
fn test_work_contract_with_dbc_config_override() {
    let dir = tempfile::tempdir().unwrap();
    std::fs::create_dir_all(dir.path().join(".git")).unwrap();
    std::fs::write(dir.path().join("Cargo.toml"), "[package]\nname = \"test\"").unwrap();

    // Override to Universal even though Cargo.toml exists
    let config_dir = dir.path().join(".pmat-work");
    std::fs::create_dir_all(&config_dir).unwrap();
    std::fs::write(
        config_dir.join("config.toml"),
        "[dbc]\nprofile = \"universal\"\n",
    )
    .unwrap();

    let contract =
        WorkContract::with_dbc("TEST-5".to_string(), "abc123".to_string(), dir.path(), &[], 1)
            .unwrap();

    assert_eq!(
        contract.profile,
        Some(ContractProfile::Universal)
    );
    assert_eq!(contract.triad_claim_count(), 6); // Universal, not Rust
}

// === v5.0 serialization round-trip ===

#[test]
fn test_work_contract_v5_round_trip() {
    let dir = tempfile::tempdir().unwrap();
    std::fs::create_dir_all(dir.path().join(".git")).unwrap();

    let contract =
        WorkContract::with_dbc("TEST-RT".to_string(), "abc123".to_string(), dir.path(), &[], 1)
            .unwrap();

    // Save
    let saved_path = contract.save(dir.path()).unwrap();
    assert!(saved_path.exists());

    // Load
    let loaded = WorkContract::load(dir.path(), "TEST-RT").unwrap();
    assert_eq!(loaded.version, "5.0");
    assert!(loaded.is_dbc());
    assert_eq!(loaded.require.len(), 2);
    assert_eq!(loaded.ensure.len(), 2);
    assert_eq!(loaded.invariant.len(), 2);
    assert_eq!(loaded.profile, Some(ContractProfile::Universal));
}

// === v4.0 backward compat ===

#[test]
fn test_v4_contract_loads_with_empty_triad() {
    let dir = tempfile::tempdir().unwrap();

    // Create a v4.0 contract (no triad fields)
    let v4 = WorkContract::new("TEST-V4".to_string(), "abc123".to_string());
    v4.save(dir.path()).unwrap();

    // Load it back
    let loaded = WorkContract::load(dir.path(), "TEST-V4").unwrap();
    assert_eq!(loaded.version, "4.0");
    assert!(!loaded.is_dbc());
    assert!(loaded.require.is_empty());
    assert!(loaded.ensure.is_empty());
    assert!(loaded.invariant.is_empty());
    assert!(loaded.profile.is_none());
    assert_eq!(loaded.iteration, 1);
    assert_eq!(loaded.claims.len(), 22);
}

// === Profile detection ===

#[test]
fn test_profile_detect_universal() {
    let dir = tempfile::tempdir().unwrap();
    std::fs::create_dir_all(dir.path().join(".git")).unwrap();
    assert_eq!(ContractProfile::detect(dir.path()), ContractProfile::Universal);
}

#[test]
fn test_profile_detect_rust() {
    let dir = tempfile::tempdir().unwrap();
    std::fs::create_dir_all(dir.path().join(".git")).unwrap();
    std::fs::write(dir.path().join("Cargo.toml"), "[package]\nname = \"x\"").unwrap();
    assert_eq!(ContractProfile::detect(dir.path()), ContractProfile::Rust);
}

#[test]
fn test_profile_detect_pmat() {
    let dir = tempfile::tempdir().unwrap();
    std::fs::create_dir_all(dir.path().join(".git")).unwrap();
    std::fs::write(dir.path().join("Cargo.toml"), "[package]\nname = \"x\"").unwrap();
    std::fs::create_dir_all(dir.path().join(".pmat")).unwrap();
    std::fs::write(dir.path().join(".pmat").join("context.idx"), "").unwrap();
    assert_eq!(ContractProfile::detect(dir.path()), ContractProfile::Pmat);
}

#[test]
fn test_profile_detect_stack() {
    let dir = tempfile::tempdir().unwrap();
    std::fs::create_dir_all(dir.path().join(".git")).unwrap();
    std::fs::write(
        dir.path().join(".dbc-stack.toml"),
        "[stack]\nname = \"test\"\n",
    )
    .unwrap();
    match ContractProfile::detect(dir.path()) {
        ContractProfile::Stack { manifest_path } => {
            assert!(manifest_path.ends_with(".dbc-stack.toml"));
        }
        other => panic!("Expected Stack, got {:?}", other),
    }
}

// === CheckpointRecord tests ===

#[test]
fn test_checkpoint_record_new_all_pass() {
    let results = vec![
        InvariantResult {
            clause_id: "invariant.lint".to_string(),
            passed: true,
            explanation: "Lint clean".to_string(),
        },
        InvariantResult {
            clause_id: "invariant.complexity".to_string(),
            passed: true,
            explanation: "Max complexity: 18 (limit: 20)".to_string(),
        },
    ];

    let record = CheckpointRecord::new(
        "PMAT-500".to_string(),
        "abc123def".to_string(),
        1,
        results,
    );

    assert!(record.all_invariants_hold);
    assert_eq!(record.work_item_id, "PMAT-500");
    assert_eq!(record.git_sha, "abc123def");
    assert_eq!(record.iteration, 1);
    assert_eq!(record.invariant_results.len(), 2);
    assert!(!record.checkpoint_id.is_empty());
}

#[test]
fn test_checkpoint_record_new_with_failure() {
    let results = vec![
        InvariantResult {
            clause_id: "invariant.lint".to_string(),
            passed: true,
            explanation: "Lint clean".to_string(),
        },
        InvariantResult {
            clause_id: "invariant.complexity".to_string(),
            passed: false,
            explanation: "Max complexity: 32 exceeds limit 20".to_string(),
        },
    ];

    let record = CheckpointRecord::new(
        "PMAT-500".to_string(),
        "def456".to_string(),
        1,
        results,
    );

    assert!(!record.all_invariants_hold);
    assert_eq!(record.invariant_results.len(), 2);
}

#[test]
fn test_checkpoint_record_empty_invariants() {
    let record = CheckpointRecord::new(
        "PMAT-500".to_string(),
        "abc123".to_string(),
        1,
        vec![],
    );

    assert!(record.all_invariants_hold); // vacuously true
    assert!(record.invariant_results.is_empty());
}

#[test]
fn test_checkpoint_record_save_and_load() {
    let dir = tempfile::tempdir().unwrap();

    let results = vec![
        InvariantResult {
            clause_id: "invariant.lint".to_string(),
            passed: true,
            explanation: "Lint clean".to_string(),
        },
    ];

    let record = CheckpointRecord::new(
        "TEST-CK".to_string(),
        "abc123".to_string(),
        1,
        results,
    );

    // Save
    let path = record.save(dir.path()).unwrap();
    assert!(path.exists());
    assert!(path.to_string_lossy().contains("checkpoints"));

    // Load all
    let loaded = CheckpointRecord::load_all(dir.path(), "TEST-CK");
    assert_eq!(loaded.len(), 1);
    assert_eq!(loaded[0].work_item_id, "TEST-CK");
    assert_eq!(loaded[0].checkpoint_id, record.checkpoint_id);
    assert!(loaded[0].all_invariants_hold);
}

#[test]
fn test_checkpoint_record_load_multiple() {
    let dir = tempfile::tempdir().unwrap();

    // Save two checkpoints
    let r1 = CheckpointRecord::new(
        "TEST-MULTI".to_string(),
        "sha1".to_string(),
        1,
        vec![InvariantResult {
            clause_id: "invariant.lint".to_string(),
            passed: true,
            explanation: "ok".to_string(),
        }],
    );
    r1.save(dir.path()).unwrap();

    let r2 = CheckpointRecord::new(
        "TEST-MULTI".to_string(),
        "sha2".to_string(),
        1,
        vec![InvariantResult {
            clause_id: "invariant.lint".to_string(),
            passed: false,
            explanation: "lint failed".to_string(),
        }],
    );
    r2.save(dir.path()).unwrap();

    let loaded = CheckpointRecord::load_all(dir.path(), "TEST-MULTI");
    assert_eq!(loaded.len(), 2);
    // Sorted by timestamp, first should pass, second should fail
    assert!(loaded[0].all_invariants_hold);
    assert!(!loaded[1].all_invariants_hold);
}

#[test]
fn test_checkpoint_record_load_nonexistent() {
    let dir = tempfile::tempdir().unwrap();
    let loaded = CheckpointRecord::load_all(dir.path(), "NONEXISTENT");
    assert!(loaded.is_empty());
}

#[test]
fn test_checkpoint_serialization_round_trip() {
    let results = vec![
        InvariantResult {
            clause_id: "invariant.complexity".to_string(),
            passed: true,
            explanation: "Max complexity: 15".to_string(),
        },
    ];

    let record = CheckpointRecord::new(
        "PMAT-RT".to_string(),
        "deadbeef".to_string(),
        2,
        results,
    );

    let json = serde_json::to_string_pretty(&record).unwrap();
    let deserialized: CheckpointRecord = serde_json::from_str(&json).unwrap();

    assert_eq!(deserialized.checkpoint_id, record.checkpoint_id);
    assert_eq!(deserialized.work_item_id, "PMAT-RT");
    assert_eq!(deserialized.iteration, 2);
    assert_eq!(deserialized.invariant_results.len(), 1);
    assert!(deserialized.all_invariants_hold);
}

// === Subcontracting with iteration ===

#[test]
fn test_iteration_field_default() {
    let contract = WorkContract::new("TEST".to_string(), "abc".to_string());
    assert_eq!(contract.iteration, 1);
}

#[test]
fn test_iteration_persists_through_save_load() {
    let dir = tempfile::tempdir().unwrap();
    std::fs::create_dir_all(dir.path().join(".git")).unwrap();

    let mut contract =
        WorkContract::with_dbc("TEST-IT".to_string(), "abc123".to_string(), dir.path(), &[], 1)
            .unwrap();
    // Simulate iteration increment
    contract.iteration = 2;
    contract.save(dir.path()).unwrap();

    let loaded = WorkContract::load(dir.path(), "TEST-IT").unwrap();
    assert_eq!(loaded.iteration, 2);
}