aristo-cli 0.1.0

Aristo CLI binary (the `aristo` command).
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
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
//! Mechanical validator for `.aristo/proofs/<id>.proof` files.
//!
//! The validator gates a status flip on a verdict: only if every check
//! passes does the SDK accept the verdict and update the index entry's
//! status. Failures collect into a single [`ValidatorReport`] (not
//! short-circuit) so the user — or the in-agent repair loop — sees the
//! full list of what needs fixing in one pass.
//!
//! The check list is intentionally bounded and mechanical. There is NO
//! LLM-as-judge in the validator path; the schema enforcement IS the
//! audit story. (Roundtrip semantic checks are deferred — see
//! `../../../../aretta-sdk/docs/verification-research-notes.md`.)

use std::collections::HashSet;
use std::path::Path;

use aristo_core::hash::{body_hash, text_hash};
use aristo_core::index::{AnnotationId, IndexEntry, IndexFile, Sha256, Status, VerifyLevel};
use aristo_core::proof::{
    Gap, Ground, InconclusiveBody, Proof, ProofFile, ProofStep, VerdictBody, Violation,
};

/// Maximum repair attempts the validator accepts. A verdict with
/// `attempts > MAX_REPAIR_ATTEMPTS` is rejected even if structurally
/// well-formed — the verifier ran out of repair budget and should have
/// converted to inconclusive.
pub(crate) const MAX_REPAIR_ATTEMPTS: u32 = 3;

#[derive(Debug)]
pub(crate) struct ValidatorReport {
    pub failures: Vec<ValidationFailure>,
}

impl ValidatorReport {
    fn empty() -> Self {
        Self {
            failures: Vec::new(),
        }
    }

    fn push(&mut self, location: String, detail: String) {
        self.failures.push(ValidationFailure { location, detail });
    }

    pub fn is_empty(&self) -> bool {
        self.failures.is_empty()
    }

    /// Render as a multi-line human-readable message for the CLI error
    /// stream. Each failure on its own line, prefixed with the location
    /// in the proof file.
    pub fn render(&self) -> String {
        use std::fmt::Write;
        let mut out = String::new();
        let _ = writeln!(
            out,
            "verdict rejected ({} check(s) failed):",
            self.failures.len()
        );
        for f in &self.failures {
            let _ = writeln!(out, "{}: {}", f.location, f.detail);
        }
        out
    }
}

#[derive(Debug)]
pub(crate) struct ValidationFailure {
    pub location: String,
    pub detail: String,
}

#[aristo::intent(
    "The validator collects EVERY failure into one report rather than \
     short-circuiting on the first. The user (or in-agent repair loop) \
     needs the complete list to fix in one pass; short-circuiting \
     forces N round-trips for N failures, which doesn't compose with \
     the bounded-attempts budget (the verifier would burn its budget \
     fixing failures one at a time).",
    verify = "test",
    id = "validator_collects_all_failures_not_short_circuit"
)]
pub(crate) fn validate(
    focal_id: &AnnotationId,
    pf: &ProofFile,
    index: &IndexFile,
    workspace_root: &Path,
) -> ValidatorReport {
    let mut r = ValidatorReport::empty();

    // ─── verdict meta ───
    check_attempts_budget(&mut r, pf);
    check_focal_entry_hashes(&mut r, focal_id, pf, index);
    check_method_matches(&mut r, focal_id, pf, index);

    // ─── body shape ───
    let body = match pf.body() {
        Ok(b) => b,
        Err(e) => {
            r.push("verdict".into(), format!("body shape: {e}"));
            return r; // No body → no point checking step-level invariants.
        }
    };

    // ─── per-body-type checks ───
    match body {
        VerdictBody::Verified(v) => {
            check_verified_proof_nonempty(&mut r, &v.proof);
            check_proof_tree(&mut r, "verified.proof", &v.proof.steps);
            check_all_grounds(
                &mut r,
                "verified.proof",
                &v.proof.steps,
                index,
                workspace_root,
            );
        }
        VerdictBody::Counterexample(c) => {
            check_counterexample(&mut r, &c.violation);
            check_proof_tree(
                &mut r,
                "counterexample.violation.trigger_steps",
                &c.violation.trigger_steps,
            );
            check_all_grounds(
                &mut r,
                "counterexample.violation.trigger_steps",
                &c.violation.trigger_steps,
                index,
                workspace_root,
            );
        }
        VerdictBody::Inconclusive(i) => {
            check_gap(&mut r, &i.gap);
            check_inconclusive_suggestions_not_yet_addressed(&mut r, i, index);
            if let Some(p) = &i.partial_proof {
                check_proof_tree(&mut r, "inconclusive.partial_proof", &p.steps);
                check_all_grounds(
                    &mut r,
                    "inconclusive.partial_proof",
                    &p.steps,
                    index,
                    workspace_root,
                );
            }
        }
    }

    r
}

// ─── verdict-meta checks ──────────────────────────────────────────────────

fn check_attempts_budget(r: &mut ValidatorReport, pf: &ProofFile) {
    if pf.verdict.attempts == 0 {
        r.push(
            "verdict.attempts".into(),
            "attempts is 0; first attempt is 1".into(),
        );
    }
    if pf.verdict.attempts > MAX_REPAIR_ATTEMPTS {
        r.push(
            "verdict.attempts".into(),
            format!(
                "attempts={} exceeds budget {}; convert to inconclusive instead of \
                 continuing to retry past the cap",
                pf.verdict.attempts, MAX_REPAIR_ATTEMPTS
            ),
        );
    }
}

fn check_focal_entry_hashes(
    r: &mut ValidatorReport,
    focal_id: &AnnotationId,
    pf: &ProofFile,
    index: &IndexFile,
) {
    let Some(entry) = index.entries.get(focal_id) else {
        r.push(
            format!("focal entry `{focal_id}`"),
            "not found in current index".into(),
        );
        return;
    };
    let (text_h, body_h) = entry_hashes(entry);
    if pf.verdict.produced_at_text_hash != text_h {
        r.push(
            "verdict.produced_at_text_hash".into(),
            "differs from current index text_hash; entry text drifted since verification".into(),
        );
    }
    if pf.verdict.produced_at_body_hash != body_h {
        r.push(
            "verdict.produced_at_body_hash".into(),
            "differs from current index body_hash; entry code drifted since verification".into(),
        );
    }
}

fn check_method_matches(
    r: &mut ValidatorReport,
    focal_id: &AnnotationId,
    pf: &ProofFile,
    index: &IndexFile,
) {
    let Some(entry) = index.entries.get(focal_id) else {
        return; // already reported by check_focal_entry_hashes
    };
    let entry_method = match entry_verify(entry) {
        VerifyLevel::Method(m) => m,
        VerifyLevel::Bool(_) => {
            r.push(
                "verdict.method".into(),
                "focal entry has verify=true/false; only verify=neural/test/full \
                 entries accept a method-bound proof"
                    .into(),
            );
            return;
        }
    };
    if pf.verdict.method != entry_method {
        r.push(
            "verdict.method".into(),
            format!(
                "verdict claims method `{:?}` but focal entry's resolved method is `{:?}`",
                pf.verdict.method, entry_method
            ),
        );
    }
}

// ─── verified-body checks ─────────────────────────────────────────────────

fn check_verified_proof_nonempty(r: &mut ValidatorReport, p: &Proof) {
    if p.conclusion.trim().is_empty() {
        r.push("verified.proof.conclusion".into(), "is empty".into());
    }
    if p.steps.is_empty() {
        r.push(
            "verified.proof.steps".into(),
            "is empty; a verified verdict needs at least one proof step".into(),
        );
    }
}

// ─── counterexample-body checks ───────────────────────────────────────────

fn check_counterexample(r: &mut ValidatorReport, v: &Violation) {
    if v.description.trim().is_empty() {
        r.push(
            "counterexample.violation.description".into(),
            "is empty".into(),
        );
    }
    if v.violated_step_path.trim().is_empty() {
        r.push(
            "counterexample.violation.violated_step_path".into(),
            "is empty; must point at the proof step the trigger refutes".into(),
        );
    }
    if v.trigger_steps.is_empty() {
        r.push(
            "counterexample.violation.trigger_steps".into(),
            "is empty; counterexamples must demonstrate the violating trace concretely".into(),
        );
    }
}

// ─── inconclusive-body checks ─────────────────────────────────────────────

fn check_gap(r: &mut ValidatorReport, g: &Gap) {
    if g.description.trim().is_empty() {
        r.push("inconclusive.gap.description".into(), "is empty".into());
    }
    if g.unfilled_path.trim().is_empty() {
        r.push(
            "inconclusive.gap.unfilled_path".into(),
            "is empty; must identify which subgoal could not be discharged".into(),
        );
    }
    if g.suggested_annotations.is_empty() {
        r.push(
            "inconclusive.gap.suggested_annotations".into(),
            "is empty; inconclusive verdicts MUST suggest at least one annotation \
             that would close the gap — bare inconclusive without actionable suggestion \
             is no better than 'I don't know'"
                .into(),
        );
    }
}

#[aristo::intent(
    "An inconclusive verdict is stale once any of its suggested \
     annotations is present in the current index (text-hash match). \
     Either the user adopted the suggestion (good — re-run to see if \
     the gap closes) or the agent missed an existing entry that would \
     have closed the gap (good — re-run with the entry available as a \
     ground). Both paths converge on 'this verdict is no longer the \
     best answer; re-verify'. Without this check, adopting a suggestion \
     never moves the entry back to pending — the user adds the assume \
     the agent asked for, and aristo verify silently skips it forever.",
    verify = "test",
    id = "validator_rejects_inconclusive_when_suggestion_is_in_index"
)]
fn check_inconclusive_suggestions_not_yet_addressed(
    r: &mut ValidatorReport,
    body: &InconclusiveBody,
    index: &IndexFile,
) {
    // Pre-compute text_hash for every existing entry once.
    let existing_text_hashes: std::collections::HashSet<&Sha256> = index
        .entries
        .values()
        .map(|e| match e {
            IndexEntry::Intent(x) => &x.text_hash,
            IndexEntry::Assume(x) => &x.text_hash,
        })
        .collect();
    for (idx, suggestion) in body.gap.suggested_annotations.iter().enumerate() {
        let sug_hash = text_hash(&suggestion.suggested_text);
        if existing_text_hashes.contains(&sug_hash) {
            r.push(
                format!("inconclusive.gap.suggested_annotations[{idx}]"),
                format!(
                    "a matching annotation now exists in the index — the suggested \
                     `{:?}` (\"{}\") is present, so this inconclusive verdict is \
                     stale; re-run verification to see if the gap closes",
                    suggestion.kind,
                    truncate(&suggestion.suggested_text, 60)
                ),
            );
        }
    }
}

fn truncate(s: &str, max: usize) -> String {
    if s.chars().count() <= max {
        s.to_string()
    } else {
        let mut t: String = s.chars().take(max).collect();
        t.push('');
        t
    }
}

// ─── proof-tree structural checks ─────────────────────────────────────────

fn check_proof_tree(r: &mut ValidatorReport, prefix: &str, steps: &[ProofStep]) {
    if steps.is_empty() {
        return; // verified-empty / counterexample-empty already reported
    }

    // Path uniqueness.
    let mut seen = HashSet::new();
    for s in steps {
        if !seen.insert(&s.path) {
            r.push(
                format!("{prefix}.steps[{}]", s.path),
                "duplicate path".into(),
            );
        }
    }

    // Root must be "0".
    if !steps.iter().any(|s| s.path == "0") {
        r.push(
            format!("{prefix}.steps"),
            "no step with path \"0\" — tree must be rooted at \"0\"".into(),
        );
    }

    // subgoal_paths cross-references must resolve to actual steps.
    for s in steps {
        for sp in &s.subgoal_paths {
            if !steps.iter().any(|x| &x.path == sp) {
                r.push(
                    format!("{prefix}.steps[{}].subgoal_paths", s.path),
                    format!("`{sp}` does not resolve to any step in this tree"),
                );
            } else if !sp.starts_with(&format!("{}.", s.path)) {
                r.push(
                    format!("{prefix}.steps[{}].subgoal_paths", s.path),
                    format!(
                        "`{sp}` is not a descendant of `{}` (subgoal paths must extend the parent's path)",
                        s.path
                    ),
                );
            }
        }
    }

    // Every step has ≥1 ground.
    for s in steps {
        if s.grounds.is_empty() {
            r.push(
                format!("{prefix}.steps[{}].grounds", s.path),
                "step has zero grounds; every claim needs at least one ground (no 'trust me' steps)"
                    .into(),
            );
        }
    }
}

// ─── ground checks ────────────────────────────────────────────────────────

fn check_all_grounds(
    r: &mut ValidatorReport,
    prefix: &str,
    steps: &[ProofStep],
    index: &IndexFile,
    workspace_root: &Path,
) {
    let step_paths: HashSet<&str> = steps.iter().map(|s| s.path.as_str()).collect();
    for s in steps {
        for (i, g) in s.grounds.iter().enumerate() {
            check_one_ground(
                r,
                &format!("{prefix}.steps[{}].grounds[{}]", s.path, i),
                g,
                &s.path,
                &step_paths,
                index,
                workspace_root,
            );
        }
    }
}

#[aristo::intent(
    "Validator computes ground hashes from the agent's citations \
     (file+lines for code grounds, id-lookup-in-index for intent/ \
     assume grounds); the agent is not required to write them. The \
     stored hash, when present, is the validator's stamp from a prior \
     successful validation and is checked here for staleness — \
     mismatch means the cited source/intent drifted since the proof \
     was last accepted. Pushing hash computation out of the LLM's \
     job kills the dominant fabrication failure mode without weakening \
     the freshness guarantee: every accepted proof carries a hash \
     anchor, computed mechanically.",
    verify = "test",
    id = "validator_computes_ground_hashes_agent_only_cites"
)]
fn check_one_ground(
    r: &mut ValidatorReport,
    location: &str,
    g: &Ground,
    owning_path: &str,
    step_paths: &HashSet<&str>,
    index: &IndexFile,
    workspace_root: &Path,
) {
    match g {
        Ground::Intent {
            id, at_text_hash, ..
        }
        | Ground::Assume {
            id, at_text_hash, ..
        } => {
            check_index_ground(r, location, id, at_text_hash.as_ref(), g, index);
        }
        Ground::Code {
            file,
            lines,
            code_text_hash,
            ..
        } => {
            check_code_ground(
                r,
                location,
                file,
                lines,
                code_text_hash.as_ref(),
                workspace_root,
            );
        }
        Ground::PriorStep { path, .. } => {
            check_prior_step_ground(r, location, owning_path, path, step_paths);
        }
        Ground::Composition { reason } => {
            if reason.trim().is_empty() {
                r.push(
                    location.into(),
                    "composition ground has empty reason".into(),
                );
            }
        }
    }
}

#[aristo::intent(
    "Cited intent/assume grounds are rejected when (a) the id is \
     dangling, (b) the cited entry is verify=false (docs-only — not \
     load-bearing for a proof), or (c) the cited entry is Status::\
     Counterexample (refuted — building on it would launder a refuted \
     claim back into Verified). A refactor that downgrades any of \
     these to warnings would let proofs ground in claims the project \
     doesn't actually believe.",
    verify = "test",
    id = "validator_rejects_grounding_in_refuted_or_docs_only"
)]
fn check_index_ground(
    r: &mut ValidatorReport,
    location: &str,
    id: &AnnotationId,
    at_text_hash: Option<&Sha256>,
    g: &Ground,
    index: &IndexFile,
) {
    let Some(entry) = index.entries.get(id) else {
        r.push(
            location.into(),
            format!("cited id `{id}` not found in current index"),
        );
        return;
    };
    let (cur_text_hash, _) = entry_hashes(entry);
    if let Some(stamped) = at_text_hash {
        if stamped != &cur_text_hash {
            r.push(
                location.into(),
                format!(
                    "at_text_hash for cited `{id}` differs from current; cited entry's \
                     text changed since verification — re-check whether the new wording \
                     still supports this step"
                ),
            );
        }
    }
    // For Intent grounds: ensure the cited entry isn't refuted or docs-only.
    if matches!(g, Ground::Intent { .. }) {
        if let VerifyLevel::Bool(false) = entry_verify(entry) {
            r.push(
                location.into(),
                format!(
                    "cited intent `{id}` is verify=false (documentation only); cannot \
                     ground a proof in a docs-only claim"
                ),
            );
        }
        if entry_status(entry) == Status::Counterexample {
            r.push(
                location.into(),
                format!(
                    "cited intent `{id}` has status=counterexample (refuted); cannot \
                     ground a proof in a refuted claim"
                ),
            );
        }
    }
}

fn check_code_ground(
    r: &mut ValidatorReport,
    location: &str,
    file: &str,
    lines: &str,
    code_text_hash: Option<&Sha256>,
    workspace_root: &Path,
) {
    let path = workspace_root.join(file);
    let Ok(source) = std::fs::read_to_string(&path) else {
        r.push(
            location.into(),
            format!("code file `{file}` does not exist under workspace root"),
        );
        return;
    };
    let Some((lo, hi)) = parse_line_range(lines) else {
        r.push(
            location.into(),
            format!("lines `{lines}` is not a valid range (expected `N` or `N-M` with N ≤ M)"),
        );
        return;
    };
    let total_lines = source.lines().count();
    if hi > total_lines {
        r.push(
            location.into(),
            format!("line range `{lines}` exceeds file length {total_lines}"),
        );
        return;
    }
    // Only verify a stamped hash; absent hash means agent-written, will be
    // stamped on accept by the apply step.
    if let Some(stamped) = code_text_hash {
        let slice = slice_lines(&source, lo, hi);
        let actual = body_hash(&slice);
        if &actual != stamped {
            r.push(
                location.into(),
                format!(
                    "code_text_hash for `{file}:{lines}` differs from current file content; \
                     the cited code drifted since verification"
                ),
            );
        }
    }
}

/// Slice 1-indexed inclusive `[lo, hi]` from `source` and join with `\n`.
/// Used by both the validator (re-hash for staleness) and apply (compute
/// stamp). Kept in one place so the two routes never disagree.
pub(crate) fn slice_lines(source: &str, lo: usize, hi: usize) -> String {
    source
        .lines()
        .skip(lo - 1)
        .take(hi - lo + 1)
        .collect::<Vec<_>>()
        .join("\n")
}

fn check_prior_step_ground(
    r: &mut ValidatorReport,
    location: &str,
    owning_path: &str,
    cited_path: &str,
    step_paths: &HashSet<&str>,
) {
    if !step_paths.contains(cited_path) {
        r.push(
            location.into(),
            format!("prior-step `{cited_path}` does not resolve to any step in this tree"),
        );
        return;
    }
    // Prior-step must be lexicographically earlier than owning path so the
    // proof DAG is acyclic. We approximate "earlier" with string compare on
    // the dotted path — works because step indices are integers ≤ 9 in
    // practice (verifier discipline). For ≥10-child nodes a richer
    // comparison would be needed; revisit if it bites.
    if cited_path >= owning_path {
        r.push(
            location.into(),
            format!(
                "prior-step `{cited_path}` is not earlier than owning step `{owning_path}`; \
                 prior-step grounds must reference EARLIER steps only (no cycles)"
            ),
        );
    }
}

// ─── helpers ──────────────────────────────────────────────────────────────

fn entry_hashes(entry: &IndexEntry) -> (Sha256, Sha256) {
    match entry {
        IndexEntry::Intent(e) => (e.text_hash.clone(), e.body_hash.clone()),
        IndexEntry::Assume(e) => (e.text_hash.clone(), e.body_hash.clone()),
    }
}

fn entry_verify(entry: &IndexEntry) -> VerifyLevel {
    match entry {
        IndexEntry::Intent(e) => e.verify,
        IndexEntry::Assume(_) => VerifyLevel::Bool(false),
    }
}

fn entry_status(entry: &IndexEntry) -> Status {
    match entry {
        IndexEntry::Intent(e) => e.status,
        IndexEntry::Assume(e) => e.status,
    }
}

pub(crate) fn parse_line_range(s: &str) -> Option<(usize, usize)> {
    match s.split_once('-') {
        Some((a, b)) => {
            let lo: usize = a.parse().ok()?;
            let hi: usize = b.parse().ok()?;
            if lo == 0 || hi < lo {
                None
            } else {
                Some((lo, hi))
            }
        }
        None => {
            let n: usize = s.parse().ok()?;
            if n == 0 {
                None
            } else {
                Some((n, n))
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use aristo_core::hash::text_hash;
    use aristo_core::index::{IntentEntry, Meta, VerifyMethod};
    use aristo_core::proof::{
        Ground, GroundRelation, PropertyKind, RelationKind, VerdictMeta, VerdictType, VerifiedBody,
    };
    use std::collections::BTreeMap;

    fn sample_id(s: &str) -> AnnotationId {
        AnnotationId::parse(s).unwrap()
    }

    fn sample_hash(s: &str) -> Sha256 {
        text_hash(s)
    }

    fn index_with_one_intent(id: &str, text: &str, status: Status) -> IndexFile {
        let mut entries = BTreeMap::new();
        entries.insert(
            sample_id(id),
            IndexEntry::Intent(IntentEntry {
                text: text.into(),
                verify: VerifyLevel::Method(VerifyMethod::Neural),
                status,
                text_hash: text_hash(text),
                body_hash: sample_hash("body"),
                file: "src/x.rs".into(),
                site: "fn x (line 1)".into(),
                covered_region: aristo_core::index::CoveredRegion::Function,
                binding: aristo_core::index::BindingState::Local,
                parent: None,
                last_critiqued_at_text_hash: None,
                last_critique_finding_count: None,
            }),
        );
        IndexFile {
            meta: Meta {
                schema_version: 1,
                generated_by: None,
                generated_at: None,
                source_root: None,
            },
            entries,
        }
    }

    fn minimal_verified(focal_text: &str, focal_body: &str) -> ProofFile {
        ProofFile {
            verdict: VerdictMeta {
                r#type: VerdictType::Verified,
                method: VerifyMethod::Neural,
                produced_at_text_hash: text_hash(focal_text),
                produced_at_body_hash: sample_hash(focal_body),
                produced_by: "test@0".into(),
                verifier_model: None,
                attempts: 1,
                property_kind: PropertyKind::Invariant,
            },
            verified: Some(VerifiedBody {
                proof: Proof {
                    conclusion: "the property holds".into(),
                    steps: vec![ProofStep {
                        path: "0".into(),
                        claim: "by construction".into(),
                        relation_to_parent: RelationKind::Decomposes,
                        grounds: vec![Ground::Composition {
                            reason: "trivial".into(),
                        }],
                        subgoal_paths: vec![],
                        proposed_promotion: false,
                    }],
                },
            }),
            counterexample: None,
            inconclusive: None,
        }
    }

    #[test]
    fn empty_failure_list_renders_as_zero_failed() {
        let r = ValidatorReport::empty();
        assert!(r.is_empty());
    }

    #[test]
    fn minimal_valid_verdict_passes() {
        let idx = index_with_one_intent("foo", "the property", Status::Unknown);
        let pf = minimal_verified("the property", "body");
        let tmp = tempfile::tempdir().unwrap();
        let report = validate(&sample_id("foo"), &pf, &idx, tmp.path());
        assert!(report.is_empty(), "expected pass; got: {}", report.render());
    }

    #[test]
    fn rejects_zero_attempts() {
        let idx = index_with_one_intent("foo", "the property", Status::Unknown);
        let mut pf = minimal_verified("the property", "body");
        pf.verdict.attempts = 0;
        let report = validate(&sample_id("foo"), &pf, &idx, Path::new("/"));
        assert!(report
            .failures
            .iter()
            .any(|f| f.location == "verdict.attempts"));
    }

    #[test]
    fn rejects_attempts_over_budget() {
        let idx = index_with_one_intent("foo", "the property", Status::Unknown);
        let mut pf = minimal_verified("the property", "body");
        pf.verdict.attempts = MAX_REPAIR_ATTEMPTS + 1;
        let report = validate(&sample_id("foo"), &pf, &idx, Path::new("/"));
        assert!(report
            .failures
            .iter()
            .any(|f| { f.location == "verdict.attempts" && f.detail.contains("exceeds budget") }));
    }

    #[test]
    fn rejects_stale_focal_text_hash() {
        let idx = index_with_one_intent("foo", "the property", Status::Unknown);
        let mut pf = minimal_verified("DIFFERENT TEXT", "body");
        pf.verdict.attempts = 1;
        let report = validate(&sample_id("foo"), &pf, &idx, Path::new("/"));
        assert!(report
            .failures
            .iter()
            .any(|f| f.location == "verdict.produced_at_text_hash"));
    }

    #[test]
    fn rejects_dangling_focal_id() {
        let idx = index_with_one_intent("foo", "the property", Status::Unknown);
        let pf = minimal_verified("anything", "body");
        let report = validate(&sample_id("bar"), &pf, &idx, Path::new("/"));
        assert!(report
            .failures
            .iter()
            .any(|f| f.location == "focal entry `bar`"));
    }

    #[test]
    fn rejects_intent_ground_citing_dangling_id() {
        let idx = index_with_one_intent("foo", "the property", Status::Unknown);
        let mut pf = minimal_verified("the property", "body");
        pf.verified.as_mut().unwrap().proof.steps[0].grounds = vec![Ground::Intent {
            id: sample_id("nonexistent"),
            at_text_hash: Some(sample_hash("x")),
            relation: GroundRelation::Instantiates,
            reason: None,
        }];
        let report = validate(&sample_id("foo"), &pf, &idx, Path::new("/"));
        assert!(report
            .failures
            .iter()
            .any(|f| f.detail.contains("not found in current index")));
    }

    #[test]
    fn rejects_intent_ground_with_stale_text_hash() {
        let idx = index_with_one_intent("ground", "current text", Status::Unknown);
        let mut idx = idx;
        // Add focal entry too
        idx.entries.insert(
            sample_id("focal"),
            IndexEntry::Intent(IntentEntry {
                text: "focal text".into(),
                verify: VerifyLevel::Method(VerifyMethod::Neural),
                status: Status::Unknown,
                text_hash: text_hash("focal text"),
                body_hash: sample_hash("focal body"),
                file: "src/x.rs".into(),
                site: "fn focal (line 1)".into(),
                covered_region: aristo_core::index::CoveredRegion::Function,
                binding: aristo_core::index::BindingState::Local,
                parent: None,
                last_critiqued_at_text_hash: None,
                last_critique_finding_count: None,
            }),
        );
        let mut pf = minimal_verified("focal text", "focal body");
        pf.verified.as_mut().unwrap().proof.steps[0].grounds = vec![Ground::Intent {
            id: sample_id("ground"),
            at_text_hash: Some(text_hash("STALE TEXT")),
            relation: GroundRelation::Instantiates,
            reason: None,
        }];
        let report = validate(&sample_id("focal"), &pf, &idx, Path::new("/"));
        assert!(report
            .failures
            .iter()
            .any(|f| f.detail.contains("differs from current")));
    }

    #[test]
    fn rejects_grounding_in_counterexample_status() {
        let idx = index_with_one_intent("ground", "current text", Status::Counterexample);
        let mut idx = idx;
        idx.entries.insert(
            sample_id("focal"),
            IndexEntry::Intent(IntentEntry {
                text: "focal text".into(),
                verify: VerifyLevel::Method(VerifyMethod::Neural),
                status: Status::Unknown,
                text_hash: text_hash("focal text"),
                body_hash: sample_hash("focal body"),
                file: "src/x.rs".into(),
                site: "fn focal (line 1)".into(),
                covered_region: aristo_core::index::CoveredRegion::Function,
                binding: aristo_core::index::BindingState::Local,
                parent: None,
                last_critiqued_at_text_hash: None,
                last_critique_finding_count: None,
            }),
        );
        let mut pf = minimal_verified("focal text", "focal body");
        pf.verified.as_mut().unwrap().proof.steps[0].grounds = vec![Ground::Intent {
            id: sample_id("ground"),
            at_text_hash: Some(text_hash("current text")),
            relation: GroundRelation::Instantiates,
            reason: None,
        }];
        let report = validate(&sample_id("focal"), &pf, &idx, Path::new("/"));
        assert!(report
            .failures
            .iter()
            .any(|f| f.detail.contains("status=counterexample")));
    }

    #[test]
    fn intent_ground_with_absent_hash_passes_when_id_resolves() {
        // Agent-written proofs omit at_text_hash; validator stamps it on
        // accept. The check_index_ground existence + status checks must
        // still apply, but the hash comparison is skipped.
        let idx = index_with_one_intent("ground", "current text", Status::Unknown);
        let mut idx = idx;
        idx.entries.insert(
            sample_id("focal"),
            IndexEntry::Intent(IntentEntry {
                text: "focal text".into(),
                verify: VerifyLevel::Method(VerifyMethod::Neural),
                status: Status::Unknown,
                text_hash: text_hash("focal text"),
                body_hash: sample_hash("focal body"),
                file: "src/x.rs".into(),
                site: "fn focal (line 1)".into(),
                covered_region: aristo_core::index::CoveredRegion::Function,
                binding: aristo_core::index::BindingState::Local,
                parent: None,
                last_critiqued_at_text_hash: None,
                last_critique_finding_count: None,
            }),
        );
        let mut pf = minimal_verified("focal text", "focal body");
        pf.verified.as_mut().unwrap().proof.steps[0].grounds = vec![Ground::Intent {
            id: sample_id("ground"),
            at_text_hash: None,
            relation: GroundRelation::Instantiates,
            reason: None,
        }];
        let report = validate(&sample_id("focal"), &pf, &idx, Path::new("/"));
        assert!(
            report.is_empty(),
            "absent at_text_hash should pass; got: {}",
            report.render()
        );
    }

    #[test]
    fn code_ground_with_absent_hash_passes_when_file_and_lines_resolve() {
        // Mirror of the intent-side test: an agent-written Code ground
        // without code_text_hash should pass as long as the file exists
        // and the line range is in bounds.
        let idx = index_with_one_intent("foo", "the property", Status::Unknown);
        let tmp = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(tmp.path().join("src")).unwrap();
        std::fs::write(tmp.path().join("src/x.rs"), "line1\nline2\nline3\n").unwrap();
        let mut pf = minimal_verified("the property", "body");
        pf.verified.as_mut().unwrap().proof.steps[0].grounds = vec![Ground::Code {
            file: "src/x.rs".into(),
            lines: "1-2".into(),
            code_text_hash: None,
            reason: "see header".into(),
        }];
        let report = validate(&sample_id("foo"), &pf, &idx, tmp.path());
        assert!(
            report.is_empty(),
            "absent code_text_hash should pass; got: {}",
            report.render()
        );
    }

    #[test]
    fn rejects_empty_grounds_step() {
        let idx = index_with_one_intent("foo", "the property", Status::Unknown);
        let mut pf = minimal_verified("the property", "body");
        pf.verified.as_mut().unwrap().proof.steps[0].grounds = vec![];
        let report = validate(&sample_id("foo"), &pf, &idx, Path::new("/"));
        assert!(report
            .failures
            .iter()
            .any(|f| f.detail.contains("zero grounds")));
    }

    #[test]
    fn rejects_prior_step_pointing_at_later_step() {
        let idx = index_with_one_intent("foo", "the property", Status::Unknown);
        let mut pf = minimal_verified("the property", "body");
        pf.verified.as_mut().unwrap().proof.steps = vec![
            ProofStep {
                path: "0".into(),
                claim: "root".into(),
                relation_to_parent: RelationKind::Decomposes,
                grounds: vec![Ground::PriorStep {
                    path: "1".into(),
                    reason: None,
                }],
                subgoal_paths: vec![],
                proposed_promotion: false,
            },
            ProofStep {
                path: "1".into(),
                claim: "later".into(),
                relation_to_parent: RelationKind::Decomposes,
                grounds: vec![Ground::Composition {
                    reason: "trivial".into(),
                }],
                subgoal_paths: vec![],
                proposed_promotion: false,
            },
        ];
        let report = validate(&sample_id("foo"), &pf, &idx, Path::new("/"));
        assert!(report
            .failures
            .iter()
            .any(|f| f.detail.contains("not earlier than")));
    }

    #[test]
    fn rejects_inconclusive_without_suggestions() {
        let idx = index_with_one_intent("foo", "the property", Status::Unknown);
        let mut pf = minimal_verified("the property", "body");
        pf.verified = None;
        pf.inconclusive = Some(aristo_core::proof::InconclusiveBody {
            partial_proof: None,
            gap: Gap {
                description: "stuck".into(),
                unfilled_path: "0.1".into(),
                suggested_annotations: vec![],
            },
        });
        pf.verdict.r#type = VerdictType::Inconclusive;
        let report = validate(&sample_id("foo"), &pf, &idx, Path::new("/"));
        assert!(report
            .failures
            .iter()
            .any(|f| f.detail.contains("MUST suggest at least one annotation")));
    }

    #[test]
    fn rejects_inconclusive_when_suggestion_present_in_index() {
        // GAP-7 fix: inconclusive verdicts go stale once any suggested
        // annotation is in the index (text-hash match). User adopted
        // suggestion or agent missed an existing entry — either way,
        // re-verify.
        let suggestion_text = "OS rename(2) is atomic on same-filesystem moves";
        // Index has BOTH the focal entry AND a sibling whose text matches
        // a suggestion in the inconclusive proof below.
        let mut idx = index_with_one_intent("focal", "the property holds", Status::Unknown);
        let zero = sample_hash("zero");
        idx.entries.insert(
            sample_id("os_rename_is_atomic"),
            IndexEntry::Assume(aristo_core::index::AssumeEntry {
                text: suggestion_text.to_string(),
                status: Status::Unknown,
                text_hash: text_hash(suggestion_text),
                body_hash: zero,
                file: "src/x.rs".into(),
                site: "fn atomic_write (line 1)".into(),
                covered_region: aristo_core::index::CoveredRegion::Function,
                linked: None,
                parent: None,
            }),
        );
        let mut pf = minimal_verified("the property holds", "body");
        pf.verified = None;
        pf.inconclusive = Some(aristo_core::proof::InconclusiveBody {
            partial_proof: None,
            gap: Gap {
                description: "atomicity guarantee not citable".into(),
                unfilled_path: "0".into(),
                suggested_annotations: vec![aristo_core::proof::SuggestedAnnotation {
                    kind: aristo_core::index::AnnotationKind::Assume,
                    suggested_text: suggestion_text.to_string(),
                    at_site: "fn atomic_write (line 1)".into(),
                    rationale: "needed to close the atomicity branch".into(),
                    would_close_path: None,
                }],
            },
        });
        pf.verdict.r#type = VerdictType::Inconclusive;
        let report = validate(&sample_id("focal"), &pf, &idx, Path::new("/"));
        assert!(
            report
                .failures
                .iter()
                .any(|f| f.detail.contains("matching annotation now exists")),
            "expected suggestion-in-index rejection; got: {}",
            report.render()
        );
    }

    #[test]
    fn accepts_inconclusive_when_no_suggestion_is_in_index() {
        // Inverse of the above: with no text-matching entry, the
        // inconclusive verdict stands.
        let idx = index_with_one_intent("focal", "the property holds", Status::Unknown);
        let mut pf = minimal_verified("the property holds", "body");
        pf.verified = None;
        pf.inconclusive = Some(aristo_core::proof::InconclusiveBody {
            partial_proof: None,
            gap: Gap {
                description: "stuck".into(),
                unfilled_path: "0".into(),
                suggested_annotations: vec![aristo_core::proof::SuggestedAnnotation {
                    kind: aristo_core::index::AnnotationKind::Assume,
                    suggested_text: "some unique text the index doesn't have".into(),
                    at_site: "fn x (line 1)".into(),
                    rationale: "would close gap".into(),
                    would_close_path: None,
                }],
            },
        });
        pf.verdict.r#type = VerdictType::Inconclusive;
        let report = validate(&sample_id("focal"), &pf, &idx, Path::new("/"));
        assert!(
            report.is_empty(),
            "no matching suggestion → inconclusive verdict stands; got: {}",
            report.render()
        );
    }

    #[test]
    fn collects_multiple_failures_not_short_circuit() {
        let idx = index_with_one_intent("foo", "the property", Status::Unknown);
        let mut pf = minimal_verified("WRONG TEXT", "body");
        pf.verdict.attempts = 99; // also over budget
        pf.verified.as_mut().unwrap().proof.steps[0].grounds = vec![]; // empty grounds
        let report = validate(&sample_id("foo"), &pf, &idx, Path::new("/"));
        // Expect at least: stale text hash + attempts over budget + empty grounds
        assert!(
            report.failures.len() >= 3,
            "expected ≥3 failures collected; got {} — render: {}",
            report.failures.len(),
            report.render()
        );
    }
}