assay-core 3.9.1

High-performance evaluation framework for LLM agents (Core)
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
490
use super::paths::validate_entry_path;
use super::*;
use crate::replay::manifest::{
    ReplayCoverage, ReplayManifest, ReplayOutputs, ReplaySeeds, ScrubPolicy,
};
use flate2::GzBuilder;
use sha2::{Digest, Sha256};
use std::collections::BTreeMap;
use tar::{Builder, Header};

#[test]
fn write_bundle_minimal_roundtrip() {
    let manifest = ReplayManifest::minimal("2.15.0".into());
    let entries = vec![BundleEntry {
        path: "outputs/summary.json".into(),
        data: br#"{"schema_version":1}"#.to_vec(),
    }];
    let mut buf = Vec::new();
    write_bundle_tar_gz(&mut buf, &manifest, &entries).unwrap();
    assert!(!buf.is_empty());
    let digest = bundle_digest(&manifest, &entries).unwrap();
    assert_eq!(digest.len(), 64);
}

#[test]
fn read_bundle_roundtrip() {
    let manifest = ReplayManifest::minimal("2.15.0".into());
    let entries = vec![
        BundleEntry {
            path: "files/trace.jsonl".into(),
            data: b"[]".to_vec(),
        },
        BundleEntry {
            path: "outputs/summary.json".into(),
            data: br#"{"schema_version":1}"#.to_vec(),
        },
    ];
    let mut buf = Vec::new();
    write_bundle_tar_gz(&mut buf, &manifest, &entries).unwrap();
    let read = read_bundle_tar_gz(std::io::Cursor::new(&buf)).unwrap();
    assert_eq!(read.manifest.schema_version, manifest.schema_version);
    assert_eq!(read.manifest.assay_version, manifest.assay_version);
    let paths: std::collections::BTreeSet<_> =
        read.entries.iter().map(|(p, _)| p.as_str()).collect();
    assert!(paths.contains("files/trace.jsonl"));
    assert!(paths.contains("outputs/summary.json"));
    let data: std::collections::BTreeMap<_, _> = read.entries.into_iter().collect();
    assert_eq!(data.get("files/trace.jsonl").unwrap(), &b"[]"[..]);
}

/// Reader fails when manifest.json is absent (same policy: bundle must be valid).
#[test]
fn read_bundle_fails_manifest_missing() {
    let mut buf = Vec::new();
    let gz = GzBuilder::new()
        .mtime(0)
        .write(&mut buf, flate2::Compression::default());
    let mut tar = Builder::new(gz);
    let mut header = Header::new_gnu();
    header.set_path("files/x").unwrap();
    header.set_size(0);
    header.set_mode(0o644);
    header.set_cksum();
    tar.append(&header, &[] as &[u8]).unwrap();
    let gz = tar.into_inner().unwrap();
    gz.finish().unwrap();
    let err = read_bundle_tar_gz(std::io::Cursor::new(&buf)).unwrap_err();
    assert!(err.to_string().contains("manifest.json missing"), "{}", err);
}

/// Duplicate path in tar → Error (avoids zip-slip style confusion; last-wins undefined).
#[test]
fn read_bundle_fails_duplicate_path() {
    let manifest = ReplayManifest::minimal("2.15.0".into());
    let manifest_json = serde_json::to_vec(&manifest).unwrap();
    let mut buf = Vec::new();
    let gz = GzBuilder::new()
        .mtime(0)
        .write(&mut buf, flate2::Compression::default());
    let mut tar = Builder::new(gz);
    tar.mode(tar::HeaderMode::Deterministic);
    let mut h = Header::new_gnu();
    h.set_path(paths::MANIFEST).unwrap();
    h.set_size(manifest_json.len() as u64);
    h.set_mode(0o644);
    h.set_cksum();
    tar.append(&h, &manifest_json[..]).unwrap();
    for _ in 0..2 {
        let mut h2 = Header::new_gnu();
        h2.set_path("files/x").unwrap();
        h2.set_size(1);
        h2.set_mode(0o644);
        h2.set_cksum();
        tar.append(&h2, &b"x"[..]).unwrap();
    }
    let gz = tar.into_inner().unwrap();
    gz.finish().unwrap();
    let err = read_bundle_tar_gz(std::io::Cursor::new(&buf)).unwrap_err();
    assert!(err.to_string().contains("duplicate path"), "{}", err);
}

#[test]
fn build_file_manifest_normalizes_paths() {
    let entries = vec![BundleEntry {
        path: "files/trace.jsonl".into(),
        data: vec![1, 2, 3],
    }];
    let manifest_map = build_file_manifest(&entries).unwrap();
    assert_eq!(manifest_map.len(), 1);
    let entry = manifest_map.get("files/trace.jsonl").unwrap();
    assert_eq!(entry.size, 3);
    assert!(entry.sha256.starts_with("sha256:"));
}

/// Legitimate filename with ".." in segment (not traversal) is allowed.
#[test]
fn path_segment_dotdot_allows_literal_dotdot_in_filename() {
    let manifest = ReplayManifest::minimal("2.15.0".into());
    let entries = vec![BundleEntry {
        path: "files/a..b.txt".into(),
        data: b"ok".to_vec(),
    }];
    let mut buf = Vec::new();
    write_bundle_tar_gz(&mut buf, &manifest, &entries).unwrap();
    let names = list_tar_gz_paths(&buf);
    assert!(names.contains(&"files/a..b.txt".to_string()));
}

/// Non-canonical prefix (evil.txt, x/y) rejected.
#[test]
fn path_must_have_canonical_prefix() {
    let manifest = ReplayManifest::minimal("2.15.0".into());
    for bad in ["evil.txt", "x/y/z", "output/run.json"] {
        let entries = vec![BundleEntry {
            path: bad.to_string(),
            data: vec![],
        }];
        let err = write_bundle_tar_gz(&mut Vec::new(), &manifest, &entries).unwrap_err();
        assert!(
            err.to_string().contains("invalid bundle path prefix"),
            "{}",
            bad
        );
    }
}

/// Empty segment (duplicate slash) rejected.
#[test]
fn path_rejects_empty_segment() {
    let manifest = ReplayManifest::minimal("2.15.0".into());
    let entries = vec![BundleEntry {
        path: "files//x.json".into(),
        data: vec![],
    }];
    let err = write_bundle_tar_gz(&mut Vec::new(), &manifest, &entries).unwrap_err();
    assert!(err.to_string().contains("empty segment"), "files//x");
}

/// Windows drive-letter-like path rejected.
#[test]
fn path_rejects_drive_letter() {
    let manifest = ReplayManifest::minimal("2.15.0".into());
    for bad in ["C:/foo", "C:\\foo", "D:bar"] {
        let entries = vec![BundleEntry {
            path: bad.to_string(),
            data: vec![],
        }];
        let err = write_bundle_tar_gz(&mut Vec::new(), &manifest, &entries).unwrap_err();
        assert!(
            err.to_string().contains("drive-letter") || err.to_string().contains("first segment"),
            "{}",
            bad
        );
    }
}

/// build_file_manifest fail-closed: invalid path returns Err (same policy as writer).
#[test]
fn build_file_manifest_fail_closed_on_invalid_path() {
    let entries = vec![
        BundleEntry {
            path: "files/ok.json".into(),
            data: vec![],
        },
        BundleEntry {
            path: "../secrets.txt".into(),
            data: vec![],
        },
    ];
    let err = build_file_manifest(&entries).unwrap_err();
    assert!(err.to_string().contains("invalid bundle path"));
}

/// Audit: digest of written bytes equals bundle_digest(manifest, entries).
#[test]
fn bundle_digest_equals_sha256_of_written_bytes() {
    let manifest = ReplayManifest::minimal("2.15.0".into());
    let entries = vec![
        BundleEntry {
            path: "files/trace.jsonl".into(),
            data: b"[]".to_vec(),
        },
        BundleEntry {
            path: "outputs/summary.json".into(),
            data: b"{}".to_vec(),
        },
    ];
    let mut buf = Vec::new();
    write_bundle_tar_gz(&mut buf, &manifest, &entries).unwrap();
    let digest_from_fn = bundle_digest(&manifest, &entries).unwrap();
    let hash_of_bytes = hex::encode(Sha256::digest(&buf));
    assert_eq!(
        digest_from_fn, hash_of_bytes,
        "bundle_digest must equal sha256(written bytes)"
    );
}

/// Audit: path traversal (..) and empty path rejected; no .. or absolute in output.
#[test]
fn path_traversal_rejected_and_output_has_no_traversal() {
    let manifest = ReplayManifest::minimal("2.15.0".into());
    for bad_path in [
        "../secrets.txt",
        "files/../../etc/passwd",
        "outputs/../leak",
        "",
    ] {
        let entries = vec![BundleEntry {
            path: bad_path.to_string(),
            data: vec![],
        }];
        let mut buf = Vec::new();
        let err = write_bundle_tar_gz(&mut buf, &manifest, &entries).unwrap_err();
        assert!(
            err.to_string().contains("invalid bundle path"),
            "{}",
            bad_path
        );
    }
    // Leading slash and backslash are normalized; result must not be in archive as absolute/traversal
    let entries = vec![
        BundleEntry {
            path: "files/trace.jsonl".into(),
            data: b"[]".to_vec(),
        },
        BundleEntry {
            path: "outputs/run.json".into(),
            data: b"{}".to_vec(),
        },
    ];
    let mut buf = Vec::new();
    write_bundle_tar_gz(&mut buf, &manifest, &entries).unwrap();
    let names = list_tar_gz_paths(&buf);
    for name in &names {
        assert!(!name.contains(".."), "no .. in archive path: {}", name);
        assert!(
            !name.starts_with('/'),
            "no leading / in archive path: {}",
            name
        );
    }
    assert!(names.iter().any(|s| s == "manifest.json"));
    assert!(names.iter().any(|s| s.starts_with("files/")));
    assert!(names.iter().any(|s| s.starts_with("outputs/")));
}

/// Audit: full manifest (replay_coverage, seeds, scrub_policy) and canonical layout.
#[test]
fn audit_full_manifest_and_canonical_layout() {
    let mut reason = BTreeMap::new();
    reason.insert(
        "test_b".to_string(),
        "judge response not cached".to_string(),
    );
    let manifest = ReplayManifest {
        schema_version: 1,
        assay_version: "2.15.0".to_string(),
        created_at: Some("2025-01-27T12:00:00Z".to_string()),
        source_run_path: Some(".assay/run_abc123".to_string()),
        selection_method: Some("run-id".to_string()),
        git_sha: Some("a1b2c3d4e5f6".to_string()),
        git_dirty: Some(false),
        workflow_run_id: None,
        config_digest: None,
        policy_digest: None,
        baseline_digest: None,
        trace_digest: None,
        trace_path: Some("files/trace.jsonl".to_string()),
        outputs: Some(ReplayOutputs {
            run: Some("outputs/run.json".to_string()),
            summary: Some("outputs/summary.json".to_string()),
            junit: None,
            sarif: None,
        }),
        toolchain: None,
        seeds: Some(ReplaySeeds {
            seed_version: Some(1),
            order_seed: Some("42".to_string()),
            judge_seed: None,
        }),
        replay_coverage: Some(ReplayCoverage {
            complete_tests: vec!["test_a".to_string()],
            incomplete_tests: vec!["test_b".to_string()],
            reason: Some(reason),
        }),
        scrub_policy: Some(ScrubPolicy::default()),
        files: None,
        env: None,
    };
    let entries = vec![
        BundleEntry {
            path: "files/trace.jsonl".into(),
            data: b"[]".to_vec(),
        },
        BundleEntry {
            path: "outputs/run.json".into(),
            data: b"{}".to_vec(),
        },
        BundleEntry {
            path: "outputs/summary.json".into(),
            data: b"{}".to_vec(),
        },
        BundleEntry {
            path: "cassettes/.gitkeep".into(),
            data: vec![],
        },
    ];
    let mut buf = Vec::new();
    write_bundle_tar_gz(&mut buf, &manifest, &entries).unwrap();
    let names = list_tar_gz_paths(&buf);
    assert!(
        names.contains(&"manifest.json".to_string()),
        "canonical: manifest at root"
    );
    assert!(names
        .iter()
        .all(|p| !p.contains("..") && !p.starts_with('/')));
    assert!(names.contains(&"manifest.json".to_string()));
    assert!(names.iter().any(|p| p.starts_with("files/")));
    assert!(names.iter().any(|p| p.starts_with("outputs/")));
    assert!(names.iter().any(|p| p.starts_with("cassettes/")));
}

// --- Gap 1: Golden-value snapshot test ---

/// Pinned digest: catches silent reproducibility regressions (serde field order,
/// flate2 compression defaults, tar header changes).
#[test]
fn golden_digest_snapshot() {
    let manifest = ReplayManifest::minimal("2.15.0".into());
    let entries = vec![BundleEntry {
        path: "files/trace.jsonl".into(),
        data: b"[]".to_vec(),
    }];
    let digest = bundle_digest(&manifest, &entries).unwrap();
    assert_eq!(
        digest, "e982d2dd1d7cf56df6b417c7af1bc3f7f334ecfc47298bf5d240f4485f3b7a7c",
        "Golden digest changed — if intentional, update this value after verifying \
             that the new output is still deterministic across platforms"
    );
}

// --- Gap 2: Fix helper + sort-order test ---

/// Returns tar entry paths in **archive order** (no sorting).
fn list_tar_gz_paths(gz: &[u8]) -> Vec<String> {
    let dec = flate2::read::GzDecoder::new(gz);
    let mut ar = tar::Archive::new(dec);
    let mut names = Vec::new();
    for e in ar.entries().unwrap() {
        let e = e.unwrap();
        let path = e.path().unwrap();
        names.push(path.to_string_lossy().replace('\\', "/"));
    }
    names
}

/// Writer must emit entries in sorted order (after manifest). Entries given
/// out-of-order must appear sorted in the archive.
#[test]
fn entries_written_in_sorted_order() {
    let manifest = ReplayManifest::minimal("2.15.0".into());
    // Provide entries deliberately out of sorted order.
    let entries = vec![
        BundleEntry {
            path: "outputs/z.json".into(),
            data: b"{}".to_vec(),
        },
        BundleEntry {
            path: "files/a.jsonl".into(),
            data: b"[]".to_vec(),
        },
        BundleEntry {
            path: "cassettes/m.json".into(),
            data: b"{}".to_vec(),
        },
    ];
    let mut buf = Vec::new();
    write_bundle_tar_gz(&mut buf, &manifest, &entries).unwrap();
    let names = list_tar_gz_paths(&buf);
    assert_eq!(names[0], "manifest.json", "manifest must be first");
    let data_entries: Vec<_> = names[1..].to_vec();
    let mut expected = data_entries.clone();
    expected.sort();
    assert_eq!(
        data_entries, expected,
        "entries after manifest must be in sorted order"
    );
}

// --- Gap 3: Direct unit tests for validate_entry_path ---

#[test]
fn validate_entry_path_accepts_valid_paths() {
    for good in [
        "files/trace.jsonl",
        "outputs/run.json",
        "cassettes/openai/embed.json",
        "files/a..b.txt",
        "files/deep/nested/dir/file.json",
    ] {
        let result = validate_entry_path(good);
        assert!(result.is_ok(), "should accept: {}", good);
        assert_eq!(result.unwrap(), good, "valid path returned unchanged");
    }
}

#[test]
fn validate_entry_path_normalizes_backslash_and_leading_slash() {
    assert_eq!(
        validate_entry_path("files\\trace.jsonl").unwrap(),
        "files/trace.jsonl"
    );
    assert_eq!(
        validate_entry_path("/files/trace.jsonl").unwrap(),
        "files/trace.jsonl"
    );
    assert_eq!(
        validate_entry_path("\\files\\trace.jsonl").unwrap(),
        "files/trace.jsonl"
    );
}

#[test]
fn validate_entry_path_rejects_empty() {
    let err = validate_entry_path("").unwrap_err();
    assert!(err.to_string().contains("empty path"));
}

#[test]
fn validate_entry_path_rejects_empty_segment() {
    let err = validate_entry_path("files//x.json").unwrap_err();
    assert!(err.to_string().contains("empty segment"));
}

#[test]
fn validate_entry_path_rejects_dot_segments() {
    for bad in ["files/./x.json", "files/../x.json", "outputs/.."] {
        let err = validate_entry_path(bad).unwrap_err();
        assert!(
            err.to_string().contains("traversal segment"),
            "should reject: {}",
            bad
        );
    }
}

#[test]
fn validate_entry_path_rejects_drive_letter() {
    for bad in ["C:/foo", "D:bar"] {
        let err = validate_entry_path(bad).unwrap_err();
        assert!(
            err.to_string().contains("drive-letter"),
            "should reject: {}",
            bad
        );
    }
}

#[test]
fn validate_entry_path_rejects_non_canonical_prefix() {
    for bad in ["evil.txt", "x/y/z", "output/run.json", "file/x.json"] {
        let err = validate_entry_path(bad).unwrap_err();
        assert!(
            err.to_string().contains("invalid bundle path prefix"),
            "should reject: {}",
            bad
        );
    }
}