xchecker 1.2.0

Spec pipeline with receipts and gateable JSON contracts
Documentation
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
//! Test schema validation using generated JSON from constructors
//!
//! This test validates that JSON generated from actual constructors (not static files)
//! conforms to the JSON schemas. It also tests array sorting and stable key ordering.

use chrono::Utc;
use std::collections::{BTreeMap, HashMap};
use std::fs;
use tempfile::TempDir;

use xchecker::doctor::{CheckStatus, DoctorCheck, DoctorOutput};
use xchecker::receipt::ReceiptManager;
use xchecker::types::{
    ArtifactInfo, ConfigSource, ConfigValue, DriftPair, FileHash, LockDrift, PacketEvidence,
    PhaseId, StatusOutput,
};

/// Test that generated receipts validate against schema
#[test]
fn test_generated_receipt_validates_against_schema() {
    use camino::Utf8PathBuf;

    let temp_dir = TempDir::new().unwrap();
    let base_path = Utf8PathBuf::from_path_buf(temp_dir.path().to_path_buf()).unwrap();
    let manager = ReceiptManager::new(&base_path);

    // Generate a receipt using the actual constructor
    let outputs = vec![
        FileHash {
            path: "artifacts/00-requirements.md".to_string(),
            blake3_canonicalized:
                "abc123def456789012345678901234567890123456789012345678901234abcd".to_string(),
        },
        FileHash {
            path: "artifacts/10-design.md".to_string(),
            blake3_canonicalized:
                "def456abc789012345678901234567890123456789012345678901234567890a".to_string(),
        },
    ];

    let packet = PacketEvidence {
        files: vec![],
        max_bytes: 65536,
        max_lines: 1200,
    };

    let receipt = manager.create_receipt(
        "test-spec",
        PhaseId::Requirements,
        0,
        outputs,
        "0.1.0",
        "0.8.1",
        "haiku",
        None,
        HashMap::new(),
        packet,
        None,
        None,
        vec![],
        None,
        "native",
        None,
        None,
        None,
        None,
        None, // pipeline
    );

    // Serialize to JSON
    let json_value = serde_json::to_value(&receipt).unwrap();

    // Load schema and validate
    let schema_content =
        fs::read_to_string("schemas/receipt.v1.json").expect("Failed to read receipt schema");
    let schema: serde_json::Value =
        serde_json::from_str(&schema_content).expect("Failed to parse receipt schema");

    let validator = jsonschema::validator_for(&schema).expect("Failed to compile receipt schema");

    if let Err(error) = validator.validate(&json_value) {
        panic!("Generated receipt failed validation:\n{}", error);
    }

    println!("✓ Generated receipt validates against schema");
}

/// Test that generated status outputs validate against schema
#[test]
fn test_generated_status_validates_against_schema() {
    // Generate a status output using the actual constructor
    let artifacts = vec![
        ArtifactInfo {
            path: "artifacts/00-requirements.md".to_string(),
            blake3_first8: "abc12345".to_string(),
        },
        ArtifactInfo {
            path: "artifacts/10-design.md".to_string(),
            blake3_first8: "def67890".to_string(),
        },
    ];

    let mut effective_config = BTreeMap::new();
    effective_config.insert(
        "model".to_string(),
        ConfigValue {
            value: serde_json::json!("claude-sonnet-4"),
            source: ConfigSource::Cli,
        },
    );
    effective_config.insert(
        "max_turns".to_string(),
        ConfigValue {
            value: serde_json::json!(6),
            source: ConfigSource::Config,
        },
    );

    let lock_drift = Some(LockDrift {
        model_full_name: Some(DriftPair {
            locked: "claude-sonnet-4-20250101".to_string(),
            current: "claude-sonnet-4-20250201".to_string(),
        }),
        claude_cli_version: None,
        schema_version: None,
    });

    let status = StatusOutput {
        schema_version: "1".to_string(),
        emitted_at: Utc::now(),
        runner: "native".to_string(),
        runner_distro: None,
        fallback_used: false,
        canonicalization_version: "yaml-v1,md-v1".to_string(),
        canonicalization_backend: "jcs-rfc8785".to_string(),
        artifacts,
        last_receipt_path: "receipts/00-requirements.json".to_string(),
        effective_config,
        lock_drift,
        pending_fixups: None,
    };

    // Serialize to JSON
    let json_value = serde_json::to_value(&status).unwrap();

    // Load schema and validate
    let schema_content =
        fs::read_to_string("schemas/status.v1.json").expect("Failed to read status schema");
    let schema: serde_json::Value =
        serde_json::from_str(&schema_content).expect("Failed to parse status schema");

    let validator = jsonschema::validator_for(&schema).expect("Failed to compile status schema");

    if let Err(error) = validator.validate(&json_value) {
        panic!("Generated status failed validation:\n{}", error);
    }

    println!("✓ Generated status validates against schema");
}

/// Test that generated doctor outputs validate against schema
#[test]
fn test_generated_doctor_validates_against_schema() {
    // Generate a doctor output using the actual constructor
    let checks = vec![
        DoctorCheck {
            name: "claude_path".to_string(),
            status: CheckStatus::Pass,
            details: "Found claude at /usr/local/bin/claude".to_string(),
        },
        DoctorCheck {
            name: "claude_version".to_string(),
            status: CheckStatus::Pass,
            details: "0.8.1".to_string(),
        },
        DoctorCheck {
            name: "wsl_availability".to_string(),
            status: CheckStatus::Warn,
            details: "WSL not installed (Windows only)".to_string(),
        },
    ];

    let doctor = DoctorOutput {
        schema_version: "1".to_string(),
        emitted_at: Utc::now(),
        ok: true,
        checks,
        cache_stats: None,
    };

    // Serialize to JSON
    let json_value = serde_json::to_value(&doctor).unwrap();

    // Load schema and validate
    let schema_content =
        fs::read_to_string("schemas/doctor.v1.json").expect("Failed to read doctor schema");
    let schema: serde_json::Value =
        serde_json::from_str(&schema_content).expect("Failed to parse doctor schema");

    let validator = jsonschema::validator_for(&schema).expect("Failed to compile doctor schema");

    if let Err(error) = validator.validate(&json_value) {
        panic!("Generated doctor output failed validation:\n{}", error);
    }

    println!("✓ Generated doctor output validates against schema");
}

/// Test that arrays are sorted in generated outputs
#[test]
fn test_generated_outputs_have_sorted_arrays() {
    use camino::Utf8PathBuf;

    let temp_dir = TempDir::new().unwrap();
    let base_path = Utf8PathBuf::from_path_buf(temp_dir.path().to_path_buf()).unwrap();
    let manager = ReceiptManager::new(&base_path);

    // Create outputs in unsorted order
    let outputs = vec![
        FileHash {
            path: "artifacts/20-tasks.md".to_string(),
            blake3_canonicalized:
                "1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef".to_string(),
        },
        FileHash {
            path: "artifacts/00-requirements.md".to_string(),
            blake3_canonicalized:
                "abc123def456789012345678901234567890123456789012345678901234abcd".to_string(),
        },
        FileHash {
            path: "artifacts/10-design.md".to_string(),
            blake3_canonicalized:
                "def456abc789012345678901234567890123456789012345678901234567890a".to_string(),
        },
    ];

    let packet = PacketEvidence {
        files: vec![],
        max_bytes: 65536,
        max_lines: 1200,
    };

    let receipt = manager.create_receipt(
        "test-spec",
        PhaseId::Requirements,
        0,
        outputs,
        "0.1.0",
        "0.8.1",
        "haiku",
        None,
        HashMap::new(),
        packet,
        None,
        None,
        vec![],
        None,
        "native",
        None,
        None,
        None,
        None,
        None, // pipeline
    );

    // Serialize to JSON
    let json_value = serde_json::to_value(&receipt).unwrap();

    // Verify outputs are sorted by path
    let outputs_array = json_value["outputs"].as_array().unwrap();
    assert_eq!(
        outputs_array[0]["path"], "artifacts/00-requirements.md",
        "First output should be 00-requirements.md"
    );
    assert_eq!(
        outputs_array[1]["path"], "artifacts/10-design.md",
        "Second output should be 10-design.md"
    );
    assert_eq!(
        outputs_array[2]["path"], "artifacts/20-tasks.md",
        "Third output should be 20-tasks.md"
    );

    println!("✓ Receipt outputs are sorted by path");

    // Test status artifacts sorting
    let mut artifacts = vec![
        ArtifactInfo {
            path: "artifacts/20-tasks.md".to_string(),
            blake3_first8: "12345678".to_string(),
        },
        ArtifactInfo {
            path: "artifacts/00-requirements.md".to_string(),
            blake3_first8: "abc12345".to_string(),
        },
        ArtifactInfo {
            path: "artifacts/10-design.md".to_string(),
            blake3_first8: "def67890".to_string(),
        },
    ];

    // Sort artifacts by path before emission (as required by design)
    artifacts.sort_by(|a, b| a.path.cmp(&b.path));

    let status = StatusOutput {
        schema_version: "1".to_string(),
        emitted_at: Utc::now(),
        runner: "native".to_string(),
        runner_distro: None,
        fallback_used: false,
        canonicalization_version: "yaml-v1,md-v1".to_string(),
        canonicalization_backend: "jcs-rfc8785".to_string(),
        artifacts,
        last_receipt_path: "receipts/00-requirements.json".to_string(),
        effective_config: BTreeMap::new(),
        lock_drift: None,
        pending_fixups: None,
    };

    let json_value = serde_json::to_value(&status).unwrap();
    let artifacts_array = json_value["artifacts"].as_array().unwrap();
    assert_eq!(
        artifacts_array[0]["path"], "artifacts/00-requirements.md",
        "First artifact should be 00-requirements.md"
    );
    assert_eq!(
        artifacts_array[1]["path"], "artifacts/10-design.md",
        "Second artifact should be 10-design.md"
    );
    assert_eq!(
        artifacts_array[2]["path"], "artifacts/20-tasks.md",
        "Third artifact should be 20-tasks.md"
    );

    println!("✓ Status artifacts are sorted by path");

    // Test doctor checks sorting
    let mut checks = vec![
        DoctorCheck {
            name: "wsl_availability".to_string(),
            status: CheckStatus::Warn,
            details: "WSL not installed".to_string(),
        },
        DoctorCheck {
            name: "claude_path".to_string(),
            status: CheckStatus::Pass,
            details: "Found claude".to_string(),
        },
        DoctorCheck {
            name: "claude_version".to_string(),
            status: CheckStatus::Pass,
            details: "0.8.1".to_string(),
        },
    ];

    // Sort checks by name before emission (as required by design)
    checks.sort_by(|a, b| a.name.cmp(&b.name));

    let doctor = DoctorOutput {
        schema_version: "1".to_string(),
        emitted_at: Utc::now(),
        ok: true,
        checks,
        cache_stats: None,
    };

    let json_value = serde_json::to_value(&doctor).unwrap();
    let checks_array = json_value["checks"].as_array().unwrap();
    assert_eq!(
        checks_array[0]["name"], "claude_path",
        "First check should be claude_path"
    );
    assert_eq!(
        checks_array[1]["name"], "claude_version",
        "Second check should be claude_version"
    );
    assert_eq!(
        checks_array[2]["name"], "wsl_availability",
        "Third check should be wsl_availability"
    );

    println!("✓ Doctor checks are sorted by name");
}

/// Test that different insertion orders produce byte-identical JSON
#[test]
fn test_different_insertion_orders_produce_identical_json() {
    // Test with BTreeMap for effective_config (should maintain sorted order)
    let mut config1 = BTreeMap::new();
    config1.insert(
        "model".to_string(),
        ConfigValue {
            value: serde_json::json!("claude-sonnet-4"),
            source: ConfigSource::Cli,
        },
    );
    config1.insert(
        "max_turns".to_string(),
        ConfigValue {
            value: serde_json::json!(6),
            source: ConfigSource::Config,
        },
    );
    config1.insert(
        "packet_max_bytes".to_string(),
        ConfigValue {
            value: serde_json::json!(65536),
            source: ConfigSource::Default,
        },
    );

    let mut config2 = BTreeMap::new();
    // Insert in different order
    config2.insert(
        "packet_max_bytes".to_string(),
        ConfigValue {
            value: serde_json::json!(65536),
            source: ConfigSource::Default,
        },
    );
    config2.insert(
        "max_turns".to_string(),
        ConfigValue {
            value: serde_json::json!(6),
            source: ConfigSource::Config,
        },
    );
    config2.insert(
        "model".to_string(),
        ConfigValue {
            value: serde_json::json!("claude-sonnet-4"),
            source: ConfigSource::Cli,
        },
    );

    let status1 = StatusOutput {
        schema_version: "1".to_string(),
        emitted_at: Utc::now(),
        runner: "native".to_string(),
        runner_distro: None,
        fallback_used: false,
        canonicalization_version: "yaml-v1,md-v1".to_string(),
        canonicalization_backend: "jcs-rfc8785".to_string(),
        artifacts: vec![],
        last_receipt_path: "receipts/00-requirements.json".to_string(),
        effective_config: config1,
        lock_drift: None,
        pending_fixups: None,
    };

    let status2 = StatusOutput {
        schema_version: "1".to_string(),
        emitted_at: status1.emitted_at, // Use same timestamp
        runner: "native".to_string(),
        runner_distro: None,
        fallback_used: false,
        canonicalization_version: "yaml-v1,md-v1".to_string(),
        canonicalization_backend: "jcs-rfc8785".to_string(),
        artifacts: vec![],
        last_receipt_path: "receipts/00-requirements.json".to_string(),
        effective_config: config2,
        lock_drift: None,
        pending_fixups: None,
    };

    // Serialize both to JSON strings
    let json1 = serde_json::to_string(&status1).unwrap();
    let json2 = serde_json::to_string(&status2).unwrap();

    // They should be byte-identical
    assert_eq!(
        json1, json2,
        "Different insertion orders should produce identical JSON"
    );

    println!("✓ Different insertion orders produce byte-identical JSON");
}

/// Combined test that runs all schema validation checks
#[test]
fn test_generated_outputs_validate_against_schemas() {
    test_generated_receipt_validates_against_schema();
    test_generated_status_validates_against_schema();
    test_generated_doctor_validates_against_schema();
    test_generated_outputs_have_sorted_arrays();
    test_different_insertion_orders_produce_identical_json();

    println!("\n✅ All schema validation tests passed!");
}