crtx 0.1.1

CLI for the Cortex supervisory memory substrate.
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
//! End-to-end CLI tests for `cortex release readiness` after ADR 0041 wiring.
//!
//! Covers the five operator scenarios the design document calls out for
//! Slice 4: all-four-witnesses success, three-of-four partial,
//! two-witnesses-same-domain overlap, stale witness rejection, and
//! evidence-digest mismatch rejection. Witnesses are built in-memory from
//! deterministic Ed25519 seeds — no live signatures, no filesystem keys.
//!
//! Also hosts the load-bearing Cosign-class subject-binding test
//! [`release_readiness_rejects_witnesses_whose_subject_blake3_does_not_match_evidence_input`],
//! named in ADR 0041 §"Acceptance criteria" as a binding CI gate. That test
//! consumes committed fixture files under
//! `tests/fixtures/verifier-binding/` so the wire shape exercised in CI is
//! exactly the wire shape an operator would supply on the command line.

use std::path::{Path, PathBuf};
use std::process::Command;

use chrono::{DateTime, Duration, Utc};
use cortex_verifier::{
    AuthorityDomain, IndependentWitness, WitnessClass, WitnessPayload, WitnessSignature,
    WitnessTier,
};
use ed25519_dalek::{Signer, SigningKey};
use serde_json::{json, Value};

fn cortex_bin() -> PathBuf {
    PathBuf::from(env!("CARGO_BIN_EXE_cortex"))
}

fn run(args: &[&str]) -> std::process::Output {
    Command::new(cortex_bin())
        .env_remove("RUST_LOG")
        .args(args)
        .output()
        .expect("spawn cortex")
}

fn authority_grade_input() -> String {
    json!({
        "evidence_kind": "remote_ci",
        "runtime_mode": "authority_grade",
        "authority_class": "operator",
        "proof_state": "full_chain_verified",
        "claim_ceiling": "authority_grade",
        "policy_outcome": "allow",
        "source_refs": ["signed://fixture/release-readiness"]
    })
    .to_string()
}

fn blake3_hex(input: &str) -> String {
    blake3::hash(input.as_bytes()).to_hex().to_string()
}

fn signing_key(seed: u8) -> SigningKey {
    let mut bytes = [0u8; 32];
    bytes[0] = seed;
    bytes[31] = seed.wrapping_add(0x5A);
    SigningKey::from_bytes(&bytes)
}

fn sample_payload(class: WitnessClass) -> WitnessPayload {
    let stamp =
        DateTime::<Utc>::from_timestamp(1_715_500_000, 0).expect("constant fits in chrono range");
    match class {
        WitnessClass::SignedLedgerChainHead => WitnessPayload::SignedLedgerChainHead {
            chain_head_hash: blake3::hash(b"chain-head").to_hex().to_string(),
            event_count: 42,
        },
        WitnessClass::ExternalAnchorCrossing => WitnessPayload::ExternalAnchorCrossing {
            chain_head_hash: blake3::hash(b"chain-head").to_hex().to_string(),
            event_count: 42,
            sink_kind: "branch_protection".to_string(),
        },
        WitnessClass::RemoteCiConclusion => WitnessPayload::RemoteCiConclusion {
            workflow_run_id: "ci-run-1".to_string(),
            commit_sha: "0".repeat(40),
            conclusion_timestamp: stamp,
        },
        WitnessClass::ReproducibleBuildProvenance => WitnessPayload::ReproducibleBuildProvenance {
            builder_id: "https://slsa-builder.example/v1".to_string(),
            source_digest: blake3::hash(b"source").to_hex().to_string(),
            artifact_digest: blake3::hash(b"artifact").to_hex().to_string(),
        },
    }
}

fn build_witness(
    seed: u8,
    class: WitnessClass,
    tier: WitnessTier,
    subject_digest: &str,
    asserted_at: DateTime<Utc>,
) -> IndependentWitness {
    let key = signing_key(seed);
    let domain = class.required_authority_domain();
    let payload = sample_payload(class);
    let preimage = payload.canonical_preimage(domain, subject_digest, asserted_at);
    let signature = key.sign(&preimage);
    IndependentWitness {
        class,
        authority_domain: domain,
        tier,
        asserted_at,
        asserted_subject_blake3: subject_digest.to_string(),
        signature: WitnessSignature::Ed25519 {
            public_key_bytes: key.verifying_key().to_bytes(),
            signature_bytes: signature.to_bytes(),
            signer_id: Some(format!("test-{}", class.wire_str())),
        },
        payload,
    }
}

fn override_domain(witness: &mut IndependentWitness, seed: u8, domain: AuthorityDomain) {
    witness.authority_domain = domain;
    let key = signing_key(seed);
    let preimage = witness.payload.canonical_preimage(
        witness.authority_domain,
        &witness.asserted_subject_blake3,
        witness.asserted_at,
    );
    let signature = key.sign(&preimage);
    match &mut witness.signature {
        WitnessSignature::Ed25519 {
            public_key_bytes,
            signature_bytes,
            ..
        } => {
            *public_key_bytes = key.verifying_key().to_bytes();
            *signature_bytes = signature.to_bytes();
        }
        other => panic!("override_domain: expected Ed25519, got {other:?}"),
    }
}

fn full_witness_set(subject_digest: &str, asserted_at: DateTime<Utc>) -> Vec<IndependentWitness> {
    vec![
        build_witness(
            1,
            WitnessClass::SignedLedgerChainHead,
            WitnessTier::OperatorOwned,
            subject_digest,
            asserted_at,
        ),
        build_witness(
            2,
            WitnessClass::ExternalAnchorCrossing,
            WitnessTier::OperatorOwned,
            subject_digest,
            asserted_at,
        ),
        build_witness(
            3,
            WitnessClass::RemoteCiConclusion,
            WitnessTier::ThirdParty,
            subject_digest,
            asserted_at,
        ),
        build_witness(
            4,
            WitnessClass::ReproducibleBuildProvenance,
            WitnessTier::ThirdParty,
            subject_digest,
            asserted_at,
        ),
    ]
}

fn witnesses_to_json(witnesses: &[IndependentWitness]) -> Vec<String> {
    witnesses
        .iter()
        .map(|w| serde_json::to_string(w).expect("witness serializes"))
        .collect()
}

fn assert_exit(out: &std::process::Output, expected: i32) {
    let code = out.status.code().expect("process exited via signal");
    assert_eq!(
        code,
        expected,
        "expected exit {expected}, got {code}\nstdout: {}\nstderr: {}",
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr),
    );
}

#[test]
fn all_four_witnesses_promote_to_full_chain_verified_and_exit_ok() {
    let input = authority_grade_input();
    let digest = blake3_hex(&input);
    let witnesses = full_witness_set(&digest, Utc::now());
    let json_witnesses = witnesses_to_json(&witnesses);

    let mut cli = vec![
        "release",
        "readiness",
        "--evidence-json",
        &input,
        "--evidence-blake3",
        &digest,
    ];
    for w in &json_witnesses {
        cli.push("--witness-json");
        cli.push(w.as_str());
    }
    let out = run(&cli);
    assert_exit(&out, 0);

    let report: Value =
        serde_json::from_slice(&out.stderr).expect("stderr is JSON preflight report");
    assert_eq!(report["command"], "release.readiness");
    assert_eq!(report["trusted_artifact_emitted"], true);
    assert_eq!(report["trusted_stdout_artifact"], true);
    assert_eq!(report["independent_verification"], true);
    assert_eq!(report["claim_allowed"], true);
    assert_eq!(report["verifier"]["invoked"], true);
    assert_eq!(report["verifier"]["state"], "full_chain_verified");
    assert_eq!(report["verifier"]["ceiling"], "authority_grade");
    assert_eq!(
        report["verifier"]["witnesses"]
            .as_array()
            .map(Vec::len)
            .unwrap_or(0),
        4
    );
}

#[test]
fn three_of_four_witnesses_yield_partial_and_advisory_exit() {
    let input = authority_grade_input();
    let digest = blake3_hex(&input);
    let mut witnesses = full_witness_set(&digest, Utc::now());
    // Drop the SLSA build provenance witness.
    witnesses.pop();
    let json_witnesses = witnesses_to_json(&witnesses);

    let mut cli = vec![
        "release",
        "readiness",
        "--evidence-json",
        &input,
        "--evidence-blake3",
        &digest,
    ];
    for w in &json_witnesses {
        cli.push("--witness-json");
        cli.push(w.as_str());
    }
    let out = run(&cli);
    assert_exit(&out, 7);

    let report: Value = serde_json::from_slice(&out.stderr).expect("stderr is JSON");
    assert_eq!(report["trusted_artifact_emitted"], false);
    assert_eq!(report["verifier"]["state"], "partial");
    let reasons = report["verifier"]["reasons"]
        .as_array()
        .expect("verifier.reasons is array");
    assert!(reasons.iter().any(|r| r

        .as_str()
        .unwrap_or("")
        .contains("reproducible_build_provenance")));
    assert_eq!(
        report["evidence_input"]["failed_rule"],
        "release.evidence_input.independent_verification_partial"
    );
}

#[test]
fn two_witnesses_sharing_authority_domain_break_with_overlap_invariant() {
    let input = authority_grade_input();
    let digest = blake3_hex(&input);
    let now = Utc::now();
    let mut witnesses = full_witness_set(&digest, now);
    // Force the external anchor witness onto the local_signed_ledger domain
    // so two witnesses share `local_signed_ledger`. Re-signs with the same
    // seed so the verifier reaches the disjointness check rather than the
    // signature check.
    override_domain(&mut witnesses[1], 2, AuthorityDomain::LocalSignedLedger);
    let json_witnesses = witnesses_to_json(&witnesses);

    let mut cli = vec![
        "release",
        "readiness",
        "--evidence-json",
        &input,
        "--evidence-blake3",
        &digest,
    ];
    for w in &json_witnesses {
        cli.push("--witness-json");
        cli.push(w.as_str());
    }
    let out = run(&cli);
    assert_exit(&out, 7);

    let report: Value = serde_json::from_slice(&out.stderr).expect("stderr is JSON");
    assert_eq!(report["trusted_artifact_emitted"], false);
    assert_eq!(report["verifier"]["state"], "broken");
    assert_eq!(
        report["verifier"]["broken_edge"]["invariant"],
        "verifier.witness.authority_overlap"
    );
    assert_eq!(
        report["evidence_input"]["failed_rule"],
        "release.evidence_input.independent_verification_broken"
    );
}

#[test]
fn stale_witness_is_rejected_with_witness_stale_invariant() {
    let input = authority_grade_input();
    let digest = blake3_hex(&input);
    // Signed 7 days ago; default max-age is 1 day.
    let asserted_at = Utc::now() - Duration::days(7);
    let witnesses = full_witness_set(&digest, asserted_at);
    let json_witnesses = witnesses_to_json(&witnesses);

    let mut cli = vec![
        "release",
        "readiness",
        "--evidence-json",
        &input,
        "--evidence-blake3",
        &digest,
    ];
    for w in &json_witnesses {
        cli.push("--witness-json");
        cli.push(w.as_str());
    }
    let out = run(&cli);
    assert_exit(&out, 7);

    let report: Value = serde_json::from_slice(&out.stderr).expect("stderr is JSON");
    assert_eq!(report["trusted_artifact_emitted"], false);
    assert_eq!(report["verifier"]["state"], "broken");
    assert_eq!(
        report["verifier"]["broken_edge"]["invariant"],
        "verifier.witness.stale"
    );
}

#[test]
fn evidence_digest_mismatch_witness_is_rejected_with_disagreement_invariant() {
    let input = authority_grade_input();
    let digest = blake3_hex(&input);
    let now = Utc::now();
    // Build witnesses against a different subject digest.
    let other_digest = "1".repeat(64);
    let witnesses = full_witness_set(&other_digest, now);
    let json_witnesses = witnesses_to_json(&witnesses);

    let mut cli = vec![
        "release",
        "readiness",
        "--evidence-json",
        &input,
        "--evidence-blake3",
        &digest,
    ];
    for w in &json_witnesses {
        cli.push("--witness-json");
        cli.push(w.as_str());
    }
    let out = run(&cli);
    assert_exit(&out, 7);

    let report: Value = serde_json::from_slice(&out.stderr).expect("stderr is JSON");
    assert_eq!(report["trusted_artifact_emitted"], false);
    assert_eq!(report["verifier"]["state"], "broken");
    assert_eq!(
        report["verifier"]["broken_edge"]["invariant"],
        "verifier.witness.disagreement"
    );
}

// ----------------------------------------------------------------------------
// Load-bearing Cosign-class subject-binding gate (ADR 0041 acceptance criteria)
//
// GHSA-whqx-f9j3-ch6m (2024) showed that a "verified" Rekor entry could be
// accepted for the WRONG artifact when the verifier failed to bind the subject
// digest. ADR 0041 §3 names this risk and the pure verifier rejects it via
// `Broken(witness.disagreement)`. This integration test PROVES the subject
// binding holds end-to-end across the `cortex release readiness` CLI surface
// when an operator supplies witnesses on disk via `--witness-file`.
//
// Fixtures are committed under `tests/fixtures/verifier-binding/` so the bytes
// the test asserts about are the bytes CI is gated against. The fixtures can
// be regenerated by running:
//
//     cargo test -p cortex --test cli_release_readiness -- \
//         --ignored regenerate_verifier_binding_fixtures
//
// The regenerator itself is a fail-closed helper that overwrites the fixture
// JSON files. It is `#[ignore]`d so plain `cargo test` does not mutate the
// committed fixtures.
// ----------------------------------------------------------------------------

const VERIFIER_BINDING_FIXTURE_DIR: &str = "tests/fixtures/verifier-binding";
const EVIDENCE_FIXTURE_NAME: &str = "evidence-d1.json";
const WITNESS_FIXTURE_NAMES: [&str; 4] = [
    "witness-signed-ledger-d2.json",
    "witness-external-anchor-d2.json",
    "witness-remote-ci-d2.json",
    "witness-reproducible-build-d2.json",
];
/// `D2` — the false subject every committed witness fixture claims to attest.
/// Distinct from the BLAKE3 of the committed `evidence-d1.json` (which is
/// `D1`). The verifier MUST reject because `D1 != D2`.
const FALSE_SUBJECT_BLAKE3: &str =
    "1111111111111111111111111111111111111111111111111111111111111111";

fn verifier_binding_fixture_dir() -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(VERIFIER_BINDING_FIXTURE_DIR)
}

fn read_fixture_bytes(name: &str) -> Vec<u8> {
    let path = verifier_binding_fixture_dir().join(name);
    std::fs::read(&path).unwrap_or_else(|err| {
        panic!(
            "fixture {} is missing or unreadable: {err}. \
             Regenerate with: cargo test -p cortex --test cli_release_readiness -- \
             --ignored regenerate_verifier_binding_fixtures",
            path.display()
        )
    })
}

/// Load-bearing CI gate proving that `cortex release readiness` rejects
/// witnesses whose `asserted_subject_blake3` disagrees with the producer's
/// evidence digest. Named verbatim in ADR 0041 §"Acceptance criteria" as a
/// binding gate. Renaming this test is a contract break.
#[test]
fn release_readiness_rejects_witnesses_whose_subject_blake3_does_not_match_evidence_input() {
    let fixture_dir = verifier_binding_fixture_dir();
    let evidence_path = fixture_dir.join(EVIDENCE_FIXTURE_NAME);
    let evidence_bytes = read_fixture_bytes(EVIDENCE_FIXTURE_NAME);
    // `D1` is the producer-supplied digest computed over the canonical
    // evidence-input bytes — the same digest the CLI's authority-shape gate
    // re-computes from the file contents.
    let d1 = blake3::hash(&evidence_bytes).to_hex().to_string();

    // Every committed witness fixture asserts a subject of `D2`. Sanity-check
    // here so a fixture regression surfaces with a clear message instead of as
    // an unrelated `verifier.witness.signature_invalid` failure downstream.
    assert_ne!(
        d1, FALSE_SUBJECT_BLAKE3,
        "fixture invariant violated: D1 must differ from D2 for the subject-binding test to be meaningful"
    );
    for witness_name in WITNESS_FIXTURE_NAMES {
        let witness_bytes = read_fixture_bytes(witness_name);
        let parsed: Value = serde_json::from_slice(&witness_bytes)
            .unwrap_or_else(|err| panic!("witness fixture {witness_name} is not JSON: {err}"));
        assert_eq!(
            parsed["asserted_subject_blake3"].as_str(),
            Some(FALSE_SUBJECT_BLAKE3),
            "witness fixture {witness_name} must declare the false subject D2 \
             (regenerate via --ignored regenerate_verifier_binding_fixtures)"
        );
    }

    let witness_paths: Vec<PathBuf> = WITNESS_FIXTURE_NAMES
        .iter()
        .map(|name| fixture_dir.join(name))
        .collect();

    let mut cli: Vec<String> = vec![
        "release".into(),
        "readiness".into(),
        "--evidence-file".into(),
        evidence_path.to_string_lossy().into_owned(),
        "--evidence-blake3".into(),
        d1.clone(),
    ];
    for witness_path in &witness_paths {
        cli.push("--witness-file".into());
        cli.push(witness_path.to_string_lossy().into_owned());
    }
    let cli_refs: Vec<&str> = cli.iter().map(String::as_str).collect();
    let out = run(&cli_refs);

    // (1) Exit code MUST be `Exit::PreconditionUnmet` (= 7). A trusted
    //     artifact MUST NOT have been emitted.
    assert_exit(&out, 7);

    let stderr = String::from_utf8(out.stderr.clone()).expect("stderr is UTF-8");

    // (2) The stable invariant `verifier.witness.disagreement` MUST appear
    //     verbatim in stderr. Operators and downstream policy rules key off
    //     this string; renaming it is a contract break.
    assert!(
        stderr.contains("verifier.witness.disagreement"),
        "stderr MUST contain stable invariant `verifier.witness.disagreement` verbatim; got: {stderr}"
    );

    // (3) The preflight report MUST flip every trust-claim flag to false.
    let report: Value = serde_json::from_str(&stderr).unwrap_or_else(|err| {
        panic!("stderr is not a JSON preflight report: {err}\nstderr: {stderr}")
    });
    assert_eq!(report["command"], "release.readiness");
    assert_eq!(
        report["trusted_artifact_emitted"], false,
        "subject-binding mismatch MUST NOT emit a trusted artifact"
    );
    assert_eq!(
        report["independent_verification"], false,
        "subject-binding mismatch MUST report independent_verification=false"
    );
    assert_eq!(report["trusted_stdout_artifact"], false);
    assert_eq!(report["artifact_emitted"], false);

    // (4) The verifier report MUST identify the failing edge precisely. This
    //     is what makes the test load-bearing: a regression that silently
    //     dropped subject-binding would leave the witnesses passing every
    //     other gate, and `broken_edge.invariant` would no longer be
    //     `verifier.witness.disagreement`.
    assert_eq!(report["verifier"]["invoked"], true);
    assert_eq!(report["verifier"]["state"], "broken");
    assert_eq!(
        report["verifier"]["broken_edge"]["invariant"],
        "verifier.witness.disagreement"
    );
    let detail = report["verifier"]["broken_edge"]["detail"]
        .as_str()
        .expect("broken_edge.detail is a string");
    assert!(
        detail.contains(FALSE_SUBJECT_BLAKE3),
        "broken_edge.detail MUST quote the false subject D2; got: {detail}"
    );
    assert!(
        detail.contains(&d1),
        "broken_edge.detail MUST quote the producer-supplied subject D1; got: {detail}"
    );

    // (5) The evidence input report MUST flag the failure at the verifier
    //     stage, not the earlier authority-shape stages — that proves the
    //     witnesses actually reached the verifier (because the digest and
    //     source refs all passed) and were rejected there.
    assert_eq!(
        report["evidence_input"]["failed_rule"],
        "release.evidence_input.independent_verification_broken"
    );
    assert_eq!(report["evidence_input"]["accepted"], false);
    assert_eq!(report["evidence_input"]["trusted_artifact_emitted"], false);
}

// ----------------------------------------------------------------------------
// Fixture regenerator. `#[ignore]`d so a plain `cargo test` does not touch
// the committed fixtures. Run explicitly with:
//
//   cargo test -p cortex --test cli_release_readiness -- --ignored \
//       regenerate_verifier_binding_fixtures
//
// The regenerator is deterministic: every signing key derives from a fixed
// seed, every timestamp is a fixed constant, and the canonical preimage is
// produced by `WitnessPayload::canonical_preimage`. Re-running on the same
// commit produces byte-identical fixtures.
// ----------------------------------------------------------------------------

fn write_fixture_atomic(path: &Path, bytes: &[u8]) {
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)
            .unwrap_or_else(|err| panic!("create_dir_all({}) failed: {err}", parent.display()));
    }
    std::fs::write(path, bytes)
        .unwrap_or_else(|err| panic!("write fixture {} failed: {err}", path.display()));
}

#[test]
#[ignore = "regenerator: writes committed fixtures; run explicitly via --ignored"]
fn regenerate_verifier_binding_fixtures() {
    let dir = verifier_binding_fixture_dir();

    // Evidence input: an authority-grade release-readiness preflight JSON
    // shaped exactly like the producer-supplied input the CLI parses today.
    // Its BLAKE3 is `D1` (computed at test time from the committed bytes).
    let evidence_input = json!({
        "evidence_kind": "remote_ci",
        "runtime_mode": "authority_grade",
        "authority_class": "operator",
        "proof_state": "full_chain_verified",
        "claim_ceiling": "authority_grade",
        "policy_outcome": "allow",
        "source_refs": ["signed://fixture/verifier-binding/d1-evidence"]
    });
    // `to_string` (not pretty) for a stable, single-line evidence input.
    let evidence_bytes =
        serde_json::to_vec(&evidence_input).expect("evidence input serializes to JSON");
    write_fixture_atomic(&dir.join(EVIDENCE_FIXTURE_NAME), &evidence_bytes);

    // Fixed timestamp keeps witness JSON byte-identical across runs.
    let asserted_at =
        DateTime::<Utc>::from_timestamp(1_715_500_000, 0).expect("constant fits in chrono range");
    // Distinct seeds per witness so signing keys are disjoint.
    let witnesses: [(u8, WitnessClass, WitnessTier, &str); 4] = [
        (
            21,
            WitnessClass::SignedLedgerChainHead,
            WitnessTier::OperatorOwned,
            WITNESS_FIXTURE_NAMES[0],
        ),
        (
            22,
            WitnessClass::ExternalAnchorCrossing,
            WitnessTier::OperatorOwned,
            WITNESS_FIXTURE_NAMES[1],
        ),
        (
            23,
            WitnessClass::RemoteCiConclusion,
            WitnessTier::ThirdParty,
            WITNESS_FIXTURE_NAMES[2],
        ),
        (
            24,
            WitnessClass::ReproducibleBuildProvenance,
            WitnessTier::ThirdParty,
            WITNESS_FIXTURE_NAMES[3],
        ),
    ];
    for (seed, class, tier, name) in witnesses {
        // Sign over the FALSE subject D2 so the only edge that ever rejects
        // these witnesses is subject-binding.
        let witness = build_witness(seed, class, tier, FALSE_SUBJECT_BLAKE3, asserted_at);
        // Pretty-print so a `git diff` on the fixture is readable.
        let bytes = serde_json::to_vec_pretty(&witness).expect("witness serializes to JSON");
        write_fixture_atomic(&dir.join(name), &bytes);
    }
}