agent-file-tools 0.50.0

Agent File Tools — tree-sitter powered code analysis for AI 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
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
//! Parsing and Phase-1 safety checks for the hashline patch language.
//!
//! This module deliberately separates a patch's *requested* coordinates from
//! execution. Every address is resolved against the retained snapshot before a
//! caller plans a mutation, and exact verification compares that snapshot with
//! one caller-owned baseline. That keeps later operations in the same patch
//! from silently renumbering the coordinates of earlier input.

use std::collections::BTreeMap;
use std::fmt;
use std::path::{Path, PathBuf};

use serde_json::Value;

use crate::hashline::scan::{scan_bytes, RawLineRecord, Snapshot};
use crate::hashline::snapshot::{equivalent_snapshots, SnapshotLookupError, SnapshotStore};

/// The hashline edit entry point accepts exactly one argument field, `patch`,
/// while hashline validation is enabled.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct HashlineRequest {
    pub patch: String,
}

/// Validate raw tool arguments before any legacy edit normalization can run.
///
/// The gate-on surface owns exactly one field. Rejecting unknown fields is
/// intentional: accepting a legacy `path`, `edits`, or `oldString` field would
/// make an agent believe that hashline verified input which the native engine
/// never parsed.
pub fn validate_raw_arguments(arguments: &Value) -> Result<HashlineRequest, HashlineRejection> {
    let Some(object) = arguments.as_object() else {
        return Err(HashlineRejection::parse(
            "hashline edit arguments must be an object containing only patch",
        ));
    };
    if object.len() != 1 || !object.contains_key("patch") {
        return Err(HashlineRejection::parse(
            "hashline edit arguments must contain only the patch field",
        ));
    }
    let Some(patch) = object.get("patch").and_then(Value::as_str) else {
        return Err(HashlineRejection::parse("patch must be a string"));
    };
    if patch.trim().is_empty() {
        return Err(HashlineRejection::parse("patch must not be empty"));
    }
    Ok(HashlineRequest {
        patch: patch.to_string(),
    })
}

/// A stable pre-execution rejection code.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum HashlineRejectionCode {
    MissingTag,
    MalformedTag,
    UnknownTag,
    EvictedTag,
    AmbiguousTag,
    StaleTag,
    UnseenLine,
    BoundaryIneligible,
    UntaggablePath,
    RegisterOverflow,
    BackupUnavailable,
    ParseError,
}

impl HashlineRejectionCode {
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::MissingTag => "hashline_missing_tag",
            Self::MalformedTag => "hashline_malformed_tag",
            Self::UnknownTag => "hashline_unknown_tag",
            Self::EvictedTag => "hashline_evicted_tag",
            Self::AmbiguousTag => "hashline_ambiguous_tag",
            Self::StaleTag => "hashline_stale_tag",
            Self::UnseenLine => "hashline_unseen_line",
            Self::BoundaryIneligible => "hashline_boundary_ineligible",
            Self::UntaggablePath => "hashline_untaggable_path",
            Self::RegisterOverflow => "hashline_register_overflow",
            Self::BackupUnavailable => "hashline_backup_unavailable",
            Self::ParseError => "hashline_parse_error",
        }
    }
}

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

/// The one canonical Phase-1 adjudication stage enum.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum RejectionStage {
    Parse,
    Header,
    Path,
    Resolution,
    Eligibility,
    Verification,
    Recovery,
    Register,
    Baseline,
}

impl RejectionStage {
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Parse => "parse",
            Self::Header => "header",
            Self::Path => "path",
            Self::Resolution => "resolution",
            Self::Eligibility => "eligibility",
            Self::Verification => "verification",
            Self::Recovery => "recovery",
            Self::Register => "register",
            Self::Baseline => "baseline",
        }
    }
}

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

/// Transport-neutral details for a Phase-1 rejection.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct HashlineRejection {
    pub code: HashlineRejectionCode,
    pub stage: RejectionStage,
    pub message: String,
    pub steering: String,
}

impl HashlineRejection {
    pub fn new(
        code: HashlineRejectionCode,
        stage: RejectionStage,
        message: impl Into<String>,
    ) -> Self {
        Self {
            code,
            stage,
            message: message.into(),
            steering: steering_for(code, stage).to_string(),
        }
    }

    pub fn parse(message: impl Into<String>) -> Self {
        Self::new(
            HashlineRejectionCode::ParseError,
            RejectionStage::Parse,
            message,
        )
    }

    pub fn missing_tag(message: impl Into<String>) -> Self {
        Self::new(
            HashlineRejectionCode::MissingTag,
            RejectionStage::Header,
            message,
        )
    }

    pub fn malformed_tag(message: impl Into<String>) -> Self {
        Self::new(
            HashlineRejectionCode::MalformedTag,
            RejectionStage::Header,
            message,
        )
    }

    pub fn resolution(code: HashlineRejectionCode, message: impl Into<String>) -> Self {
        debug_assert!(matches!(
            code,
            HashlineRejectionCode::UnknownTag
                | HashlineRejectionCode::EvictedTag
                | HashlineRejectionCode::AmbiguousTag
        ));
        Self::new(code, RejectionStage::Resolution, message)
    }

    pub fn eligibility(code: HashlineRejectionCode, message: impl Into<String>) -> Self {
        debug_assert!(matches!(
            code,
            HashlineRejectionCode::UnseenLine | HashlineRejectionCode::BoundaryIneligible
        ));
        Self::new(code, RejectionStage::Eligibility, message)
    }

    pub fn stale_verification(message: impl Into<String>) -> Self {
        Self::new(
            HashlineRejectionCode::StaleTag,
            RejectionStage::Verification,
            message,
        )
    }

    pub fn stale_recovery(message: impl Into<String>) -> Self {
        Self::new(
            HashlineRejectionCode::StaleTag,
            RejectionStage::Recovery,
            message,
        )
    }

    pub fn ambiguous_recovery(message: impl Into<String>) -> Self {
        Self::new(
            HashlineRejectionCode::AmbiguousTag,
            RejectionStage::Recovery,
            message,
        )
    }

    pub fn untaggable_path(message: impl Into<String>) -> Self {
        Self::new(
            HashlineRejectionCode::UntaggablePath,
            RejectionStage::Path,
            message,
        )
    }

    pub fn register_overflow(message: impl Into<String>) -> Self {
        Self::new(
            HashlineRejectionCode::RegisterOverflow,
            RejectionStage::Register,
            message,
        )
    }

    pub fn backup_unavailable(message: impl Into<String>) -> Self {
        Self::new(
            HashlineRejectionCode::BackupUnavailable,
            RejectionStage::Baseline,
            message,
        )
    }
}

impl fmt::Display for HashlineRejection {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            formatter,
            "{} at {}: {}",
            self.code, self.stage, self.message
        )
    }
}

impl std::error::Error for HashlineRejection {}

fn steering_for(code: HashlineRejectionCode, stage: RejectionStage) -> &'static str {
    match (code, stage) {
        (HashlineRejectionCode::MissingTag | HashlineRejectionCode::MalformedTag, _) => {
            "read the current file with the tagged read surface, then include its four-hex tag"
        }
        (
            HashlineRejectionCode::UnknownTag | HashlineRejectionCode::EvictedTag,
            RejectionStage::Resolution,
        ) => "re-read the current tagged content before editing",
        (HashlineRejectionCode::AmbiguousTag, RejectionStage::Resolution) => {
            "use apply_patch or another available non-hashline edit surface; re-reading preserves this colliding four-hex tag"
        }
        (HashlineRejectionCode::AmbiguousTag, RejectionStage::Recovery) => {
            "re-address the current tagged content; the stale span has multiple verbatim landings"
        }
        (HashlineRejectionCode::StaleTag, RejectionStage::Verification) => {
            "perform a ranged tagged re-read because required boundary context changed"
        }
        (HashlineRejectionCode::StaleTag, RejectionStage::Recovery) => {
            "re-address the current tagged content; the stale span no longer occurs verbatim"
        }
        (HashlineRejectionCode::UnseenLine | HashlineRejectionCode::BoundaryIneligible, _) => {
            "read the addressed rows and their boundary context with the tagged read surface"
        }
        (HashlineRejectionCode::UntaggablePath, _) => {
            "choose a writable regular text file or use an available non-hashline surface"
        }
        (HashlineRejectionCode::RegisterOverflow, _) => {
            "reduce register contents before retrying the patch"
        }
        (HashlineRejectionCode::BackupUnavailable, _) => {
            "enable backups or use apply_patch for this destructive change"
        }
        (HashlineRejectionCode::ParseError, _) => {
            "submit only a hashline patch with tagged section headers and valid operations"
        }
        _ => "re-read the current tagged content before editing",
    }
}

/// A parsed patch. Section order is patch order and must be retained by later
/// planning and execution stages.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Patch {
    pub sections: Vec<PatchSection>,
}

impl Patch {
    pub fn is_empty(&self) -> bool {
        self.sections.is_empty()
    }
}

/// A per-file patch unit headed by the requested path and its snapshot tag.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PatchSection {
    pub header: SectionHeader,
    pub operations: Vec<Operation>,
    pub line: usize,
}

/// The lossless path spelling paired with a normalized tag.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SectionHeader {
    pub requested_path: String,
    pub tag: String,
}

impl SectionHeader {
    pub fn new(
        requested_path: impl Into<String>,
        tag: impl AsRef<str>,
    ) -> Result<Self, HashlineRejection> {
        let requested_path = requested_path.into();
        if requested_path.is_empty() {
            return Err(HashlineRejection::missing_tag(
                "a section header must name a path before its tag",
            ));
        }
        let tag = normalize_tag(tag.as_ref())?;
        Ok(Self {
            requested_path,
            tag,
        })
    }
}

/// One hashline operation. Body-bearing PUTs retain logical body lines so the
/// apply layer can select the target file's terminator policy after verification.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Operation {
    Put(PutOperation),
    Cut(CutOperation),
    Rem(RemOperation),
    Mv(MvOperation),
}

impl Operation {
    pub fn address(&self) -> Option<&Address> {
        match self {
            Self::Put(operation) => Some(&operation.address),
            Self::Cut(operation) => Some(&operation.address),
            Self::Rem(_) | Self::Mv(_) => None,
        }
    }

    fn append_body_line(&mut self, line: &str) -> bool {
        match self {
            Self::Put(PutOperation {
                source: PutSource::Text(lines),
                ..
            }) => {
                let Some(content) = line.strip_prefix('+') else {
                    return false;
                };
                lines.push(content.to_string());
                true
            }
            _ => false,
        }
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PutOperation {
    pub address: Address,
    pub source: PutSource,
    pub line: usize,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum PutSource {
    Text(Vec<String>),
    Register(RegisterRef),
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CutOperation {
    pub address: Address,
    pub register: Option<RegisterRef>,
    pub line: usize,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct RemOperation {
    pub line: usize,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct MvOperation {
    pub destination: String,
    pub line: usize,
}

/// Named registers are durable only for the life of the session; the anonymous
/// register is represented explicitly so it cannot collide with an empty name.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub enum RegisterRef {
    Anonymous,
    Named(String),
}

/// A reference whose value is resolved solely from `Snapshot::total_lines`.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum LineReference {
    Absolute(usize),
    /// `$` is offset zero; `$-1` is the penultimate snapshot row.
    EofRelative(usize),
}

/// One parsed pre-request address.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Address {
    /// `0` and `<1` are both BOF insertion forms.
    Bof,
    Line(LineReference),
    Range {
        start: LineReference,
        end: LineReference,
    },
    Gap {
        side: GapSide,
        line: LineReference,
    },
    Block(LineReference),
    /// A gap adjacent to a syntactic block, such as `>8*`.
    BlockGap {
        side: GapSide,
        line: LineReference,
    },
}

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum GapSide {
    Before,
    After,
}

/// Parse a complete patch after raw tool arguments selected the hashline path.
/// Accept an optional `*** Begin Patch` / `*** End Patch` envelope, but reject
/// any other preamble or trailing content instead of ignoring it.
pub fn parse_hashline_patch(patch: &str) -> Result<Patch, HashlineRejection> {
    if patch.trim().is_empty() {
        return Err(HashlineRejection::parse("patch must not be empty"));
    }

    let mut sections = Vec::new();
    let mut envelope_started = false;
    let mut envelope_ended = false;
    for (index, raw_line) in patch.split('\n').enumerate() {
        let line_number = index + 1;
        let line = raw_line.strip_suffix('\r').unwrap_or(raw_line);
        let trimmed = line.trim();

        if trimmed == "*** Begin Patch" {
            if envelope_started || !sections.is_empty() {
                return Err(HashlineRejection::parse(format!(
                    "unexpected patch envelope start at line {line_number}"
                )));
            }
            envelope_started = true;
            continue;
        }
        if trimmed == "*** End Patch" {
            if !envelope_started || envelope_ended {
                return Err(HashlineRejection::parse(format!(
                    "unexpected patch envelope end at line {line_number}"
                )));
            }
            envelope_ended = true;
            continue;
        }
        if envelope_ended {
            if !trimmed.is_empty() {
                return Err(HashlineRejection::parse(format!(
                    "content follows the patch envelope at line {line_number}"
                )));
            }
            continue;
        }

        if is_header_line(trimmed) {
            let header = parse_section_header(trimmed)?;
            sections.push(PatchSection {
                header,
                operations: Vec::new(),
                line: line_number,
            });
            continue;
        }

        if is_directive(line) {
            let section = sections.last_mut().ok_or_else(|| {
                HashlineRejection::parse(format!(
                    "operation at line {line_number} appears before a tagged section header"
                ))
            })?;
            section.operations.push(parse_operation(line, line_number)?);
            continue;
        }

        if trimmed.is_empty() && sections.is_empty() {
            continue;
        }

        let Some(section) = sections.last_mut() else {
            return Err(HashlineRejection::parse(format!(
                "expected a tagged section header at line {line_number}"
            )));
        };
        let Some(operation) = section.operations.last_mut() else {
            return Err(HashlineRejection::parse(format!(
                "expected an operation after section header at line {}",
                section.line
            )));
        };
        if !operation.append_body_line(line) {
            return Err(HashlineRejection::parse(format!(
                "PUT body rows must begin with +; unexpected content at line {line_number}"
            )));
        }
    }

    if envelope_started && !envelope_ended {
        return Err(HashlineRejection::parse(
            "patch envelope is missing *** End Patch",
        ));
    }
    if sections.is_empty() {
        return Err(HashlineRejection::parse(
            "patch must contain at least one tagged section header",
        ));
    }
    if let Some(section) = sections
        .iter()
        .find(|section| section.operations.is_empty())
    {
        return Err(HashlineRejection::parse(format!(
            "section at line {} contains no operation",
            section.line
        )));
    }
    for section in &sections {
        validate_section_composition(section)?;
        for operation in &section.operations {
            if let Operation::Put(PutOperation {
                source: PutSource::Text(lines),
                line,
                ..
            }) = operation
            {
                if lines.is_empty() {
                    return Err(HashlineRejection::parse(format!(
                        "PUT at line {line} requires one or more + body rows"
                    )));
                }
            }
        }
    }
    Ok(Patch { sections })
}

fn validate_section_composition(section: &PatchSection) -> Result<(), HashlineRejection> {
    let rem_count = section
        .operations
        .iter()
        .filter(|operation| matches!(operation, Operation::Rem(_)))
        .count();
    if rem_count > 0 && section.operations.len() != 1 {
        return Err(HashlineRejection::parse(format!(
            "REM at section line {} cannot be combined with line operations",
            section.line
        )));
    }
    let mv_positions: Vec<usize> = section
        .operations
        .iter()
        .enumerate()
        .filter_map(|(index, operation)| matches!(operation, Operation::Mv(_)).then_some(index))
        .collect();
    if mv_positions.len() > 1
        || mv_positions
            .first()
            .is_some_and(|index| *index + 1 != section.operations.len())
    {
        return Err(HashlineRejection::parse(format!(
            "MV at section line {} must occur once and after all line operations",
            section.line
        )));
    }
    Ok(())
}

/// Parse one recognizable header and distinguish absent and malformed tags.
pub fn parse_section_header(line: &str) -> Result<SectionHeader, HashlineRejection> {
    let trimmed = line.trim();
    if !is_header_line(trimmed) {
        return Err(HashlineRejection::parse(
            "section headers must use [requested-path#TAG]",
        ));
    }
    let inner = &trimmed[1..trimmed.len() - 1];
    let Some((path, tag)) = inner.split_once('#') else {
        return Err(HashlineRejection::missing_tag(
            "section header is missing its #TAG handle",
        ));
    };
    if path.is_empty() {
        return Err(HashlineRejection::missing_tag(
            "section header must name a path before #TAG",
        ));
    }
    if path.contains('#') || path.contains(['\r', '\n']) {
        return Err(HashlineRejection::parse(
            "section paths cannot contain #, carriage return, or newline",
        ));
    }
    SectionHeader::new(path, tag)
}

fn is_header_line(line: &str) -> bool {
    line.starts_with('[') && line.ends_with(']') && line.len() >= 2
}

fn is_directive(line: &str) -> bool {
    ["PUT", "CUT", "REM", "MV"].into_iter().any(|keyword| {
        line == keyword
            || line
                .strip_prefix(keyword)
                .is_some_and(|remainder| remainder.starts_with(char::is_whitespace))
    })
}

fn parse_operation(line: &str, line_number: usize) -> Result<Operation, HashlineRejection> {
    let trimmed = line.trim();
    if trimmed == "REM" {
        return parse_rem("", line_number);
    }
    let (keyword, remainder) = trimmed.split_once(char::is_whitespace).ok_or_else(|| {
        HashlineRejection::parse(format!(
            "operation at line {line_number} lacks required input"
        ))
    })?;
    let remainder = remainder.trim();
    match keyword {
        "PUT" => parse_put(remainder, line_number),
        "CUT" => parse_cut(remainder, line_number),
        "REM" => parse_rem(remainder, line_number),
        "MV" => parse_mv(remainder, line_number),
        _ => Err(HashlineRejection::parse(format!(
            "unknown operation {keyword:?} at line {line_number}"
        ))),
    }
}

fn parse_put(remainder: &str, line: usize) -> Result<Operation, HashlineRejection> {
    let Some(prefix) = remainder.strip_suffix(':') else {
        let mut parts = remainder.split_whitespace();
        let address = parts.next().ok_or_else(|| {
            HashlineRejection::parse(format!("PUT at line {line} lacks an address"))
        })?;
        let register = match parts.next() {
            Some(register) => parse_register(register)?,
            // When no register is specified, use the anonymous register. This
            // supports `PUT >$` immediately after a bare CUT.
            None => RegisterRef::Anonymous,
        };
        if parts.next().is_some() {
            return Err(HashlineRejection::parse(format!(
                "PUT at line {line} accepts at most one register source"
            )));
        }
        return Ok(Operation::Put(PutOperation {
            address: parse_address(address)?,
            source: PutSource::Register(register),
            line,
        }));
    };
    let address = prefix.trim();
    if address.is_empty() {
        return Err(HashlineRejection::parse(format!(
            "PUT at line {line} lacks an address before :"
        )));
    }
    Ok(Operation::Put(PutOperation {
        address: parse_address(address)?,
        source: PutSource::Text(Vec::new()),
        line,
    }))
}

fn parse_cut(remainder: &str, line: usize) -> Result<Operation, HashlineRejection> {
    let mut parts = remainder.split_whitespace();
    let address = parts
        .next()
        .ok_or_else(|| HashlineRejection::parse(format!("CUT at line {line} lacks an address")))?;
    let register = match parts.next() {
        Some(register) => Some(parse_register(register)?),
        None => None,
    };
    if parts.next().is_some() {
        return Err(HashlineRejection::parse(format!(
            "CUT at line {line} has unexpected trailing input"
        )));
    }
    Ok(Operation::Cut(CutOperation {
        address: parse_address(address)?,
        register,
        line,
    }))
}

fn parse_rem(remainder: &str, line: usize) -> Result<Operation, HashlineRejection> {
    if !remainder.trim().is_empty() {
        return Err(HashlineRejection::parse(format!(
            "REM at line {line} removes the whole section file and accepts no address"
        )));
    }
    Ok(Operation::Rem(RemOperation { line }))
}

fn parse_mv(remainder: &str, line: usize) -> Result<Operation, HashlineRejection> {
    let destination = remainder.trim();
    if destination.is_empty() || destination.split_whitespace().count() != 1 {
        return Err(HashlineRejection::parse(format!(
            "MV at line {line} requires exactly one destination path"
        )));
    }
    Ok(Operation::Mv(MvOperation {
        destination: unquote(destination).to_string(),
        line,
    }))
}

fn parse_register(input: &str) -> Result<RegisterRef, HashlineRejection> {
    let Some(name) = input.strip_prefix('@') else {
        return Err(HashlineRejection::parse("registers must begin with @"));
    };
    if name.is_empty()
        || !name.chars().all(|character| {
            character.is_ascii_alphanumeric() || character == '_' || character == '-'
        })
    {
        return Err(HashlineRejection::parse(
            "register names may contain only ASCII letters, digits, _, and -",
        ));
    }
    Ok(RegisterRef::Named(name.to_string()))
}

/// Parse line, range, gap, block, and EOF-relative forms without consulting a
/// live file. Resolution happens later against a snapshot's recorded line count.
pub fn parse_address(input: &str) -> Result<Address, HashlineRejection> {
    let input = input.trim();
    if input == "0" {
        return Ok(Address::Bof);
    }
    if let Some((side, line)) = input
        .strip_prefix('<')
        .map(|line| (GapSide::Before, line))
        .or_else(|| input.strip_prefix('>').map(|line| (GapSide::After, line)))
    {
        if let Some(block_line) = line.strip_suffix('*') {
            return Ok(Address::BlockGap {
                side,
                line: parse_line_reference(block_line)?,
            });
        }
        return Ok(Address::Gap {
            side,
            line: parse_line_reference(line)?,
        });
    }
    if let Some(line) = input.strip_suffix('*') {
        return Ok(Address::Block(parse_line_reference(line)?));
    }
    // The canonical range separator is `.=`, but these alternate forms retain
    // compatibility with existing hashline input.
    for separator in ["..=", ".=", ".."] {
        if let Some((start, end)) = input.split_once(separator) {
            return Ok(Address::Range {
                start: parse_line_reference(start)?,
                end: parse_line_reference(end)?,
            });
        }
    }
    Ok(Address::Line(parse_line_reference(input)?))
}

fn parse_line_reference(input: &str) -> Result<LineReference, HashlineRejection> {
    let input = input.trim();
    if input == "$" {
        return Ok(LineReference::EofRelative(0));
    }
    if let Some(offset) = input.strip_prefix("$-") {
        return Ok(LineReference::EofRelative(parse_positive_usize(offset)?));
    }
    let line = parse_positive_usize(input)?;
    Ok(LineReference::Absolute(line))
}

fn parse_positive_usize(input: &str) -> Result<usize, HashlineRejection> {
    let value = input.parse::<usize>().map_err(|_| {
        HashlineRejection::parse(format!("{input:?} is not a valid positive line number"))
    })?;
    if value == 0 {
        return Err(HashlineRejection::parse(
            "line number zero is only valid as the standalone BOF address",
        ));
    }
    Ok(value)
}

fn unquote(value: &str) -> &str {
    value
        .strip_prefix('"')
        .and_then(|value| value.strip_suffix('"'))
        .or_else(|| {
            value
                .strip_prefix('\'')
                .and_then(|value| value.strip_suffix('\''))
        })
        .unwrap_or(value)
}

fn normalize_tag(tag: &str) -> Result<String, HashlineRejection> {
    if tag.len() != 4 || !tag.bytes().all(|byte| byte.is_ascii_hexdigit()) {
        return Err(HashlineRejection::malformed_tag(
            "section tags must be exactly four hexadecimal digits",
        ));
    }
    Ok(tag.to_ascii_uppercase())
}

/// A fully resolved inclusive span in pre-request coordinates.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct LineSpan {
    pub start: usize,
    pub end: usize,
}

impl LineSpan {
    pub fn new(start: usize, end: usize) -> Option<Self> {
        (start > 0 && start <= end).then_some(Self { start, end })
    }

    pub fn lines(self) -> impl Iterator<Item = usize> {
        self.start..=self.end
    }
}

/// A gap resolves to adjacent snapshot rows rather than a current live-file
/// offset. `None` anchors name BOF/EOF facts retained in the snapshot.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct ResolvedGap {
    pub before: Option<usize>,
    pub after: Option<usize>,
}

/// The result of resolving one parsed address against its retained snapshot.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum ResolvedAddress {
    /// REM and MV address every record in their source section file.
    WholeFile,
    Span(LineSpan),
    Gap(ResolvedGap),
    /// Block parsing is owned here; a language-aware block resolver expands the
    /// anchor to a span before verification and execution.
    BlockAnchor(usize),
    /// A language-aware resolver must expand this block before the gap can be
    /// verified against its predecessor and successor anchors.
    BlockGapAnchor {
        side: GapSide,
        anchor: usize,
    },
}

impl ResolvedAddress {
    pub fn addressed_span(self) -> Option<LineSpan> {
        match self {
            Self::Span(span) => Some(span),
            Self::WholeFile | Self::Gap(_) | Self::BlockAnchor(_) | Self::BlockGapAnchor { .. } => {
                None
            }
        }
    }

    pub fn required_anchors(self) -> Vec<usize> {
        match self {
            Self::Gap(gap) => [gap.before, gap.after].into_iter().flatten().collect(),
            Self::WholeFile
            | Self::Span(_)
            | Self::BlockAnchor(_)
            | Self::BlockGapAnchor { .. } => Vec::new(),
        }
    }
}

/// Resolve an address against the snapshot that minted its handle. This function
/// never reads filesystem state, including for `$` and EOF-relative forms.
pub fn resolve_address(
    address: &Address,
    snapshot: &Snapshot,
) -> Result<ResolvedAddress, HashlineRejection> {
    let total_lines = snapshot.total_lines;
    match address {
        Address::Bof => Ok(ResolvedAddress::Gap(ResolvedGap {
            before: None,
            after: (total_lines > 0).then_some(1),
        })),
        Address::Line(reference) => {
            let line = resolve_line_reference(*reference, total_lines)?;
            Ok(ResolvedAddress::Span(LineSpan {
                start: line,
                end: line,
            }))
        }
        Address::Range { start, end } => {
            let start = resolve_line_reference(*start, total_lines)?;
            let end = resolve_line_reference(*end, total_lines)?;
            let Some(span) = LineSpan::new(start, end) else {
                return Err(HashlineRejection::eligibility(
                    HashlineRejectionCode::BoundaryIneligible,
                    "range start occurs after range end in the retained snapshot",
                ));
            };
            Ok(ResolvedAddress::Span(span))
        }
        Address::Gap { side, line } => {
            let line = resolve_line_reference(*line, total_lines)?;
            let gap = match side {
                GapSide::Before => ResolvedGap {
                    before: line.checked_sub(1),
                    after: Some(line),
                },
                GapSide::After => ResolvedGap {
                    before: Some(line),
                    after: (line < total_lines).then_some(line + 1),
                },
            };
            Ok(ResolvedAddress::Gap(gap))
        }
        Address::Block(reference) => Ok(ResolvedAddress::BlockAnchor(resolve_line_reference(
            *reference,
            total_lines,
        )?)),
        Address::BlockGap { side, line } => Ok(ResolvedAddress::BlockGapAnchor {
            side: *side,
            anchor: resolve_line_reference(*line, total_lines)?,
        }),
    }
}

fn resolve_line_reference(
    reference: LineReference,
    total_lines: usize,
) -> Result<usize, HashlineRejection> {
    let line = match reference {
        LineReference::Absolute(line) if line <= total_lines => Some(line),
        LineReference::EofRelative(offset) if offset < total_lines => Some(total_lines - offset),
        LineReference::Absolute(_) | LineReference::EofRelative(_) => None,
    };
    line.ok_or_else(|| {
        HashlineRejection::eligibility(
            HashlineRejectionCode::BoundaryIneligible,
            "address falls outside the retained snapshot boundary",
        )
    })
}

/// Substitute an authoritative language-aware block span for a parsed block
/// anchor. The supplied span is still constrained to pre-request coordinates.
pub fn expand_block(
    resolved: ResolvedAddress,
    span: LineSpan,
    snapshot: &Snapshot,
) -> Result<ResolvedAddress, HashlineRejection> {
    let (side, anchor) = match resolved {
        ResolvedAddress::BlockAnchor(anchor) => (None, anchor),
        ResolvedAddress::BlockGapAnchor { side, anchor } => (Some(side), anchor),
        ResolvedAddress::WholeFile | ResolvedAddress::Span(_) | ResolvedAddress::Gap(_) => {
            return Err(HashlineRejection::parse(
                "only a parsed block address can be expanded as a block",
            ));
        }
    };
    if !span.lines().any(|line| line == anchor) || span.end > snapshot.total_lines {
        return Err(HashlineRejection::eligibility(
            HashlineRejectionCode::BoundaryIneligible,
            "block resolver returned a span outside the retained snapshot",
        ));
    }
    match side {
        None => Ok(ResolvedAddress::Span(span)),
        Some(GapSide::Before) => Ok(ResolvedAddress::Gap(ResolvedGap {
            before: span.start.checked_sub(1),
            after: Some(span.start),
        })),
        Some(GapSide::After) => Ok(ResolvedAddress::Gap(ResolvedGap {
            before: Some(span.end),
            after: (span.end < snapshot.total_lines).then_some(span.end + 1),
        })),
    }
}

/// Prove that the retained snapshot authorizes every record and boundary fact
/// an address will use. This is deliberately separate from exact verification:
/// an unread row is never eligible merely because current bytes happen to match.
pub fn check_eligibility(
    snapshot: &Snapshot,
    address: ResolvedAddress,
) -> Result<(), HashlineRejection> {
    match address {
        ResolvedAddress::WholeFile => {
            if snapshot.records.len() != snapshot.total_lines
                || (1..=snapshot.total_lines).any(|line| !snapshot.is_seen(line))
            {
                return Err(HashlineRejection::eligibility(
                    HashlineRejectionCode::UnseenLine,
                    "REM and MV require a tagged read that retained the whole source file",
                ));
            }
        }
        ResolvedAddress::Span(span) => {
            for line in span.lines() {
                if !snapshot.is_seen(line) {
                    return Err(HashlineRejection::eligibility(
                        HashlineRejectionCode::UnseenLine,
                        format!("line {line} was not retained by the tagged read"),
                    ));
                }
            }
        }
        ResolvedAddress::BlockAnchor(line)
        | ResolvedAddress::BlockGapAnchor { anchor: line, .. } => {
            if !snapshot.is_seen(line) {
                return Err(HashlineRejection::eligibility(
                    HashlineRejectionCode::UnseenLine,
                    format!("block anchor line {line} was not retained by the tagged read"),
                ));
            }
        }
        ResolvedAddress::Gap(gap) => {
            if gap.before.is_none() && gap.after.is_none() {
                if !snapshot.boundary.empty_file {
                    return Err(HashlineRejection::eligibility(
                        HashlineRejectionCode::BoundaryIneligible,
                        "empty-file gap has no retained empty-file boundary evidence",
                    ));
                }
                return Ok(());
            }
            for line in [gap.before, gap.after].into_iter().flatten() {
                if !snapshot.is_seen(line) {
                    return Err(HashlineRejection::eligibility(
                        HashlineRejectionCode::UnseenLine,
                        format!("gap boundary line {line} was not retained by the tagged read"),
                    ));
                }
            }
            if gap.before.is_none() && !snapshot.boundary.bof_observed {
                return Err(HashlineRejection::eligibility(
                    HashlineRejectionCode::BoundaryIneligible,
                    "BOF boundary evidence was not retained",
                ));
            }
            if gap.after.is_none() && !snapshot.boundary.eof_observed {
                return Err(HashlineRejection::eligibility(
                    HashlineRejectionCode::BoundaryIneligible,
                    "EOF boundary evidence was not retained",
                ));
            }
        }
    }
    Ok(())
}

/// Resolve all sections against their snapshot handles before any later apply
/// stage can mutate a path. A canonical path may appear in several sections,
/// but all of those sections must use equivalent verification evidence.
#[derive(Clone, Debug)]
pub struct ResolvedPatchSection {
    pub section_index: usize,
    pub canonical_path: PathBuf,
    pub snapshot: Snapshot,
    pub operations: Vec<ResolvedOperation>,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ResolvedOperation {
    pub operation_index: usize,
    /// REM and MV use `WholeFile`; line operations retain their parsed address.
    pub address: ResolvedAddress,
}

pub fn resolve_patch_sections<F>(
    store: &mut SnapshotStore,
    patch: &Patch,
    mut canonicalize: F,
) -> Result<Vec<ResolvedPatchSection>, HashlineRejection>
where
    F: FnMut(&str) -> Result<PathBuf, HashlineRejection>,
{
    let mut views: BTreeMap<PathBuf, Snapshot> = BTreeMap::new();
    let mut resolved = Vec::with_capacity(patch.sections.len());
    for (section_index, section) in patch.sections.iter().enumerate() {
        let canonical_path = canonicalize(&section.header.requested_path)?;
        let snapshot = resolve_snapshot(store, &canonical_path, &section.header.tag)?;
        if let Some(existing) = views.get(&canonical_path) {
            if !equivalent_snapshots(existing, &snapshot) {
                return Err(HashlineRejection::resolution(
                    HashlineRejectionCode::AmbiguousTag,
                    "sections for one canonical path selected different retained verification evidence",
                ));
            }
        } else {
            views.insert(canonical_path.clone(), snapshot.clone());
        }

        let mut operations = Vec::with_capacity(section.operations.len());
        for (operation_index, operation) in section.operations.iter().enumerate() {
            let address = match operation.address() {
                Some(address) => resolve_address(address, &snapshot)?,
                None => ResolvedAddress::WholeFile,
            };
            check_eligibility(&snapshot, address)?;
            operations.push(ResolvedOperation {
                operation_index,
                address,
            });
        }
        resolved.push(ResolvedPatchSection {
            section_index,
            canonical_path,
            snapshot,
            operations,
        });
    }
    Ok(resolved)
}

/// Normalize and resolve one case-insensitive four-hex snapshot tag using the
/// snapshot store's recorded result for the requested canonical path.
pub fn resolve_snapshot(
    store: &mut SnapshotStore,
    canonical_path: impl AsRef<Path>,
    tag: &str,
) -> Result<Snapshot, HashlineRejection> {
    let tag = normalize_tag(tag)?;
    store
        .lookup(canonical_path, &tag)
        .map_err(|error| match error {
            SnapshotLookupError::UnknownTag => HashlineRejection::resolution(
                HashlineRejectionCode::UnknownTag,
                "the tagged snapshot is not resident for this path",
            ),
            SnapshotLookupError::EvictedTag => HashlineRejection::resolution(
                HashlineRejectionCode::EvictedTag,
                "the tagged snapshot was evicted from this session",
            ),
            SnapshotLookupError::AmbiguousTag => HashlineRejection::resolution(
                HashlineRejectionCode::AmbiguousTag,
                "the four-hex tag collides across different normalized file content",
            ),
        })
}

/// A complete Phase-1 baseline owned by one patch and one canonical path.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Baseline {
    pub bytes: Vec<u8>,
    pub snapshot: Snapshot,
}

impl Baseline {
    pub fn from_bytes(bytes: impl Into<Vec<u8>>) -> Self {
        let bytes = bytes.into();
        Self {
            snapshot: scan_bytes(&bytes),
            bytes,
        }
    }

    pub fn raw_record(&self, line: usize) -> Option<&RawLineRecord> {
        self.snapshot.raw_record(line)
    }
}

/// A per-patch cache that makes the one-baseline-per-canonical-path contract
/// explicit. Calling `load_once` again returns the original byte buffer rather
/// than silently replacing the evidence used by another section.
#[derive(Clone, Debug, Default)]
pub struct BaselineCache {
    baselines: BTreeMap<PathBuf, Baseline>,
}

impl BaselineCache {
    pub fn load_once(
        &mut self,
        canonical_path: impl Into<PathBuf>,
        bytes: impl Into<Vec<u8>>,
    ) -> &Baseline {
        let path = canonical_path.into();
        self.baselines
            .entry(path)
            .or_insert_with(|| Baseline::from_bytes(bytes))
    }

    pub fn get(&self, canonical_path: impl AsRef<Path>) -> Option<&Baseline> {
        self.baselines.get(canonical_path.as_ref())
    }

    pub fn len(&self) -> usize {
        self.baselines.len()
    }

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

/// The result of exact verification. An addressed-span mismatch is deliberately
/// not a rejection: the recovery planner receives its exact old records. An
/// anchor mismatch remains a loud verification-stage rejection because moving a
/// gap or boundary insertion would change its meaning.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum VerificationOutcome {
    Exact,
    RecoveryRequired(RecoveryPlan),
    Rejected(HashlineRejection),
    BlockNeedsResolution { anchor: usize },
}

/// The exact records from the old addressed span that a recovery plan can use
/// to remap the operation.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct RecoveryPlan {
    pub old_span: LineSpan,
    pub expected_records: Vec<RawLineRecord>,
}

/// Verify an already-resolved address against one common baseline. Anchor rows
/// are checked before addressed rows so a stale gap cannot be auto-remapped.
pub fn verify_exact(
    snapshot: &Snapshot,
    baseline: &Baseline,
    address: ResolvedAddress,
) -> VerificationOutcome {
    if let Err(rejection) = check_eligibility(snapshot, address) {
        return VerificationOutcome::Rejected(rejection);
    }
    match address {
        ResolvedAddress::WholeFile => {
            if snapshot.total_lines != baseline.snapshot.total_lines
                || snapshot.records != baseline.snapshot.records
            {
                VerificationOutcome::Rejected(HashlineRejection::stale_verification(
                    "the whole-file source changed since the tagged read",
                ))
            } else {
                VerificationOutcome::Exact
            }
        }
        ResolvedAddress::BlockAnchor(anchor) | ResolvedAddress::BlockGapAnchor { anchor, .. } => {
            VerificationOutcome::BlockNeedsResolution { anchor }
        }
        ResolvedAddress::Gap(gap) => {
            for line in [gap.before, gap.after].into_iter().flatten() {
                if snapshot.raw_record(line) != baseline.raw_record(line) {
                    return VerificationOutcome::Rejected(HashlineRejection::stale_verification(
                        format!("required gap anchor line {line} changed since the tagged read"),
                    ));
                }
            }
            VerificationOutcome::Exact
        }
        ResolvedAddress::Span(span) => {
            let expected_records: Vec<RawLineRecord> = span
                .lines()
                .filter_map(|line| snapshot.raw_record(line).cloned())
                .collect();
            let changed = span
                .lines()
                .any(|line| snapshot.raw_record(line) != baseline.raw_record(line));
            if changed {
                VerificationOutcome::RecoveryRequired(RecoveryPlan {
                    old_span: span,
                    expected_records,
                })
            } else {
                VerificationOutcome::Exact
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::hashline::scan::{scan_bytes_with_request, CoverageInput, ScanRequest};
    use crate::hashline::snapshot::MAX_SNAPSHOT_PATHS;

    fn snapshot(bytes: &[u8], lines: impl IntoIterator<Item = usize>) -> Snapshot {
        scan_bytes_with_request(bytes, ScanRequest::new(CoverageInput::lines(lines)))
            .snapshot
            .expect("in-memory snapshots reach EOF")
    }

    #[test]
    fn raw_arguments_allow_only_a_nonempty_patch_string() {
        let request = validate_raw_arguments(&serde_json::json!({
            "patch": "[src/lib.rs#cafe]\nREM"
        }))
        .expect("hashline request");
        assert!(request.patch.contains("REM"));

        for value in [
            serde_json::json!({"patch": "", "path": "src/lib.rs"}),
            serde_json::json!({"patch": 3}),
            serde_json::json!({"path": "src/lib.rs", "edits": []}),
        ] {
            let rejection = validate_raw_arguments(&value).expect_err("legacy shape is rejected");
            assert_eq!(rejection.code, HashlineRejectionCode::ParseError);
            assert_eq!(rejection.stage, RejectionStage::Parse);
        }
    }

    #[test]
    fn headers_distinguish_missing_and_malformed_tags() {
        let missing = parse_section_header("[src/lib.rs]").expect_err("missing tag");
        assert_eq!(missing.code, HashlineRejectionCode::MissingTag);
        assert_eq!(missing.stage, RejectionStage::Header);

        for header in ["[src/lib.rs#]", "[src/lib.rs#abc]", "[src/lib.rs#ABCDE]"] {
            let malformed = parse_section_header(header).expect_err("malformed tag");
            assert_eq!(malformed.code, HashlineRejectionCode::MalformedTag);
            assert_eq!(malformed.stage, RejectionStage::Header);
        }
        assert_eq!(
            parse_section_header("[src/lib.rs#cAfE]")
                .expect("valid header")
                .tag,
            "CAFE"
        );
    }

    #[test]
    fn parser_retains_multisection_operations_and_put_body() {
        let patch = parse_hashline_patch(
            "*** Begin Patch\n[a.rs#cafe]\nPUT <2:\n+first\n+second\nCUT 3 @copied\n[b.rs#BEEF]\nPUT $ @copied\nMV c.rs\n*** End Patch",
        )
        .expect("patch parses");
        assert_eq!(patch.sections.len(), 2);
        assert_eq!(patch.sections[0].operations.len(), 2);
        let Operation::Put(put) = &patch.sections[0].operations[0] else {
            panic!("first operation is PUT");
        };
        assert_eq!(
            put.source,
            PutSource::Text(vec!["first".into(), "second".into()])
        );
        assert!(matches!(
            patch.sections[1].operations[0],
            Operation::Put(PutOperation {
                source: PutSource::Register(RegisterRef::Named(_)),
                ..
            })
        ));
    }

    #[test]
    fn parser_accepts_all_pre_request_address_forms() {
        assert_eq!(parse_address("0").unwrap(), Address::Bof);
        assert!(matches!(
            parse_address("2.=4").unwrap(),
            Address::Range { .. }
        ));
        assert!(matches!(
            parse_address("2..=4").unwrap(),
            Address::Range { .. }
        ));
        assert!(matches!(parse_address("<1").unwrap(), Address::Gap { .. }));
        assert!(matches!(
            parse_address(">$-1").unwrap(),
            Address::Gap { .. }
        ));
        assert!(matches!(
            parse_address(">8*").unwrap(),
            Address::BlockGap {
                side: GapSide::After,
                ..
            }
        ));
        assert!(matches!(parse_address("$*").unwrap(), Address::Block(_)));
    }

    #[test]
    fn parser_rejects_body_rows_without_plus_and_noncanonical_file_operations() {
        let body = parse_hashline_patch("[a.rs#CAFE]\nPUT 1:\nreplacement")
            .expect_err("body rows require the + marker");
        assert_eq!(body.stage, RejectionStage::Parse);
        assert!(parse_hashline_patch("[a.rs#CAFE]\nREM 1").is_err());
        assert!(parse_hashline_patch("[a.rs#CAFE]\nMV 1 -> b.rs").is_err());
        assert!(parse_hashline_patch("[a.rs#CAFE]\nREM\nPUT 1:\n+x").is_err());
        assert!(parse_hashline_patch("[a.rs#CAFE]\nMV b.rs\nCUT 1").is_err());
    }

    #[test]
    fn snapshot_lookup_maps_all_store_outcomes_to_resolution_stage() {
        let mut store = SnapshotStore::new();
        let unknown = resolve_snapshot(&mut store, "/not-known", "CAFE").expect_err("unknown");
        assert_eq!(unknown.code, HashlineRejectionCode::UnknownTag);
        assert_eq!(unknown.stage, RejectionStage::Resolution);

        let path = PathBuf::from("/same-tag");
        let first = snapshot(b"shared\none\n", [1]);
        let mut collision = snapshot(b"shared\nother\n", [1]);
        let tag = first.tag.clone();
        collision.tag = tag.clone();
        store.publish(&path, first);
        store.publish(&path, collision);
        let ambiguous = resolve_snapshot(&mut store, &path, &tag).expect_err("collision");
        assert_eq!(store.snapshot_count(), 2);
        assert_eq!(
            store.lookup_state(&path, &tag),
            crate::hashline::snapshot::SnapshotLookup::Ambiguous
        );
        assert_eq!(ambiguous.code, HashlineRejectionCode::AmbiguousTag);
        assert_eq!(ambiguous.stage, RejectionStage::Resolution);
        assert_eq!(
            ambiguous.steering,
            "use apply_patch or another available non-hashline edit surface; re-reading preserves this colliding four-hex tag"
        );
    }

    #[test]
    fn evicted_handles_keep_their_distinct_resolution_code() {
        let mut store = SnapshotStore::new();
        let first_path = PathBuf::from("/evicted-0");
        let first = snapshot(b"row\n", [1]);
        let tag = first.tag.clone();
        store.publish(&first_path, first);
        for index in 1..=MAX_SNAPSHOT_PATHS {
            store.publish(
                PathBuf::from(format!("/evicted-{index}")),
                snapshot(b"row\n", [1]),
            );
        }
        let rejection = resolve_snapshot(&mut store, &first_path, &tag).expect_err("evicted");
        assert_eq!(rejection.code, HashlineRejectionCode::EvictedTag);
        assert_eq!(rejection.stage, RejectionStage::Resolution);
    }

    #[test]
    fn equivalent_candidates_resolve_despite_different_provenance() {
        let mut store = SnapshotStore::new();
        let path = PathBuf::from("/equivalent");
        let first = snapshot(b"one\ntwo\n", [1]);
        let mut reread = snapshot(b"one\ntwo\n", [1]);
        reread.provenance = reread.provenance.with_label("read", "second");
        let tag = first.tag.clone();
        store.publish(&path, first);
        store.publish(&path, reread);
        assert!(resolve_snapshot(&mut store, &path, &tag).is_ok());
    }

    #[test]
    fn same_path_sections_are_resolved_in_pre_request_coordinates() {
        let mut store = SnapshotStore::new();
        let path = PathBuf::from("/pre-request");
        let captured = snapshot(b"one\ntwo\nthree\n", [1, 2, 3]);
        let tag = captured.tag.clone();
        store.publish(&path, captured);
        let patch = parse_hashline_patch(&format!(
            "[/pre-request#{tag}]\nCUT 1\n[/pre-request#{tag}]\nCUT 3"
        ))
        .expect("patch");
        let sections =
            resolve_patch_sections(&mut store, &patch, |requested| Ok(PathBuf::from(requested)))
                .expect("both sections resolve before mutation");
        assert_eq!(sections.len(), 2);
        assert_eq!(
            sections[1].operations[0].address,
            ResolvedAddress::Span(LineSpan { start: 3, end: 3 })
        );
    }

    #[test]
    fn whole_file_operations_require_full_retained_coverage() {
        let mut store = SnapshotStore::new();
        let path = PathBuf::from("/whole-file");
        let partial = snapshot(b"one\ntwo\n", [1]);
        let tag = partial.tag.clone();
        store.publish(&path, partial);
        let patch = parse_hashline_patch(&format!("[/whole-file#{tag}]\nREM")).expect("patch");
        let rejection =
            resolve_patch_sections(&mut store, &patch, |requested| Ok(PathBuf::from(requested)))
                .expect_err("partial read cannot authorize whole-file deletion");
        assert_eq!(rejection.code, HashlineRejectionCode::UnseenLine);
        assert_eq!(rejection.stage, RejectionStage::Eligibility);
    }

    #[test]
    fn addresses_resolve_against_snapshot_not_live_baseline_length() {
        let retained = snapshot(b"one\ntwo\nthree\n", [2, 3]);
        let resolved = resolve_address(&parse_address("$-1").unwrap(), &retained).unwrap();
        assert_eq!(
            resolved,
            ResolvedAddress::Span(LineSpan { start: 2, end: 2 })
        );

        let baseline = Baseline::from_bytes(b"one\ntwo\nthree\nfour\n".to_vec());
        assert!(matches!(
            verify_exact(&retained, &baseline, resolved),
            VerificationOutcome::Exact
        ));
    }

    #[test]
    fn gaps_require_their_retained_boundary_rows() {
        let retained = snapshot(b"one\ntwo\nthree\n", [2]);
        let gap = resolve_address(&parse_address("<2").unwrap(), &retained).unwrap();
        let rejection = check_eligibility(&retained, gap).expect_err("line one was unseen");
        assert_eq!(rejection.code, HashlineRejectionCode::UnseenLine);
        assert_eq!(rejection.stage, RejectionStage::Eligibility);

        let eof = resolve_address(&parse_address(">$").unwrap(), &retained).unwrap();
        let rejection = check_eligibility(&retained, eof).expect_err("line three was unseen");
        assert_eq!(rejection.code, HashlineRejectionCode::UnseenLine);
    }

    #[test]
    fn one_baseline_is_retained_for_every_section_of_a_canonical_path() {
        let mut cache = BaselineCache::default();
        let path = PathBuf::from("/canonical");
        let first = cache
            .load_once(path.clone(), b"before\n".to_vec())
            .bytes
            .clone();
        let second = cache
            .load_once(path.clone(), b"after\n".to_vec())
            .bytes
            .clone();
        assert_eq!(first, b"before\n");
        assert_eq!(second, b"before\n");
        assert_eq!(cache.len(), 1);
    }

    #[test]
    fn anchor_mismatch_is_verification_but_span_mismatch_requests_recovery() {
        let retained = snapshot(b"one\ntwo\nthree\n", [1, 2, 3]);
        let span = resolve_address(&parse_address("2").unwrap(), &retained).unwrap();
        let changed_span = Baseline::from_bytes(b"one\nTWO\nthree\n".to_vec());
        let VerificationOutcome::RecoveryRequired(plan) =
            verify_exact(&retained, &changed_span, span)
        else {
            panic!("addressed record drift must be planned for recovery");
        };
        assert_eq!(plan.old_span, LineSpan { start: 2, end: 2 });

        let gap = resolve_address(&parse_address("<2").unwrap(), &retained).unwrap();
        let changed_anchor = Baseline::from_bytes(b"ONE\ntwo\nthree\n".to_vec());
        let VerificationOutcome::Rejected(rejection) =
            verify_exact(&retained, &changed_anchor, gap)
        else {
            panic!("anchor drift must reject before recovery");
        };
        assert_eq!(rejection.code, HashlineRejectionCode::StaleTag);
        assert_eq!(rejection.stage, RejectionStage::Verification);
    }

    #[test]
    fn exact_verification_compares_terminators_and_unnormalized_bytes() {
        let retained = snapshot(b"one  \r\ntwo\n", [1, 2]);
        let span = resolve_address(&parse_address("1").unwrap(), &retained).unwrap();
        let trailing_space_drift = Baseline::from_bytes(b"one\r\ntwo\n".to_vec());
        assert!(matches!(
            verify_exact(&retained, &trailing_space_drift, span),
            VerificationOutcome::RecoveryRequired(_)
        ));
    }
}