remem-ai 0.5.209

Local-first coding agent memory for Claude Code and OpenAI Codex
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
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
use anyhow::{Context, Result};
use serde::de::DeserializeOwned;
use serde_json::Value;
use std::collections::BTreeSet;
use std::fs;
use std::path::{Component, Path, PathBuf};

use super::types::{
    BenchVerifyFailure, BenchVerifyOptions, BenchVerifyReport, BenchmarkLayer,
    CodingMemoryContract, CodingRunArtifact, MemoryRunArtifact, PublicBenchmarkManifest,
    PublicBenchmarkReport,
};

const REQUIRED_SCHEMA_FILES: [&str; 6] = [
    "schemas/benchmark-manifest.schema.json",
    "schemas/memory-run.schema.json",
    "schemas/coding-run.schema.json",
    "schemas/memory-report.schema.json",
    "schemas/coding-report.schema.json",
    "schemas/reproduction-metadata.schema.json",
];

const MEMORY_ARTIFACT_KEYS: [&str; 5] = [
    "reader_input",
    "retrieved_evidence",
    "answer",
    "score",
    "diagnosis",
];

const CODING_ARTIFACT_KEYS: [&str; 3] = ["patch", "tool_log", "test_log"];

const CODING_FAILURE_REASONS: [&str; 11] = [
    "test_failure",
    "timeout",
    "compile_failure",
    "wrong_file_modified",
    "ignored_memory",
    "missing_memory",
    "stale_memory_followed",
    "irrelevant_memory_distracted",
    "over_context_budget",
    "agent_hallucinated_memory",
    "oracle_inconclusive",
];

pub fn verify_benchmark_artifacts(options: BenchVerifyOptions) -> Result<BenchVerifyReport> {
    let root = options.root;
    let mut state = VerifyState::new(root.clone());

    if !root.exists() {
        state.fail(".".to_string(), "benchmark root does not exist");
        return Ok(state.finish());
    }
    if !root.is_dir() {
        state.fail(".".to_string(), "benchmark root is not a directory");
        return Ok(state.finish());
    }

    validate_required_schemas(&mut state);

    let manifest_paths = collect_manifest_paths(&root)?;
    if manifest_paths.is_empty() {
        state.fail(
            rel_display(&root, &root),
            "benchmark root has no manifests under a manifests/ directory",
        );
    }

    for manifest_path in manifest_paths {
        state.manifests_checked += 1;
        let Some(manifest) =
            read_json::<PublicBenchmarkManifest>(&manifest_path, &mut state, "manifest")
        else {
            continue;
        };
        validate_manifest(&manifest_path, &manifest, &mut state);
        for report_path in &manifest.reports {
            let Some(report_abs) = resolve_public_path(&mut state, report_path, report_path) else {
                continue;
            };
            validate_report_path_layer(&manifest_path, &manifest, &report_abs, &mut state);
        }
    }

    Ok(state.finish())
}

fn validate_required_schemas(state: &mut VerifyState) {
    for relative in REQUIRED_SCHEMA_FILES {
        let Some(path) = resolve_public_path(state, relative, relative) else {
            continue;
        };
        if !path.exists() {
            state.fail(relative.to_string(), "required schema file is missing");
            continue;
        }
        let Some(value) = read_json::<Value>(&path, state, "schema") else {
            continue;
        };
        if value.get("$schema").and_then(Value::as_str).is_none() {
            state.fail(relative.to_string(), "schema is missing $schema");
        }
        if value
            .pointer("/properties/schema_version/const")
            .and_then(Value::as_u64)
            != Some(1)
        {
            state.fail(
                relative.to_string(),
                "schema must pin schema_version const 1",
            );
        }
    }
}

fn validate_manifest(path: &Path, manifest: &PublicBenchmarkManifest, state: &mut VerifyState) {
    let label = rel_display(&state.root, path);
    if manifest.schema_version != 1 {
        state.fail(label.clone(), "manifest schema_version must be 1");
    }
    require_non_blank(&manifest.benchmark_id, &label, "benchmark_id", state);
    require_non_blank(&manifest.version, &label, "version", state);
    if manifest.created_at_epoch <= 0 {
        state.fail(label.clone(), "manifest created_at_epoch must be positive");
    }
    if manifest.conditions.is_empty() {
        state.fail(label.clone(), "manifest conditions must not be empty");
    }
    if manifest.reports.is_empty() {
        state.fail(label.clone(), "manifest reports must not be empty");
    }
    if manifest.source_policy.private_user_memory_allowed {
        state.fail(
            label.clone(),
            "public benchmark manifest must not allow private user memory",
        );
    }
    if !manifest.source_policy.requires_temp_remem_data_dir {
        state.fail(
            label,
            "public benchmark manifest must require temporary REMEM_DATA_DIR isolation",
        );
    }
    if let Some(revision) = manifest.source_policy.external_dataset_revision.as_deref() {
        scan_private_string(
            revision,
            path,
            "source_policy.external_dataset_revision",
            state,
        );
    }
}

fn validate_report_path_layer(
    manifest_path: &Path,
    manifest: &PublicBenchmarkManifest,
    report_path: &Path,
    state: &mut VerifyState,
) {
    state.reports_checked += 1;
    let Some(report) = read_json::<PublicBenchmarkReport>(report_path, state, "report") else {
        return;
    };
    let label = rel_display(&state.root, report_path);
    if report.schema_version != 1 {
        state.fail(label.clone(), "report schema_version must be 1");
    }
    require_non_blank(&report.benchmark_id, &label, "benchmark_id", state);
    require_non_blank(
        &report.benchmark_version,
        &label,
        "benchmark_version",
        state,
    );
    require_non_blank(&report.claim_level, &label, "claim_level", state);
    if report.layer != manifest.layer {
        state.fail(
            label.clone(),
            "report layer must match the manifest layer that references it",
        );
    }
    if report.benchmark_id != manifest.benchmark_id {
        state.fail(
            label.clone(),
            "report benchmark_id must match the manifest benchmark_id",
        );
    }
    if report.conditions.is_empty() {
        state.fail(label.clone(), "report conditions must not be empty");
    }
    if report.schema_refs.is_empty() {
        state.fail(label.clone(), "report schema_refs must not be empty");
    }
    if report.run_artifacts.is_empty() {
        state.fail(label.clone(), "report run_artifacts must not be empty");
    }
    if !report.verifier.required || report.verifier.schema_version != 1 {
        state.fail(
            label.clone(),
            "report verifier metadata must require schema_version 1",
        );
    }
    if report.aggregate_metrics.is_null() {
        state.fail(label.clone(), "report aggregate_metrics must be present");
    }
    scan_private_json(
        &serde_json::to_value(&report).unwrap_or(Value::Null),
        report_path,
        "$",
        state,
    );
    for schema_ref in &report.schema_refs {
        let Some(schema_path) = resolve_public_path(state, schema_ref, schema_ref) else {
            continue;
        };
        if !schema_path.exists() {
            state.fail(schema_ref.clone(), "report schema_ref does not exist");
        }
    }
    for run_artifact in &report.run_artifacts {
        let Some(run_path) = resolve_public_path(state, run_artifact, run_artifact) else {
            continue;
        };
        match report.layer {
            BenchmarkLayer::MemorySystemCapability => {
                validate_memory_run_artifact(&run_path, &report, manifest_path, state)
            }
            BenchmarkLayer::CodingAgentOutcome => {
                validate_coding_run_artifact(&run_path, &report, manifest_path, state)
            }
        }
    }
}

fn validate_memory_run_artifact(
    run_path: &Path,
    report: &PublicBenchmarkReport,
    _manifest_path: &Path,
    state: &mut VerifyState,
) {
    state.run_artifacts_checked += 1;
    let Some(run) = read_json::<MemoryRunArtifact>(run_path, state, "memory run artifact") else {
        return;
    };
    let label = rel_display(&state.root, run_path);
    if run.schema_version != 1 {
        state.fail(label.clone(), "memory run schema_version must be 1");
    }
    if run.layer != BenchmarkLayer::MemorySystemCapability || run.layer != report.layer {
        state.fail(
            label.clone(),
            "memory run layer must be memory_system_capability",
        );
    }
    require_non_blank(&run.benchmark_version, &label, "benchmark_version", state);
    require_non_blank(&run.suite, &label, "suite", state);
    require_non_blank(&run.condition, &label, "condition", state);
    require_non_blank(&run.task_id, &label, "task_id", state);
    if run.reference_time_epoch <= 0 {
        state.fail(
            label.clone(),
            "memory run reference_time_epoch must be positive",
        );
    }
    validate_environment(&run.environment, &label, state);
    if run.reader_model.is_null() {
        state.fail(label.clone(), "memory run reader_model must be present");
    }
    if run.answer.is_null() {
        state.fail(label.clone(), "memory run answer must be present");
    }
    if run.metrics.is_null() {
        state.fail(label.clone(), "memory run metrics must be present");
    }
    if !run.diagnosis.write_side_gap
        && !run.diagnosis.retrieval_side_gap
        && !run.diagnosis.reader_gap
        && !run.diagnosis.policy_abstention
        && run
            .diagnosis
            .notes
            .iter()
            .any(|note| note.trim().is_empty())
    {
        state.fail(
            label.clone(),
            "memory run diagnosis notes must not be blank",
        );
    }
    let abstained = run
        .answer
        .get("abstained")
        .and_then(Value::as_bool)
        .unwrap_or(false);
    if run.retrieval.gold_supporting_event_ids.is_empty() {
        state.fail(
            label.clone(),
            "memory run is missing gold supporting evidence IDs",
        );
    }
    if !abstained && run.condition != "no_memory" && run.retrieval.retrieved_memory_ids.is_empty() {
        state.fail(
            label.clone(),
            "memory run condition requires retrieved memory IDs",
        );
    }
    let diagnosis_explains_abstention = run.diagnosis.policy_abstention
        || run.diagnosis.write_side_gap
        || run.diagnosis.retrieval_side_gap
        || run.diagnosis.reader_gap
        || run.condition == "no_memory";
    if abstained && !diagnosis_explains_abstention {
        state.fail(
            label.clone(),
            "abstained memory run must mark a diagnosis reason",
        );
    }
    if !abstained {
        if run.condition != "no_memory" && run.evidence.cited_memory_ids.is_empty() {
            state.fail(label.clone(), "memory run is missing cited memory IDs");
        }
        if run.evidence.cited_event_ids.is_empty() {
            state.fail(label.clone(), "memory run is missing cited event IDs");
        }
    }
    for id in &run.retrieval.retrieved_supporting_evidence_ids {
        require_non_blank(id, &label, "retrieved_supporting_evidence_ids", state);
    }
    for id in &run.retrieval.missing_supporting_evidence_ids {
        require_non_blank(id, &label, "missing_supporting_evidence_ids", state);
    }
    validate_artifact_map(&run.artifacts, MEMORY_ARTIFACT_KEYS, &label, state);
    scan_private_json(
        &serde_json::to_value(&run).unwrap_or(Value::Null),
        run_path,
        "$",
        state,
    );
}

fn validate_coding_run_artifact(
    run_path: &Path,
    report: &PublicBenchmarkReport,
    _manifest_path: &Path,
    state: &mut VerifyState,
) {
    state.run_artifacts_checked += 1;
    let Some(run) = read_json::<CodingRunArtifact>(run_path, state, "coding run artifact") else {
        return;
    };
    let label = rel_display(&state.root, run_path);
    if run.schema_version != 1 {
        state.fail(label.clone(), "coding run schema_version must be 1");
    }
    if run.layer != BenchmarkLayer::CodingAgentOutcome || run.layer != report.layer {
        state.fail(
            label.clone(),
            "coding run layer must be coding_agent_outcome",
        );
    }
    require_non_blank(&run.benchmark_version, &label, "benchmark_version", state);
    require_non_blank(&run.condition, &label, "condition", state);
    require_non_blank(&run.task_id, &label, "task_id", state);
    validate_environment(&run.environment, &label, state);
    if run.model.is_null() {
        state.fail(label.clone(), "coding run model must be present");
    }
    if run.resolved {
        if run.failure_reason.is_some() {
            state.fail(
                label.clone(),
                "resolved coding run must not carry failure_reason",
            );
        }
    } else {
        let Some(reason) = run.failure_reason.as_deref().map(str::trim) else {
            state.fail(label.clone(), "failed coding run must carry failure_reason");
            return;
        };
        if !CODING_FAILURE_REASONS.contains(&reason) {
            state.fail(label.clone(), "coding run has unknown failure_reason enum");
        }
    }
    validate_coding_metrics(&run, &label, state);
    validate_artifact_map(&run.artifacts, CODING_ARTIFACT_KEYS, &label, state);
    if run.condition == "remem" {
        require_artifact_key(&run.artifacts, "injected_context", &label, state);
        require_artifact_key(&run.artifacts, "remem_db_snapshot", &label, state);
        if let Some(contract) = &run.memory_contract {
            validate_coding_memory_contract(contract, run.failure_reason.as_deref(), &label, state);
        } else {
            state.fail(
                label.clone(),
                "remem coding run must include memory_contract",
            );
        }
    }
    scan_private_json(
        &serde_json::to_value(&run).unwrap_or(Value::Null),
        run_path,
        "$",
        state,
    );
}

fn validate_coding_memory_contract(
    contract: &CodingMemoryContract,
    failure_reason: Option<&str>,
    label: &str,
    state: &mut VerifyState,
) {
    validate_rate(
        contract.citation_precision,
        "memory_contract.citation_precision",
        label,
        state,
    );
    validate_rate(
        contract.citation_recall,
        "memory_contract.citation_recall",
        label,
        state,
    );
    require_unique_positive_ids(
        &contract.injected_memory_ids,
        "memory_contract.injected_memory_ids",
        label,
        state,
    );
    require_unique_positive_ids(
        &contract.used_memory_ids,
        "memory_contract.used_memory_ids",
        label,
        state,
    );
    if contract.memory_helped && contract.memory_hurt {
        state.fail(
            label.to_string(),
            "memory_contract cannot mark both memory_helped and memory_hurt",
        );
    }
    if failure_reason.is_some_and(is_memory_specific_failure_reason) && !contract.memory_hurt {
        state.fail(
            label.to_string(),
            "memory-specific failure_reason requires memory_contract.memory_hurt=true",
        );
    }
}

fn validate_rate(value: f64, field: &str, label: &str, state: &mut VerifyState) {
    if !(0.0..=1.0).contains(&value) || !value.is_finite() {
        state.fail(
            label.to_string(),
            format!("{field} must be a finite rate between 0 and 1"),
        );
    }
}

fn require_unique_positive_ids(ids: &[i64], field: &str, label: &str, state: &mut VerifyState) {
    let mut seen = BTreeSet::new();
    for id in ids {
        if *id <= 0 {
            state.fail(
                label.to_string(),
                format!("{field} contains non-positive id"),
            );
        }
        if !seen.insert(*id) {
            state.fail(label.to_string(), format!("{field} contains duplicate id"));
        }
    }
}

fn is_memory_specific_failure_reason(reason: &str) -> bool {
    matches!(
        reason,
        "ignored_memory"
            | "missing_memory"
            | "stale_memory_followed"
            | "irrelevant_memory_distracted"
            | "agent_hallucinated_memory"
    )
}

fn validate_coding_metrics(run: &CodingRunArtifact, label: &str, state: &mut VerifyState) {
    if let (Some(input), Some(output), Some(total)) = (
        run.metrics.tokens_input,
        run.metrics.tokens_output,
        run.metrics.tokens_total,
    ) {
        if input.saturating_add(output) != total {
            state.fail(label.to_string(), "coding run token totals do not add up");
        }
    } else {
        state.fail(
            label.to_string(),
            "coding run must include complete token accounting",
        );
    }
    if run.metrics.turns.is_none() {
        state.fail(label.to_string(), "coding run is missing turns");
    }
    if run.metrics.wall_time_ms.is_none() {
        state.fail(label.to_string(), "coding run is missing wall_time_ms");
    }
    if run.metrics.tool_calls.is_none() {
        state.fail(label.to_string(), "coding run is missing tool_calls");
    }
    if run.metrics.commands_run.is_none() {
        state.fail(label.to_string(), "coding run is missing commands_run");
    }
}

fn validate_environment(env: &super::types::RunEnvironment, label: &str, state: &mut VerifyState) {
    require_non_blank(&env.os, label, "environment.os", state);
    require_non_blank(&env.arch, label, "environment.arch", state);
    require_non_blank(&env.remem_commit, label, "environment.remem_commit", state);
    require_non_blank(
        &env.remem_data_dir,
        label,
        "environment.remem_data_dir",
        state,
    );
    if !env.remem_data_dir.starts_with("temp://")
        && !env.remem_data_dir.starts_with("/tmp/")
        && !env.remem_data_dir.starts_with("/private/tmp/")
    {
        state.fail(
            label.to_string(),
            "environment.remem_data_dir must prove temporary isolation",
        );
    }
    if let Some(digest) = env.docker_image_digest.as_deref() {
        require_non_blank(digest, label, "environment.docker_image_digest", state);
    }
    if let Some(revision) = env.fixture_revision.as_deref() {
        require_non_blank(revision, label, "environment.fixture_revision", state);
    }
    if let Some(commit) = env.repo_base_commit.as_deref() {
        require_non_blank(commit, label, "environment.repo_base_commit", state);
    }
}

fn validate_artifact_map<const N: usize>(
    artifacts: &std::collections::BTreeMap<String, String>,
    required_keys: [&str; N],
    label: &str,
    state: &mut VerifyState,
) {
    for key in required_keys {
        require_artifact_key(artifacts, key, label, state);
    }
}

fn require_artifact_key(
    artifacts: &std::collections::BTreeMap<String, String>,
    key: &str,
    label: &str,
    state: &mut VerifyState,
) {
    let Some(raw_path) = artifacts.get(key) else {
        state.fail(label.to_string(), format!("artifact key {key} is missing"));
        return;
    };
    let Some(path) = resolve_public_path(state, raw_path, raw_path) else {
        return;
    };
    if !path.exists() {
        state.fail(
            raw_path.clone(),
            format!("artifact file for {key} is missing"),
        );
        return;
    }
    state.artifact_files.insert(rel_display(&state.root, &path));
}

fn require_non_blank(value: &str, label: &str, field: &str, state: &mut VerifyState) {
    if value.trim().is_empty() {
        state.fail(label.to_string(), format!("{field} must not be blank"));
    }
}

fn read_json<T: DeserializeOwned>(path: &Path, state: &mut VerifyState, label: &str) -> Option<T> {
    let display = rel_display(&state.root, path);
    let content = match fs::read_to_string(path) {
        Ok(content) => content,
        Err(err) => {
            state.fail(display, format!("read {label}: {err}"));
            return None;
        }
    };
    let value = match serde_json::from_str::<Value>(&content) {
        Ok(value) => value,
        Err(err) => {
            state.fail(display, format!("parse {label} JSON: {err}"));
            return None;
        }
    };
    scan_private_json(&value, path, "$", state);
    match serde_json::from_value::<T>(value) {
        Ok(parsed) => Some(parsed),
        Err(err) => {
            state.fail(display, format!("validate {label} schema: {err}"));
            None
        }
    }
}

pub(super) fn collect_manifest_paths(root: &Path) -> Result<Vec<PathBuf>> {
    let mut paths = Vec::new();
    collect_manifest_paths_recursive(root, &mut paths)
        .with_context(|| format!("scan benchmark manifests under {}", root.display()))?;
    paths.sort();
    Ok(paths)
}

fn collect_manifest_paths_recursive(dir: &Path, paths: &mut Vec<PathBuf>) -> Result<()> {
    for entry in fs::read_dir(dir).with_context(|| format!("read directory {}", dir.display()))? {
        let entry = entry?;
        let path = entry.path();
        if path.is_dir() {
            collect_manifest_paths_recursive(&path, paths)?;
        } else if path.extension().is_some_and(|ext| ext == "json")
            && path
                .parent()
                .and_then(Path::file_name)
                .is_some_and(|name| name == "manifests")
        {
            paths.push(path);
        }
    }
    Ok(())
}

fn resolve_public_path(state: &mut VerifyState, raw: &str, label: &str) -> Option<PathBuf> {
    let root = state.root.clone();
    scan_private_string(raw, &root.join(label), label, state);
    let path = Path::new(raw);
    if path.is_absolute() {
        state.fail(label.to_string(), "artifact path must be relative");
        return None;
    }
    if raw.trim().is_empty() {
        state.fail(label.to_string(), "artifact path must not be blank");
        return None;
    }
    if path.components().any(|component| {
        matches!(
            component,
            Component::ParentDir | Component::RootDir | Component::Prefix(_)
        )
    }) {
        state.fail(
            label.to_string(),
            "artifact path must stay inside benchmark root",
        );
        return None;
    }
    Some(root.join(path))
}

fn scan_private_json(value: &Value, path: &Path, pointer: &str, state: &mut VerifyState) {
    match value {
        Value::String(text) => scan_private_string(text, path, pointer, state),
        Value::Array(items) => {
            for (index, item) in items.iter().enumerate() {
                scan_private_json(item, path, &format!("{pointer}/{index}"), state);
            }
        }
        Value::Object(object) => {
            for (key, item) in object {
                scan_private_json(item, path, &format!("{pointer}/{key}"), state);
            }
        }
        Value::Bool(_) | Value::Number(_) | Value::Null => {}
    }
}

fn scan_private_string(text: &str, path: &Path, pointer: &str, state: &mut VerifyState) {
    if text.contains("~/.remem")
        || text.contains("$HOME/.remem")
        || text.contains("${HOME}/.remem")
        || contains_user_remem_path(text)
    {
        state.fail(
            rel_display(&state.root, path),
            format!("{pointer} contains a private remem path"),
        );
    }
    if let Some(home) = dirs::home_dir().and_then(|path| path.into_os_string().into_string().ok()) {
        if text.starts_with(&home) {
            state.fail(
                rel_display(&state.root, path),
                format!("{pointer} contains an absolute path under the current user home"),
            );
        }
    }
}

fn contains_user_remem_path(text: &str) -> bool {
    text.contains("/.remem/")
        && (text.contains("/Users/") || text.contains("/home/") || text.contains("/var/home/"))
}

fn rel_display(root: &Path, path: &Path) -> String {
    path.strip_prefix(root)
        .unwrap_or(path)
        .to_string_lossy()
        .replace('\\', "/")
}

struct VerifyState {
    root: PathBuf,
    manifests_checked: usize,
    reports_checked: usize,
    run_artifacts_checked: usize,
    artifact_files: BTreeSet<String>,
    failures: Vec<BenchVerifyFailure>,
}

impl VerifyState {
    fn new(root: PathBuf) -> Self {
        Self {
            root,
            manifests_checked: 0,
            reports_checked: 0,
            run_artifacts_checked: 0,
            artifact_files: BTreeSet::new(),
            failures: Vec::new(),
        }
    }

    fn fail(&mut self, path: String, message: impl Into<String>) {
        self.failures.push(BenchVerifyFailure {
            path,
            message: message.into(),
        });
    }

    fn finish(self) -> BenchVerifyReport {
        BenchVerifyReport {
            schema_version: 1,
            root: self.root.to_string_lossy().into_owned(),
            passed: self.failures.is_empty(),
            manifests_checked: self.manifests_checked,
            reports_checked: self.reports_checked,
            run_artifacts_checked: self.run_artifacts_checked,
            artifact_files_checked: self.artifact_files.len(),
            failures: self.failures,
        }
    }
}