truth-mirror 0.7.0

Truthfulness gate and adversarial reviewer harness for AI coding agents.
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
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
//! CLAIM parsing and deterministic pre-commit gate.

use std::fmt;

use thiserror::Error;

pub const DEFAULT_FAKE_MARKERS: &[&str] = &["mock-as-real", "TODO-as-done"];

/// Default evidence-pointer prefixes that make a CLAIM's evidence look real.
pub const DEFAULT_EVIDENCE_PATTERNS: &[&str] = &[
    "file:",
    "path:",
    "log:",
    "test:",
    "tests:",
    "screenshot:",
    "artifact:",
    "ci:",
    "bead:",
    "openspec:",
    "commit:",
];

/// Diff paths excluded from the fake-marker scan: documentation and specs mention
/// markers to *describe* them, not to fake behavior. Matched by prefix or suffix.
pub const DEFAULT_MARKER_IGNORE_PATHS: &[&str] = &[".md", "openspec/", "docs/"];

/// Resolved deterministic-gate policy (markers, evidence patterns, ignore paths).
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct GatePolicy {
    pub fake_markers: Vec<String>,
    pub evidence_patterns: Vec<String>,
    pub marker_ignore_paths: Vec<String>,
}

impl Default for GatePolicy {
    fn default() -> Self {
        Self {
            fake_markers: owned(DEFAULT_FAKE_MARKERS),
            evidence_patterns: owned(DEFAULT_EVIDENCE_PATTERNS),
            marker_ignore_paths: owned(DEFAULT_MARKER_IGNORE_PATHS),
        }
    }
}

fn owned(values: &[&str]) -> Vec<String> {
    values.iter().map(|value| (*value).to_owned()).collect()
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Claim {
    pub what: String,
    pub verification: String,
    pub evidence: Vec<EvidenceRef>,
}

impl Claim {
    pub fn new(
        what: impl Into<String>,
        verification: impl Into<String>,
        evidence: Vec<EvidenceRef>,
    ) -> Result<Self, ClaimError> {
        let claim = Self {
            what: normalize_field(what.into()),
            verification: normalize_field(verification.into()),
            evidence,
        };
        claim.validate()?;
        Ok(claim)
    }

    pub fn parse(input: &str) -> Result<Self, ClaimError> {
        Self::parse_with(input, DEFAULT_EVIDENCE_PATTERNS)
    }

    /// Parse a CLAIM, accepting the given evidence-pointer patterns (in addition
    /// to the built-in heuristics).
    pub fn parse_with<S: AsRef<str>>(input: &str, patterns: &[S]) -> Result<Self, ClaimError> {
        let line = input
            .lines()
            .map(str::trim)
            .find(|line| line.starts_with("CLAIM:"))
            .ok_or(ClaimError::MissingClaim)?;

        Self::parse_line_with(line, patterns)
    }

    pub fn parse_line(line: &str) -> Result<Self, ClaimError> {
        Self::parse_line_with(line, DEFAULT_EVIDENCE_PATTERNS)
    }

    pub fn parse_line_with<S: AsRef<str>>(line: &str, patterns: &[S]) -> Result<Self, ClaimError> {
        let body = line
            .trim()
            .strip_prefix("CLAIM:")
            .ok_or(ClaimError::MissingClaim)?;
        let fields = claim_fields(body, patterns);
        let claim_segment = fields.first().map_or(body, |field| &body[..field.start]);

        let mut verification = None;
        let mut evidence = Vec::new();
        let mut evidence_error = None;

        for field in fields {
            match field.kind {
                ClaimFieldKind::Verification => {
                    let field_value = normalize_field(field.value.to_owned());
                    if !field_value.is_empty() && verification.is_none() {
                        verification = Some(field_value);
                    }
                }
                ClaimFieldKind::Evidence => {
                    for item in field
                        .value
                        .split(',')
                        .map(str::trim)
                        .filter(|item| !item.is_empty())
                    {
                        match EvidenceRef::parse_with(item, patterns) {
                            Ok(parsed) => evidence.push(parsed),
                            Err(error) => {
                                if evidence_error.is_none() {
                                    evidence_error = Some(error);
                                }
                            }
                        }
                    }
                }
            }
        }

        let what = normalize_field(trim_claim_text(claim_segment).to_owned());
        if what.is_empty() {
            return Err(ClaimError::EmptyWhat);
        }
        if let Some(error) = evidence_error {
            return Err(error);
        }
        if evidence.is_empty() {
            return Err(ClaimError::MissingEvidence);
        }
        let verification = verification.ok_or(ClaimError::MissingVerification)?;
        if verification.is_empty() {
            return Err(ClaimError::MissingVerification);
        }

        Ok(Self {
            what,
            verification,
            evidence,
        })
    }

    pub fn to_line(&self) -> String {
        let evidence = self
            .evidence
            .iter()
            .map(EvidenceRef::as_str)
            .collect::<Vec<_>>()
            .join(", ");

        format!(
            "CLAIM: {} | verified: {} | evidence: {}",
            self.what, self.verification, evidence
        )
    }

    fn validate(&self) -> Result<(), ClaimError> {
        if self.what.is_empty() {
            return Err(ClaimError::EmptyWhat);
        }

        if self.verification.is_empty() {
            return Err(ClaimError::MissingVerification);
        }

        if self.evidence.is_empty() {
            return Err(ClaimError::MissingEvidence);
        }

        Ok(())
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct EvidenceRef(String);

impl EvidenceRef {
    pub fn parse(value: &str) -> Result<Self, ClaimError> {
        Self::parse_with(value, DEFAULT_EVIDENCE_PATTERNS)
    }

    pub fn parse_with<S: AsRef<str>>(value: &str, patterns: &[S]) -> Result<Self, ClaimError> {
        let value = normalize_field(value.to_owned());
        if value.is_empty() {
            return Err(ClaimError::MissingEvidence);
        }

        let normalized = value.to_ascii_lowercase();
        if matches!(
            normalized.as_str(),
            "none" | "n/a" | "na" | "todo" | "tbd" | "later" | "missing"
        ) || !looks_like_pointer(&value, patterns)
        {
            return Err(ClaimError::InvalidEvidence { value });
        }

        Ok(Self(value))
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for EvidenceRef {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(formatter)
    }
}

#[derive(Clone, Debug, Eq, Error, PartialEq)]
pub enum ClaimError {
    #[error("missing CLAIM: line")]
    MissingClaim,
    #[error("CLAIM: what field is empty")]
    EmptyWhat,
    #[error("CLAIM: missing verified field")]
    MissingVerification,
    #[error("CLAIM: missing evidence pointer")]
    MissingEvidence,
    #[error("CLAIM: invalid evidence pointer {value:?}")]
    InvalidEvidence { value: String },
}

#[derive(Clone, Debug, Eq, Error, PartialEq)]
pub enum GateFailure {
    #[error("missing CLAIM: line")]
    MissingClaim,
    #[error(
        "completion wording lacks evidence pointer for word {word:?}; example: CLAIM: change behavior | verified: cargo test | evidence: tests:cargo-test"
    )]
    CompletionWithoutEvidence { word: String },
    #[error("{0}")]
    InvalidClaim(#[from] ClaimError),
    #[error("fake marker {marker:?} found at diff line {line}")]
    FakeMarker { marker: String, line: usize },
}

pub fn evaluate_commit_message(
    commit_message: &str,
    claim_file: Option<&str>,
    diff: Option<&str>,
    policy: &GatePolicy,
) -> Result<Claim, GateFailure> {
    let has_claim_line = commit_message
        .lines()
        .any(|line| line.trim().starts_with("CLAIM:"));

    let claim_source = if has_claim_line {
        commit_message
    } else {
        // No CLAIM line in the message.  Before bailing with MissingClaim, check
        // whether body prose contains a completion word — if so, surface a more
        // actionable CompletionWithoutEvidence hint.
        match claim_file {
            Some(source) => source,
            None => {
                return Err(match completion_word_outside_claim(commit_message) {
                    Some(word) => GateFailure::CompletionWithoutEvidence {
                        word: word.to_owned(),
                    },
                    None => GateFailure::MissingClaim,
                });
            }
        }
    };

    // When a CLAIM line is structurally present, surface the underlying
    // ClaimError directly — naming the exact problem (missing evidence, invalid
    // pointer value, etc.) so the author can fix it without guessing.
    //
    // CompletionWithoutEvidence is reserved for the no-claim-line path above,
    // where body prose with a completion word signals a forgotten CLAIM block.
    let claim = Claim::parse_with(claim_source, &policy.evidence_patterns)
        .map_err(GateFailure::InvalidClaim)?;

    if let Some(diff) = diff
        && let Some(marker) =
            first_fake_marker(diff, &policy.fake_markers, &policy.marker_ignore_paths)
    {
        return Err(marker);
    }

    Ok(claim)
}

/// Whether a new-side diff path is excluded from the fake-marker scan.
fn path_is_ignored<S: AsRef<str>>(path: &str, ignore_paths: &[S]) -> bool {
    ignore_paths.iter().any(|ignore| {
        let ignore = ignore.as_ref();
        !ignore.is_empty() && (path.starts_with(ignore) || path.ends_with(ignore))
    })
}

pub fn first_fake_marker<S: AsRef<str>>(
    diff: &str,
    fake_markers: &[String],
    ignore_paths: &[S],
) -> Option<GateFailure> {
    let markers = normalized_markers(fake_markers);
    let mut ignored_file = false;
    for (index, line) in diff.lines().enumerate() {
        // Track the current file from its `+++ b/<path>` header so documentation
        // and spec files (which mention markers to describe them) are skipped.
        if let Some(rest) = line.strip_prefix("+++ ") {
            let path = rest.strip_prefix("b/").unwrap_or(rest);
            ignored_file = path_is_ignored(path, ignore_paths);
            continue;
        }

        // Only lines the commit actually INTRODUCES count. Context and removed
        // lines are not this commit's doing — flagging them would trip on any
        // change made near an unrelated pre-existing marker (including a source
        // file that legitimately *defines* the marker token).
        let Some(added) = line.strip_prefix('+') else {
            continue;
        };
        if added.starts_with("++") || ignored_file {
            continue;
        }

        let line_lower = added.to_ascii_lowercase();
        if let Some(marker) = markers
            .iter()
            .find(|marker| line_lower.contains(marker.normalized.as_str()))
        {
            return Some(GateFailure::FakeMarker {
                marker: marker.original.clone(),
                line: index + 1,
            });
        }
    }

    None
}

struct Marker {
    original: String,
    normalized: String,
}

fn normalized_markers(fake_markers: &[String]) -> Vec<Marker> {
    let source: Vec<String> = if fake_markers.is_empty() {
        DEFAULT_FAKE_MARKERS
            .iter()
            .map(|marker| (*marker).to_owned())
            .collect()
    } else {
        fake_markers.to_vec()
    };

    source
        .into_iter()
        .filter(|marker| !marker.trim().is_empty())
        .map(|marker| Marker {
            normalized: marker.trim().to_ascii_lowercase(),
            original: marker.trim().to_owned(),
        })
        .collect()
}

/// Scan only lines that are NOT the CLAIM line itself for completion words.
///
/// This prevents body prose ("the fixed seed order", "verified assumptions")
/// from triggering a gate failure when a structurally valid CLAIM is present.
/// This function is used only when no CLAIM line was found, so all lines are
/// scanned as a fallback signal that the author forgot to include evidence.
fn completion_word_outside_claim(input: &str) -> Option<&'static str> {
    const WORDS: &[&str] = &[
        "done",
        "complete",
        "completed",
        "verified",
        "fixed",
        "passing",
    ];

    input
        .lines()
        .filter(|line| !line.trim().starts_with("CLAIM:"))
        .flat_map(|line| line.split(|character: char| !character.is_ascii_alphanumeric()))
        .find_map(|word| {
            let normalized = word.to_ascii_lowercase();
            WORDS
                .iter()
                .copied()
                .find(|candidate| *candidate == normalized)
        })
}

fn looks_like_pointer<S: AsRef<str>>(value: &str, patterns: &[S]) -> bool {
    let lower = value.to_ascii_lowercase();
    lower.contains("://")
        || patterns
            .iter()
            .any(|prefix| lower.starts_with(&prefix.as_ref().to_ascii_lowercase()))
        || value.contains('/')
        || value.contains('.')
}

fn normalize_field(value: String) -> String {
    value.split_whitespace().collect::<Vec<_>>().join(" ")
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum ClaimFieldKind {
    Verification,
    Evidence,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
struct ClaimField<'a> {
    kind: ClaimFieldKind,
    start: usize,
    value: &'a str,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
struct FieldTag {
    kind: ClaimFieldKind,
    start: usize,
    value_start: usize,
}

fn claim_fields<'a, S: AsRef<str>>(input: &'a str, patterns: &[S]) -> Vec<ClaimField<'a>> {
    if input.contains('|') {
        delimited_claim_fields(input, patterns)
    } else {
        loose_claim_fields(input, patterns)
    }
}

fn delimited_claim_fields<'a, S: AsRef<str>>(
    input: &'a str,
    patterns: &[S],
) -> Vec<ClaimField<'a>> {
    let mut fields = Vec::new();
    let mut segments = Vec::new();
    let mut segment_start = 0;
    let mut seen_delimiter = false;
    // The text before the first `|` is the summary (`what`); only later
    // pipe-delimited segments are parsed for named fields.
    for (index, character) in input.char_indices() {
        if character != '|' {
            continue;
        }
        if seen_delimiter {
            segments.push((segment_start, index));
        }
        seen_delimiter = true;
        segment_start = index + character.len_utf8();
    }
    if seen_delimiter {
        segments.push((segment_start, input.len()));
    }
    let segment_has_evidence = segments
        .iter()
        .copied()
        .map(|(start, end)| segment_starts_with_field(input, start, end, ClaimFieldKind::Evidence))
        .collect::<Vec<_>>();
    let any_segment_has_evidence = segment_has_evidence
        .iter()
        .any(|has_evidence| *has_evidence);

    for (segment_index, (start, end)) in segments.iter().copied().enumerate() {
        let other_segment_has_evidence =
            any_segment_has_evidence && !segment_has_evidence[segment_index];
        fields.extend(segment_claim_fields(
            input,
            start,
            end,
            other_segment_has_evidence,
            patterns,
        ));
    }
    fields
}

fn segment_claim_fields<'a, S: AsRef<str>>(
    input: &'a str,
    segment_start: usize,
    segment_end: usize,
    other_segment_has_evidence: bool,
    patterns: &[S],
) -> Vec<ClaimField<'a>> {
    let Some(segment) = input.get(segment_start..segment_end) else {
        return Vec::new();
    };
    if other_segment_has_evidence
        && let Some(tag) = segment_starting_field_tag(segment, ClaimFieldKind::Verification)
    {
        return vec![ClaimField {
            kind: tag.kind,
            start: segment_start + tag.start,
            value: &segment[tag.value_start..],
        }];
    }
    loose_claim_fields(segment, patterns)
        .into_iter()
        .map(|field| ClaimField {
            kind: field.kind,
            start: segment_start + field.start,
            value: field.value,
        })
        .collect()
}

fn segment_starts_with_field(
    input: &str,
    segment_start: usize,
    segment_end: usize,
    kind: ClaimFieldKind,
) -> bool {
    input
        .get(segment_start..segment_end)
        .and_then(|segment| segment_starting_field_tag(segment, kind))
        .is_some()
}

fn segment_starting_field_tag(segment: &str, kind: ClaimFieldKind) -> Option<FieldTag> {
    let trimmed_start = segment.len() - segment.trim_start().len();
    field_tags(segment)
        .into_iter()
        .find(|tag| tag.kind == kind && tag.start == trimmed_start)
}

fn loose_claim_fields<'a, S: AsRef<str>>(input: &'a str, patterns: &[S]) -> Vec<ClaimField<'a>> {
    let tags = field_tags(input);
    // Loose CLAIMs may mention field-like words in the summary/prose. Prefer the
    // latest verification/evidence pair whose evidence looks pointer-like, then
    // anchor on the first tag's kind, then fall back to adjacent mixed tags.
    let mut fields = complete_field_pair(input, &tags, patterns).unwrap_or_else(|| {
        [
            tags.iter()
                .copied()
                .rfind(|tag| tag.kind == ClaimFieldKind::Verification),
            tags.iter()
                .copied()
                .rfind(|tag| tag.kind == ClaimFieldKind::Evidence),
        ]
        .into_iter()
        .flatten()
        .collect::<Vec<_>>()
    });
    fields.sort_by_key(|tag| tag.start);

    fields
        .iter()
        .enumerate()
        .map(|(index, tag)| {
            let end = fields.get(index + 1).map_or(input.len(), |next| next.start);
            ClaimField {
                kind: tag.kind,
                start: tag.start,
                value: trim_field_value(&input[tag.value_start..end]),
            }
        })
        .collect()
}

fn complete_field_pair<S: AsRef<str>>(
    input: &str,
    tags: &[FieldTag],
    patterns: &[S],
) -> Option<Vec<FieldTag>> {
    if let Some(pair) = later_complete_verification_evidence_pair(input, tags, patterns) {
        return Some(pair);
    }

    if let Some(first) = tags.first().copied() {
        match first.kind {
            ClaimFieldKind::Verification => {
                if let Some(evidence) = tags
                    .iter()
                    .copied()
                    .rfind(|tag| tag.kind == ClaimFieldKind::Evidence)
                {
                    return Some(vec![first, evidence]);
                }
            }
            ClaimFieldKind::Evidence => {
                if let Some(verification) = tags
                    .iter()
                    .copied()
                    .find(|tag| tag.kind == ClaimFieldKind::Verification)
                {
                    if !evidence_tag_value_looks_like_pointer(
                        input,
                        first,
                        verification.start,
                        patterns,
                    ) && let Some(evidence) = tags.iter().copied().rfind(|tag| {
                        tag.kind == ClaimFieldKind::Evidence && tag.start > verification.start
                    }) {
                        return Some(vec![verification, evidence]);
                    }
                    return Some(vec![first, verification]);
                }
            }
        }
    }

    tags.windows(2).find_map(|window| {
        let first = window[0];
        let second = window[1];
        (first.kind != second.kind).then(|| vec![first, second])
    })
}

fn later_complete_verification_evidence_pair<S: AsRef<str>>(
    input: &str,
    tags: &[FieldTag],
    patterns: &[S],
) -> Option<Vec<FieldTag>> {
    tags.windows(2)
        .enumerate()
        .rev()
        .find_map(|(index, window)| {
            let verification = window[0];
            let evidence = window[1];
            let evidence_end = tags.get(index + 2).map_or(input.len(), |tag| tag.start);
            (verification.kind == ClaimFieldKind::Verification
                && evidence.kind == ClaimFieldKind::Evidence
                && evidence_tag_value_looks_like_pointer(input, evidence, evidence_end, patterns))
            .then(|| vec![verification, evidence])
        })
}

fn evidence_tag_value_looks_like_pointer<S: AsRef<str>>(
    input: &str,
    tag: FieldTag,
    end: usize,
    patterns: &[S],
) -> bool {
    input
        .get(tag.value_start..end)
        .map(trim_field_value)
        .is_some_and(|value| looks_like_pointer(value, patterns))
}

fn field_tags(input: &str) -> Vec<FieldTag> {
    const FIELD_NAMES_WITH_HOW: &[(&str, ClaimFieldKind)] = &[
        ("evidence-pointer", ClaimFieldKind::Evidence),
        ("verification", ClaimFieldKind::Verification),
        ("verified", ClaimFieldKind::Verification),
        ("evidence", ClaimFieldKind::Evidence),
        ("how", ClaimFieldKind::Verification),
    ];

    collect_field_tags(input, FIELD_NAMES_WITH_HOW)
}

fn collect_field_tags(input: &str, field_names: &[(&str, ClaimFieldKind)]) -> Vec<FieldTag> {
    let mut tags = Vec::new();
    for (index, _) in input.char_indices() {
        if !field_boundary_before(input, index) {
            continue;
        }
        if let Some(tag) = field_tag_at(input, index, field_names) {
            tags.push(tag);
        }
    }
    tags
}

fn field_tag_at(
    input: &str,
    index: usize,
    field_names: &[(&str, ClaimFieldKind)],
) -> Option<FieldTag> {
    for (name, kind) in field_names {
        let after_name = index + name.len();
        if input
            .get(index..after_name)
            .is_some_and(|candidate| candidate.eq_ignore_ascii_case(name))
            && input
                .get(after_name..)
                .is_some_and(|remaining| remaining.starts_with(':'))
        {
            return Some(FieldTag {
                kind: *kind,
                start: index,
                value_start: after_name + 1,
            });
        }
    }
    None
}

fn field_boundary_before(input: &str, index: usize) -> bool {
    index == 0
        || input[..index]
            .chars()
            .next_back()
            .is_some_and(|character| character.is_whitespace() || matches!(character, '|' | ';'))
}

fn trim_field_value(value: &str) -> &str {
    value
        .trim_matches(|character: char| character.is_whitespace() || matches!(character, '|' | ';'))
}

fn trim_claim_text(value: &str) -> &str {
    value.trim_matches(|character: char| {
        character.is_whitespace() || matches!(character, '|' | ';' | ',')
    })
}

#[cfg(test)]
mod tests {
    use proptest::prelude::*;

    use super::{
        Claim, ClaimError, EvidenceRef, GateFailure, GatePolicy, evaluate_commit_message,
        first_fake_marker,
    };

    /// No ignore paths — every added line is scanned.
    const NO_IGNORE: &[&str] = &[];

    #[test]
    fn parses_claim_line_with_evidence() {
        let claim = Claim::parse(
            "feat: thing\n\nCLAIM: add parser | verified: cargo test | evidence: tests:cargo-test",
        )
        .unwrap();

        assert_eq!(claim.what, "add parser");
        assert_eq!(claim.verification, "cargo test");
        assert_eq!(claim.evidence[0].as_str(), "tests:cargo-test");
    }

    #[test]
    fn parses_named_claim_fields_without_pipe_delimiters() {
        let claim = Claim::parse(
            "feat: thing\n\nCLAIM: add parser verified: cargo test evidence: tests:cargo-test",
        )
        .unwrap();

        assert_eq!(claim.what, "add parser");
        assert_eq!(claim.verification, "cargo test");
        assert_eq!(claim.evidence[0].as_str(), "tests:cargo-test");
    }

    #[test]
    fn parses_how_as_verification_alias() {
        let claim = Claim::parse(
            "feat: thing\n\nCLAIM: add parser | how: cargo test | evidence: tests:claim",
        )
        .unwrap();

        assert_eq!(claim.what, "add parser");
        assert_eq!(claim.verification, "cargo test");
        assert_eq!(claim.evidence[0].as_str(), "tests:claim");
    }

    #[test]
    fn loose_claim_parses_how_as_verification_alias() {
        let claim =
            Claim::parse("feat: thing\n\nCLAIM: add parser how: cargo test evidence: tests:claim")
                .unwrap();

        assert_eq!(claim.what, "add parser");
        assert_eq!(claim.verification, "cargo test");
        assert_eq!(claim.evidence[0].as_str(), "tests:claim");
    }

    #[test]
    fn loose_claim_accepts_evidence_before_verification() {
        let claim = Claim::parse(
            "feat: thing\n\nCLAIM: add parser evidence: tests:claim verified: cargo test",
        )
        .unwrap();

        assert_eq!(claim.what, "add parser");
        assert_eq!(claim.verification, "cargo test");
        assert_eq!(claim.evidence[0].as_str(), "tests:claim");
    }

    #[test]
    fn comma_separated_evidence_ignores_blank_items() {
        let claim = Claim::parse(
            "feat: thing\n\nCLAIM: add parser | verified: cargo test | evidence: tests:unit, , tests:integration,",
        )
        .unwrap();

        assert_eq!(claim.evidence.len(), 2);
        assert_eq!(claim.evidence[0].as_str(), "tests:unit");
        assert_eq!(claim.evidence[1].as_str(), "tests:integration");
    }

    #[test]
    fn loose_claim_preserves_field_like_summary_text() {
        let claim = Claim::parse(
            "feat: thing\n\nCLAIM: add evidence: parser verified: cargo test evidence: tests:claim",
        )
        .unwrap();

        assert_eq!(claim.what, "add evidence: parser");
        assert_eq!(claim.verification, "cargo test");
        assert_eq!(claim.evidence[0].as_str(), "tests:claim");
    }

    #[test]
    fn loose_claim_preserves_verified_label_in_summary_text() {
        let claim = Claim::parse(
            "feat: thing\n\nCLAIM: add verified: docs verified: cargo test evidence: tests:claim",
        )
        .unwrap();

        assert_eq!(claim.what, "add verified: docs");
        assert_eq!(claim.verification, "cargo test");
        assert_eq!(claim.evidence[0].as_str(), "tests:claim");
    }

    #[test]
    fn loose_claim_uses_custom_evidence_patterns_for_summary_disambiguation() {
        let claim = Claim::parse_with(
            "feat: thing\n\nCLAIM: add verified: docs verified: cargo test evidence: jira:PROJ-42",
            &["jira:"],
        )
        .unwrap();

        assert_eq!(claim.what, "add verified: docs");
        assert_eq!(claim.verification, "cargo test");
        assert_eq!(claim.evidence[0].as_str(), "jira:PROJ-42");
    }

    #[test]
    fn loose_claim_parses_how_after_field_like_summary_text() {
        let claim = Claim::parse(
            "feat: thing\n\nCLAIM: add verified: docs how: cargo test evidence: tests:x",
        )
        .unwrap();

        assert_eq!(claim.what, "add verified: docs");
        assert_eq!(claim.verification, "cargo test");
        assert_eq!(claim.evidence[0].as_str(), "tests:x");
    }

    #[test]
    fn pipe_delimited_claim_accepts_mixed_named_fields_in_segment() {
        let claim = Claim::parse(
            "feat: thing\n\nCLAIM: add parser | verified: cargo test evidence: tests:claim",
        )
        .unwrap();

        assert_eq!(claim.what, "add parser");
        assert_eq!(claim.verification, "cargo test");
        assert_eq!(claim.evidence[0].as_str(), "tests:claim");
    }

    #[test]
    fn loose_claim_keeps_evidence_when_verification_mentions_evidence() {
        let claim = Claim::parse(
            "feat: thing\n\nCLAIM: add parser evidence: tests:claim verified: reviewed evidence: output",
        )
        .unwrap();

        assert_eq!(claim.what, "add parser");
        assert_eq!(claim.verification, "reviewed evidence: output");
        assert_eq!(claim.evidence[0].as_str(), "tests:claim");
    }

    #[test]
    fn pipe_delimited_claim_keeps_later_evidence_when_verification_mentions_evidence() {
        let claim = Claim::parse(
            "feat: thing\n\nCLAIM: add parser | verified: reviewed evidence: output | evidence: tests:claim",
        )
        .unwrap();

        assert_eq!(claim.what, "add parser");
        assert_eq!(claim.verification, "reviewed evidence: output");
        assert_eq!(claim.evidence[0].as_str(), "tests:claim");
    }

    #[test]
    fn loose_claim_keeps_later_evidence_when_verification_mentions_evidence() {
        let claim = Claim::parse(
            "feat: thing\n\nCLAIM: add parser verified: reviewed evidence: output evidence: tests:claim",
        )
        .unwrap();

        assert_eq!(claim.what, "add parser");
        assert_eq!(claim.verification, "reviewed evidence: output");
        assert_eq!(claim.evidence[0].as_str(), "tests:claim");
    }

    #[test]
    fn pipe_delimited_claim_keeps_earlier_evidence_when_verification_mentions_evidence() {
        let claim = Claim::parse(
            "feat: thing\n\nCLAIM: add parser | evidence: tests:claim | verified: reviewed evidence: output",
        )
        .unwrap();

        assert_eq!(claim.what, "add parser");
        assert_eq!(claim.verification, "reviewed evidence: output");
        assert_eq!(claim.evidence[0].as_str(), "tests:claim");
    }

    #[test]
    fn duplicate_verification_aliases_ignore_empty_duplicate_in_any_order() {
        let messages = [
            "feat: thing\n\nCLAIM: fix parser | verified: cargo test | verification: | evidence: tests:x",
            "feat: thing\n\nCLAIM: fix parser | verification: | verified: cargo test | evidence: tests:x",
        ];

        for message in messages {
            let claim = Claim::parse(message).unwrap();
            assert_eq!(claim.verification, "cargo test");
            assert_eq!(claim.evidence[0].as_str(), "tests:x");
        }
    }

    #[test]
    fn duplicate_empty_verification_aliases_still_reject_as_missing() {
        let error = Claim::parse(
            "feat: thing\n\nCLAIM: fix parser | verification: | verified: | evidence: tests:x",
        )
        .unwrap_err();

        assert_eq!(error, ClaimError::MissingVerification);
    }

    #[test]
    fn pipe_delimited_claim_keeps_field_like_words_in_summary() {
        let claim = Claim::parse(
            "feat: thing\n\nCLAIM: add evidence: parser | verified: cargo test | evidence: tests:cargo-test",
        )
        .unwrap();

        assert_eq!(claim.what, "add evidence: parser");
        assert_eq!(claim.verification, "cargo test");
        assert_eq!(claim.evidence[0].as_str(), "tests:cargo-test");
    }

    #[test]
    fn pipe_delimited_claim_treats_first_segment_as_summary() {
        let claim = Claim::parse(
            "feat: thing\n\nCLAIM: evidence: parser | verified: cargo test | evidence: tests:cargo-test",
        )
        .unwrap();

        assert_eq!(claim.what, "evidence: parser");
        assert_eq!(claim.verification, "cargo test");
        assert_eq!(claim.evidence[0].as_str(), "tests:cargo-test");
    }

    #[test]
    fn pipe_delimited_claim_preserves_semicolon_in_evidence_value() {
        let claim = Claim::parse(
            "feat: thing\n\nCLAIM: add parser | verified: cargo test | evidence: tests:unit; tests:integration",
        )
        .unwrap();

        assert_eq!(claim.what, "add parser");
        assert_eq!(claim.evidence[0].as_str(), "tests:unit; tests:integration");
    }

    #[test]
    fn pipe_delimited_claim_keeps_field_like_words_in_verification() {
        let claim = Claim::parse(
            "feat: thing\n\nCLAIM: add parser | verified: describe how: it works | evidence: tests:cargo-test",
        )
        .unwrap();

        assert_eq!(claim.what, "add parser");
        assert_eq!(claim.verification, "describe how: it works");
        assert_eq!(claim.evidence[0].as_str(), "tests:cargo-test");
    }

    #[test]
    fn rejects_missing_claim() {
        let error = Claim::parse("feat: thing").unwrap_err();

        assert_eq!(error, ClaimError::MissingClaim);
    }

    #[test]
    fn rejects_missing_evidence() {
        let error = Claim::parse("CLAIM: complete parser | verified: cargo test").unwrap_err();

        assert_eq!(error, ClaimError::MissingEvidence);
    }

    #[test]
    fn reports_completion_word_without_evidence_when_no_claim_line() {
        // No CLAIM line at all + body prose with completion word → CompletionWithoutEvidence.
        let error = evaluate_commit_message(
            "feat: complete the parser",
            None,
            None,
            &GatePolicy::default(),
        )
        .unwrap_err();

        assert_eq!(
            error,
            GateFailure::CompletionWithoutEvidence {
                word: "complete".to_owned()
            }
        );
    }

    #[test]
    fn claim_line_with_missing_evidence_reports_invalid_claim_not_completion_word() {
        // A CLAIM line IS present but evidence is missing → surface the underlying
        // ClaimError so the author knows *what* failed, not a misleading completion-word hint.
        let error = evaluate_commit_message(
            "feat: parser\n\nCLAIM: complete parser | verified: cargo test",
            None,
            None,
            &GatePolicy::default(),
        )
        .unwrap_err();

        assert_eq!(
            error,
            GateFailure::InvalidClaim(ClaimError::MissingEvidence)
        );
    }

    #[test]
    fn claim_line_with_non_pointer_evidence_names_offending_value() {
        // Finding 2 regression: InvalidEvidence carries the bad value; the error must
        // name it verbatim so the author can fix it without guessing.
        let error = evaluate_commit_message(
            "feat: parser\n\nCLAIM: add things | verified: manual | evidence: not-a-pointer",
            None,
            None,
            &GatePolicy::default(),
        )
        .unwrap_err();

        assert_eq!(
            error,
            GateFailure::InvalidClaim(ClaimError::InvalidEvidence {
                value: "not-a-pointer".to_owned(),
            })
        );
    }

    #[test]
    fn equivalent_completion_claim_shapes_get_stable_evidence_failure() {
        // These all have a CLAIM line present but evidence missing/invalid.
        // After Finding 2 fix they report InvalidClaim, not CompletionWithoutEvidence.
        let messages = [
            "feat: parser\n\nCLAIM: complete parser | verified: cargo test",
            "feat: parser\n\nCLAIM: complete parser verified: cargo test",
        ];

        for message in messages {
            let error =
                evaluate_commit_message(message, None, None, &GatePolicy::default()).unwrap_err();
            assert_eq!(
                error,
                GateFailure::InvalidClaim(ClaimError::MissingEvidence),
                "unexpected error for message: {message:?}"
            );
        }
    }

    #[test]
    fn equivalent_invalid_evidence_shapes_get_stable_evidence_failure() {
        let messages = [
            "feat: parser\n\nCLAIM: complete parser | evidence: missing | verified: cargo test",
            "feat: parser\n\nCLAIM: complete parser verified: cargo test evidence: missing",
            "feat: parser\n\nCLAIM: complete parser | evidence: missing",
        ];

        for message in messages {
            let error =
                evaluate_commit_message(message, None, None, &GatePolicy::default()).unwrap_err();
            assert_eq!(
                error,
                GateFailure::InvalidClaim(ClaimError::InvalidEvidence {
                    value: "missing".to_owned(),
                })
            );
        }
    }

    #[test]
    fn subject_completion_word_does_not_mask_claim_evidence_error() {
        // Finding 2: even when the subject contains a completion word ("fixed"),
        // a structurally-present CLAIM line means the underlying ClaimError is
        // surfaced directly.  CompletionWithoutEvidence is only for the no-CLAIM case.
        let error = evaluate_commit_message(
            "fix: fixed seed order\n\nCLAIM: add parser | verified: cargo test",
            None,
            None,
            &GatePolicy::default(),
        )
        .unwrap_err();

        assert_eq!(
            error,
            GateFailure::InvalidClaim(ClaimError::MissingEvidence)
        );
    }

    #[test]
    fn later_claim_completion_word_does_not_mask_first_claim_evidence_error() {
        let error = evaluate_commit_message(
            "feat: parser\n\nCLAIM: add parser | verified: cargo test\nCLAIM: complete parser | verified: cargo test | evidence: tests:later",
            None,
            None,
            &GatePolicy::default(),
        )
        .unwrap_err();

        assert_eq!(
            error,
            GateFailure::InvalidClaim(ClaimError::MissingEvidence)
        );
    }

    #[test]
    fn body_after_first_claim_does_not_mask_first_claim_evidence_error() {
        let error = evaluate_commit_message(
            "feat: parser\n\nCLAIM: add parser | verified: cargo test\n\nverified later in prose",
            None,
            None,
            &GatePolicy::default(),
        )
        .unwrap_err();

        assert_eq!(
            error,
            GateFailure::InvalidClaim(ClaimError::MissingEvidence)
        );
    }

    #[test]
    fn valid_claim_with_completion_words_in_body_prose_passes() {
        let claim = evaluate_commit_message(
            "fix: parser\n\nThis body says the parser is fixed and verified.\n\nCLAIM: add parser | verified: cargo test | evidence: tests:x",
            None,
            None,
            &GatePolicy::default(),
        )
        .unwrap();

        assert_eq!(claim.what, "add parser");
        assert_eq!(claim.verification, "cargo test");
        assert_eq!(claim.evidence[0].as_str(), "tests:x");
    }

    #[test]
    fn invalid_evidence_is_not_masked_by_verified_field_label() {
        let error = evaluate_commit_message(
            "fix: seed order\n\nCLAIM: add parser | verified: cargo test | evidence: Depot job 393s6c1ff6 failure log",
            None,
            None,
            &GatePolicy::default(),
        )
        .unwrap_err();

        assert_eq!(
            error,
            GateFailure::InvalidClaim(ClaimError::InvalidEvidence {
                value: "Depot job 393s6c1ff6 failure log".to_owned(),
            })
        );
    }

    #[test]
    fn accepts_claim_file_fallback() {
        let claim = evaluate_commit_message(
            "feat: parser",
            Some("CLAIM: add parser | verified: cargo test | evidence: tests:cargo-test"),
            None,
            &GatePolicy::default(),
        )
        .unwrap();

        assert_eq!(claim.what, "add parser");
    }

    #[test]
    fn custom_evidence_pattern_is_accepted() {
        let policy = GatePolicy {
            evidence_patterns: vec!["jira:".to_owned()],
            ..GatePolicy::default()
        };
        let claim = evaluate_commit_message(
            "chore: thing\n\nCLAIM: do thing | verified: manual | evidence: jira:PROJ-42",
            None,
            None,
            &policy,
        )
        .unwrap();

        assert_eq!(claim.evidence[0].as_str(), "jira:PROJ-42");
    }

    #[test]
    fn body_prose_with_completion_word_does_not_reject_valid_claim() {
        // Finding 3 regression: body text "the fixed seed order" must not trigger a
        // gate failure when a fully valid CLAIM line with pointer evidence is present.
        let claim = evaluate_commit_message(
            "fix: seed order\n\nThis commit fixed the seed order so tests run deterministically.\n\nCLAIM: fix seed order | verified: cargo test | evidence: tests:cargo-test",
            None,
            None,
            &GatePolicy::default(),
        )
        .unwrap();

        assert_eq!(claim.what, "fix seed order");
    }

    #[test]
    fn marker_in_ignored_doc_path_is_not_flagged() {
        // Same added marker line, but under a doc path in the diff → skipped.
        let marker = ["mock", "as", "real"].join("-");
        let diff = format!("diff --git a/docs/x.md b/docs/x.md\n+++ b/docs/x.md\n+ {marker}");

        let policy = GatePolicy::default();
        assert!(
            first_fake_marker(&diff, &policy.fake_markers, &policy.marker_ignore_paths).is_none()
        );

        // Under a code path, the same line IS flagged.
        let code_diff = format!("diff --git a/src/x.rs b/src/x.rs\n+++ b/src/x.rs\n+ {marker}");
        assert!(
            first_fake_marker(
                &code_diff,
                &policy.fake_markers,
                &policy.marker_ignore_paths
            )
            .is_some()
        );
    }

    #[test]
    fn finds_default_fake_marker_with_location() {
        let done = ["TODO", "as", "done"].join("-");
        let diff = format!("diff --git a/x b/x\n+ {done}");
        let error = first_fake_marker(&diff, &[], NO_IGNORE).unwrap();

        assert_eq!(
            error,
            GateFailure::FakeMarker {
                marker: "TODO-as-done".to_owned(),
                line: 2
            }
        );
    }

    #[test]
    fn context_and_removed_lines_do_not_trip_fake_marker() {
        // Built at runtime so the literal marker token never appears in this file
        // (truth-mirror's own gate would otherwise flag this very line).
        let marker = ["mock", "as", "real"].join("-");
        // A context line (space prefix) and a removed line (-) that merely mention
        // the marker must not be flagged; only added (+) content counts.
        let diff = format!(
            "diff --git a/x b/x\n const MARKERS = [\"{marker}\"];\n- old_line_with {marker}\n+ let honest = compute();"
        );

        assert!(first_fake_marker(&diff, &[], NO_IGNORE).is_none());
    }

    #[test]
    fn added_line_with_marker_is_flagged() {
        let marker = ["mock", "as", "real"].join("-");
        let diff = format!("diff --git a/x b/x\n+ {marker} here");
        let error = first_fake_marker(&diff, &[], NO_IGNORE).unwrap();

        assert!(matches!(error, GateFailure::FakeMarker { .. }));
    }

    #[test]
    fn configured_fake_marker_overrides_defaults() {
        let markers = vec!["pretend-pass".to_owned()];
        let error = first_fake_marker("+ pretend-pass", &markers, NO_IGNORE).unwrap();

        assert_eq!(
            error,
            GateFailure::FakeMarker {
                marker: "pretend-pass".to_owned(),
                line: 1
            }
        );
    }

    proptest! {
        #[test]
        fn claim_roundtrip_preserves_semantic_fields(
            what in "[A-Za-z0-9][A-Za-z0-9 _./:-]{0,48}",
            verification in "[A-Za-z0-9][A-Za-z0-9 _./:-]{0,48}",
            evidence_suffix in "[a-z0-9][a-z0-9_-]{0,24}",
        ) {
            let evidence = EvidenceRef::parse(&format!("tests:{evidence_suffix}")).unwrap();
            let claim = Claim::new(what, verification, vec![evidence]).unwrap();

            let parsed = Claim::parse(&claim.to_line()).unwrap();

            prop_assert_eq!(parsed, claim);
        }
    }
}