blackline 0.4.2

Agent-first CLI for DOCX / XLSX / PPTX
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
//! Snap model ops onto text that actually exists in the paragraph.
//!
//! Phi-3 concatenates several `N|` lines into one `old` and copies the
//! prompt ellipsis. Apply then fails with `text "…" not found`. Each
//! ` | `-joined span becomes its own replace, using the document's spelling.

use std::collections::BTreeSet;

use blackline_core::textutil::find_normalized_ci;

use super::plan::{Op, Plan, Position};

/// Rewrite replace ops so `old` is a substring of a real paragraph.
pub(crate) fn snap_plan(plan: &mut Plan, lines: &[String]) {
    let mut out = Vec::with_capacity(plan.ops.len());
    let mut claimed = BTreeSet::new();
    for op in std::mem::take(&mut plan.ops) {
        match op {
            Op::Replace { index, old, new } => {
                out.extend(expand_replace(lines, index, &old, &new, &mut claimed));
            }
            Op::Insert {
                index,
                position,
                text,
            } => {
                if let Some(op) = snap_insert(lines, index, position, text, &mut claimed) {
                    out.push(op);
                }
            }
            other => out.push(other),
        }
    }
    plan.ops = out;
}

/// A Word table is one view index whose prompt text joins cells with ` | `.
/// Several replaces on that index are valid; a leftover op with the wrong
/// paragraph number is not.
fn expand_replace(
    lines: &[String],
    index: u32,
    old: &str,
    new: &str,
    claimed: &mut BTreeSet<(u32, String)>,
) -> Vec<Op> {
    let old_clean = strip_prompt_junk(old);
    let new_clean = strip_prompt_junk(new);
    if old_clean.is_empty() {
        return Vec::new();
    }
    let old_parts = split_mashed(&old_clean);
    if old_parts.is_empty() {
        return Vec::new();
    }
    let new_parts = split_mashed(&new_clean);
    let mut ops = Vec::new();
    let mut cursor = index;
    for (i, part) in old_parts.iter().enumerate() {
        let model_new = new_parts.get(i).map(String::as_str).unwrap_or("");
        for needle in needles_for_part(lines, cursor, part) {
            let Some((idx, actual, rewritten)) = snap_replace(lines, cursor, &needle, model_new)
            else {
                continue;
            };
            if actual.trim().is_empty() {
                continue;
            }
            let key = (idx, actual.to_lowercase());
            if !claimed.insert(key) {
                continue;
            }
            ops.push(Op::Replace {
                index: idx,
                old: actual,
                new: rewritten,
            });
            cursor = idx;
        }
    }
    ops
}

fn needles_for_part(lines: &[String], index: u32, part: &str) -> Vec<String> {
    if part.chars().count() < 2 {
        return Vec::new();
    }
    if locate(lines, index, part).is_some() {
        return vec![part.to_string()];
    }
    let bits: Vec<String> = part
        .split(" / ")
        .map(strip_prompt_junk)
        .filter(|s| s.chars().count() >= 2)
        .collect();
    if bits.len() > 1 {
        bits
    } else {
        vec![part.to_string()]
    }
}

fn split_mashed(s: &str) -> Vec<String> {
    s.split(" | ")
        .map(strip_prompt_junk)
        .filter(|p| p.chars().count() >= 2)
        .collect()
}

/// Phi-3 often emits `insert` after a line instead of `replace`. Track
/// `before`/`after` then dies (`needs match`).
/// A same-length n-gram that shares the last word becomes a replace
/// (`thirty days` → `sixty days`), including a prefix of a mashed insert
/// (`sixty days of invoice date`) and a hit on a neighbor line. A short
/// leftover phrase with no swap is dropped so it does not glue onto the
/// previous clause. A real sentence still inserts at `end`.
fn snap_insert(
    lines: &[String],
    index: u32,
    position: Position,
    text: String,
    claimed: &mut BTreeSet<(u32, String)>,
) -> Option<Op> {
    let text = strip_prompt_junk(&text);
    if let Some((idx, old, new)) = all_caps_insert_as_replace(lines, index, &text) {
        let key = (idx, old.to_lowercase());
        if !claimed.insert(key) {
            return None;
        }
        return Some(Op::Replace {
            index: idx,
            old,
            new,
        });
    }
    if let Some((idx, old, new)) = insert_as_replace(lines, index, &text, claimed) {
        let key = (idx, old.to_lowercase());
        if !claimed.insert(key) {
            return None;
        }
        return Some(Op::Replace {
            index: idx,
            old,
            new,
        });
    }
    if is_short_leftover_phrase(&text) {
        return None;
    }
    let position = match position {
        Position::Before | Position::After => Position::End,
        other => other,
    };
    Some(Op::Insert {
        index,
        position,
        text,
    })
}

fn insert_as_replace(
    lines: &[String],
    index: u32,
    text: &str,
    claimed: &BTreeSet<(u32, String)>,
) -> Option<(u32, String, String)> {
    let words: Vec<&str> = text.split_whitespace().collect();
    if words.len() < 2 {
        return None;
    }
    for n in (2..=words.len()).rev() {
        let last = words[n - 1];
        if !contentful_word(last) {
            continue;
        }
        let prefix = words[..n]
            .join(" ")
            .trim_end_matches(|c: char| !c.is_alphanumeric())
            .to_string();
        if let Some((idx, old)) = find_swap_ngram(lines, index, n, last, &prefix, claimed) {
            return Some((idx, old, prefix));
        }
    }
    None
}

fn index_claimed(claimed: &BTreeSet<(u32, String)>, idx: u32) -> bool {
    claimed.iter().any(|(i, _)| *i == idx)
}

/// Target line, later lines, then the previous line. Do not wrap to
/// article 1 — that retargets a clause another op already changed.
fn find_swap_ngram(
    lines: &[String],
    index: u32,
    n: usize,
    last: &str,
    new_phrase: &str,
    claimed: &BTreeSet<(u32, String)>,
) -> Option<(u32, String)> {
    let start = usize::try_from(index.saturating_sub(1)).unwrap_or(0);
    let prev = start.checked_sub(1).into_iter();
    for i in std::iter::once(start)
        .chain(start.saturating_add(1)..lines.len())
        .chain(prev)
    {
        let idx = u32::try_from(i.saturating_add(1)).ok()?;
        if index_claimed(claimed, idx) {
            continue;
        }
        if let Some(old) = ngram_sharing_last(line_body(&lines[i]), n, last, new_phrase) {
            if old.contains(" | ") {
                continue;
            }
            return Some((idx, old));
        }
    }
    None
}

fn ngram_sharing_last(body: &str, n: usize, last: &str, new_phrase: &str) -> Option<String> {
    let line_words: Vec<&str> = body.split_whitespace().collect();
    let last_key = word_key(last);
    for window in line_words.windows(n) {
        if word_key(window.last()?) != last_key {
            continue;
        }
        let old = window
            .join(" ")
            .trim_end_matches(|c: char| !c.is_alphanumeric())
            .to_string();
        if word_key(&old) == word_key(new_phrase) {
            continue;
        }
        return Some(old);
    }
    None
}

fn word_key(s: &str) -> String {
    s.chars()
        .filter(|c| c.is_alphanumeric() || c.is_whitespace())
        .flat_map(char::to_lowercase)
        .collect()
}

fn is_short_leftover_phrase(text: &str) -> bool {
    let t = text.trim();
    let words: Vec<&str> = t.split_whitespace().collect();
    if words.is_empty() || words.len() > 6 {
        return false;
    }
    let core = t.trim_end_matches(['.', '?', '!']).trim();
    if core.contains(['.', '?', '!']) {
        return false;
    }
    let starts_capital = words[0].chars().next().is_some_and(|c| c.is_uppercase());
    let ends_sentence = t.ends_with(['.', '?', '!']);
    !(starts_capital && ends_sentence)
}

fn contentful_word(word: &str) -> bool {
    word_key(word).chars().count() >= 4
}

/// All-caps insert of a sentence is Phi-3 doing `all caps first` as a
/// duplicate paragraph. Promote it to a first-word replace on the target
/// line so the original clause is not appended in caps.
fn all_caps_insert_as_replace(
    lines: &[String],
    index: u32,
    text: &str,
) -> Option<(u32, String, String)> {
    if !is_all_caps_text(text) {
        return None;
    }
    let i = usize::try_from(index).ok()?.checked_sub(1)?;
    let first = first_word(line_body(lines.get(i)?))?;
    if first.is_empty() {
        return None;
    }
    Some((index, first.clone(), first.to_uppercase()))
}

fn is_all_caps_text(s: &str) -> bool {
    let mut without_placeholders = String::new();
    let mut in_brackets = false;
    for c in s.chars() {
        match c {
            '[' => in_brackets = true,
            ']' => in_brackets = false,
            _ if !in_brackets => without_placeholders.push(c),
            _ => {}
        }
    }
    let letters: String = without_placeholders
        .chars()
        .filter(|c| c.is_alphabetic())
        .collect();
    !letters.is_empty() && letters.chars().all(|c| c.is_uppercase())
}

fn first_word(s: &str) -> Option<String> {
    let raw = s.split_whitespace().next()?;
    let trimmed = raw.trim_end_matches(|c: char| !c.is_alphanumeric());
    if trimmed.is_empty() {
        None
    } else {
        Some(trimmed.to_string())
    }
}

fn snap_replace(
    lines: &[String],
    index: u32,
    old: &str,
    new: &str,
) -> Option<(u32, String, String)> {
    let cleaned = strip_prompt_junk(old);
    let segment = cleaned.split(" | ").next().unwrap_or(&cleaned).trim();
    let needle = leading_label(segment);
    if needle.chars().count() < 2 {
        return None;
    }
    let (idx, actual) = locate(lines, index, &needle)?;
    let new = rewrite_new(&actual, new);
    Some((idx, actual, new))
}

/// Fill-in tails (`Services: [Name …]`) are not a stable `old`.
fn leading_label(s: &str) -> String {
    if let Some(i) = s.find('[') {
        let head = s[..i].trim();
        if head.chars().count() >= 2 {
            return head.to_string();
        }
    }
    s.to_string()
}

/// How far a mashed `Customer: | Contact:` replace may walk.
const LOCATE_FORWARD: usize = 8;
const LOCATE_BACK: usize = 2;

fn locate(lines: &[String], index: u32, needle: &str) -> Option<(u32, String)> {
    if let Some(i) = usize::try_from(index).ok().and_then(|n| n.checked_sub(1)) {
        if let Some(line) = lines.get(i) {
            if let Some(matched) = match_in(line_body(line), needle) {
                return Some((index, matched));
            }
        }
    }
    let start = usize::try_from(index.saturating_sub(1)).unwrap_or(0);
    let lo = start.saturating_sub(LOCATE_BACK);
    let hi = start
        .saturating_add(LOCATE_FORWARD)
        .min(lines.len().saturating_sub(1));
    for i in (start.saturating_add(1)..=hi).chain(lo..start) {
        if let Some(matched) = match_in(line_body(&lines[i]), needle) {
            let idx = u32::try_from(i.saturating_add(1)).ok()?;
            return Some((idx, matched));
        }
    }
    None
}

fn match_in(haystack: &str, needle: &str) -> Option<String> {
    find_normalized_ci(haystack, needle).map(|(_, matched)| matched)
}

fn rewrite_new(actual_old: &str, model_new: &str) -> String {
    let n = strip_prompt_junk(model_new);
    let n = n.split(" | ").next().unwrap_or(&n).trim();
    let letters: String = n.chars().filter(|c| c.is_alphabetic()).collect();
    if !letters.is_empty() && letters.chars().all(|c| c.is_uppercase()) {
        return actual_old.to_uppercase();
    }
    if n.eq_ignore_ascii_case(actual_old) {
        return n.to_string();
    }
    n.to_string()
}

fn strip_prompt_junk(s: &str) -> String {
    s.trim()
        .trim_end_matches('…')
        .trim_end_matches("...")
        .trim_end_matches('_')
        .trim()
        .to_string()
}

/// Numbered view prefix `12| text`. A pipe inside the paragraph (`Address: |`)
/// must stay; apply snaps against `text_lines()`, not the prompt.
fn line_body(line: &str) -> &str {
    let digits = line.chars().take_while(|c| c.is_ascii_digit()).count();
    if digits == 0 {
        return line;
    }
    let rest = line.get(digits..).unwrap_or("");
    let rest = rest
        .strip_prefix("| ")
        .or_else(|| rest.strip_prefix('|'))
        .unwrap_or(line);
    strip_heading_prefix(rest)
}

/// `bl docx view` prints `H1: ` in front of a heading. That prefix is
/// not in the paragraph, so a copied `old` of `H1:` must not be kept.
fn strip_heading_prefix(s: &str) -> &str {
    let t = s.trim_start();
    let b = t.as_bytes();
    if b.len() >= 4 && b[0] == b'H' && b[1].is_ascii_digit() && b[2] == b':' && b[3] == b' ' {
        return t.get(4..).unwrap_or(t);
    }
    t
}

#[cfg(test)]
mod tests {
    use super::{line_body, snap_plan, snap_replace};
    use crate::ai::plan::{Op, Plan, Position};

    fn numbered() -> Vec<String> {
        vec![
            "1| SaaS Services Order Form".into(),
            "2| Customer:".into(),
            "3| Contact:".into(),
            "4| Address:".into(),
        ]
    }

    /// Same shape as `Docx::text_lines()` — no `N|` prefix, pipes are content.
    fn apply_lines() -> Vec<String> {
        vec![
            "SaaS Services Order Form".into(),
            "Customer:".into(),
            "Contact: /".into(),
            "Address: |".into(),
            "Phone: / E-Mail: /".into(),
            "Services: [Name and briefly describe services here]".into(),
        ]
    }

    fn replace_triples(plan: &Plan) -> Vec<(u32, String, String)> {
        plan.ops
            .iter()
            .filter_map(|op| match op {
                Op::Replace { index, old, new } => Some((*index, old.clone(), new.clone())),
                _ => None,
            })
            .collect()
    }

    #[test]
    fn mashed_pipe_lines_snap_to_the_first_field() {
        let (idx, old, new) = snap_replace(
            &numbered(),
            1,
            "Customer: | Contact: / Address: | Phone: ____…",
            "CUSTOMER: | CONTACT: / ADDRESS: | PHONE: ____…",
        )
        .unwrap();
        assert_eq!(idx, 2);
        assert_eq!(old, "Customer:");
        assert_eq!(new, "CUSTOMER:");
    }

    #[test]
    fn all_caps_uses_document_spelling() {
        let (_, old, new) = snap_replace(
            &numbered(),
            1,
            "saas services order form",
            "SAAS SERVICES ORDER FORM",
        )
        .unwrap();
        assert_eq!(old, "SaaS Services Order Form");
        assert_eq!(new, "SAAS SERVICES ORDER FORM");
    }

    #[test]
    fn numbered_prefix_is_stripped_document_pipe_is_not() {
        assert_eq!(line_body("2| Customer:"), "Customer:");
        assert_eq!(
            line_body("1| H1: SaaS Services Order Form"),
            "SaaS Services Order Form"
        );
        assert_eq!(line_body("Address: |"), "Address: |");
        assert_eq!(line_body("Customer:"), "Customer:");
    }

    #[test]
    fn mashed_yc_header_expands_to_each_paragraph() {
        let mut plan = Plan {
            ops: vec![Op::Replace {
                index: 1,
                old: "Customer: | Contact: / Address: | Phone: / E-Mail: / Services: [Name and briefly describe services here] ____…".into(),
                new: "CUSTOMER: | CONTACT: / ADDRESS: | PHONE: / E-MAIL: / SERVICES: [NAME AND BRIEFLY DESCRIBE SERVICES HERE] ____…".into(),
            }],
        };
        snap_plan(&mut plan, &apply_lines());
        assert_eq!(
            replace_triples(&plan),
            vec![
                (2, "Customer:".into(), "CUSTOMER:".into()),
                (3, "Contact:".into(), "CONTACT:".into()),
                (4, "Address:".into(), "ADDRESS:".into()),
                (5, "Phone:".into(), "PHONE:".into()),
                (5, "E-Mail:".into(), "E-MAIL:".into()),
                (6, "Services:".into(), "SERVICES:".into()),
            ]
        );
    }

    #[test]
    fn snap_plan_expands_mashed_numbered_lines() {
        let mut plan = Plan {
            ops: vec![Op::Replace {
                index: 1,
                old: "Customer: | Contact: …".into(),
                new: "CUSTOMER: | CONTACT: …".into(),
            }],
        };
        snap_plan(&mut plan, &numbered());
        assert_eq!(
            replace_triples(&plan),
            vec![
                (2, "Customer:".into(), "CUSTOMER:".into()),
                (3, "Contact:".into(), "CONTACT:".into()),
            ]
        );
    }

    /// YC header is one `w:tbl` (one view index). Phi-3 still emits
    /// `Contact:` against the next paragraph; that leftover must drop.
    #[test]
    fn table_row_keeps_each_field_and_drops_wrong_index() {
        let table = "Customer: | Contact: / | Address: | Phone: / E-Mail: / | Services: [Name]";
        let lines = vec![
            "SaaS Services Order Form".into(),
            table.into(),
            "This SaaS Services Agreement is entered into".into(),
        ];
        let mut plan = Plan {
            ops: vec![
                Op::Replace {
                    index: 2,
                    old: "Customer: | Contact: / Address: | Phone: ____…".into(),
                    new: "CUSTOMER: | CONTACT: / ADDRESS: | PHONE: ____…".into(),
                },
                Op::Replace {
                    index: 3,
                    old: "Contact:".into(),
                    new: "CONTACT:".into(),
                },
            ],
        };
        snap_plan(&mut plan, &lines);
        assert_eq!(
            replace_triples(&plan),
            vec![
                (2, "Customer:".into(), "CUSTOMER:".into()),
                (2, "Contact:".into(), "CONTACT:".into()),
                (2, "Address:".into(), "ADDRESS:".into()),
                (2, "Phone:".into(), "PHONE:".into()),
            ]
        );
    }

    #[test]
    fn insert_after_swaps_a_same_length_phrase() {
        let lines = vec!["Fees are due within thirty days of invoice date.".into()];
        let mut plan = Plan {
            ops: vec![Op::Insert {
                index: 1,
                position: Position::After,
                text: "sixty days".into(),
            }],
        };
        snap_plan(&mut plan, &lines);
        assert_eq!(
            replace_triples(&plan),
            vec![(1, "thirty days".into(), "sixty days".into())]
        );
    }

    #[test]
    fn insert_after_without_a_swap_moves_to_end() {
        let lines = vec!["Fees are due within thirty days of invoice date.".into()];
        let mut plan = Plan {
            ops: vec![Op::Insert {
                index: 1,
                position: Position::After,
                text: "See Exhibit A.".into(),
            }],
        };
        snap_plan(&mut plan, &lines);
        match &plan.ops[..] {
            [Op::Insert {
                index: 1,
                position: Position::End,
                text,
            }] => assert_eq!(text, "See Exhibit A."),
            other => panic!("expected insert at end, got {other:?}"),
        }
    }

    #[test]
    fn mashed_insert_uses_a_prefix_swap() {
        let lines = vec!["Either party may terminate after thirty days notice.".into()];
        let mut plan = Plan {
            ops: vec![Op::Insert {
                index: 1,
                position: Position::After,
                text: "sixty days of invoice date".into(),
            }],
        };
        snap_plan(&mut plan, &lines);
        assert_eq!(
            replace_triples(&plan),
            vec![(1, "thirty days".into(), "sixty days".into())]
        );
    }

    #[test]
    fn leftover_insert_on_a_neighbor_swaps_the_next_line() {
        let lines = vec![
            "Provider shall implement commercially reasonable security measures.".into(),
            "Either party may terminate after thirty days notice.".into(),
        ];
        let mut plan = Plan {
            ops: vec![Op::Insert {
                index: 1,
                position: Position::After,
                text: "sixty days notice".into(),
            }],
        };
        snap_plan(&mut plan, &lines);
        assert_eq!(
            replace_triples(&plan),
            vec![(2, "thirty days notice".into(), "sixty days notice".into())]
        );
    }

    #[test]
    fn insert_does_not_wrap_onto_a_claimed_early_clause() {
        let lines = vec![
            "Either party may terminate after thirty days notice.".into(),
            "Fees are due within thirty days of invoice.".into(),
            "Limitation of liability shall not exceed fees paid.".into(),
        ];
        let mut plan = Plan {
            ops: vec![
                Op::Replace {
                    index: 1,
                    old: "thirty".into(),
                    new: "sixty".into(),
                },
                Op::Insert {
                    index: 3,
                    position: Position::After,
                    text: "sixty days notice.".into(),
                },
            ],
        };
        snap_plan(&mut plan, &lines);
        let triples = replace_triples(&plan);
        assert_eq!(triples[0], (1, "thirty".into(), "sixty".into()));
        assert!(
            !triples
                .iter()
                .any(|(i, old, _)| *i == 1 && old.contains("notice")),
            "wrapped onto the already-claimed first clause: {triples:?}"
        );
    }

    #[test]
    fn short_leftover_insert_with_no_swap_is_dropped() {
        let lines = vec!["Limitation of liability shall not exceed fees paid.".into()];
        let mut plan = Plan {
            ops: vec![Op::Insert {
                index: 1,
                position: Position::After,
                text: "sixty days notice.".into(),
            }],
        };
        snap_plan(&mut plan, &lines);
        assert!(plan.ops.is_empty(), "{:?}", plan.ops);
    }

    #[test]
    fn mashed_of_suffix_does_not_rewrite_unrelated_claims() {
        let lines = vec![
            "Indemnity covers third-party claims of intellectual property infringement.".into(),
        ];
        let mut plan = Plan {
            ops: vec![Op::Insert {
                index: 1,
                position: Position::After,
                text: "sixty days of invoice date.".into(),
            }],
        };
        snap_plan(&mut plan, &lines);
        assert!(plan.ops.is_empty(), "{:?}", plan.ops);
    }

    #[test]
    fn replace_does_not_walk_to_a_far_article() {
        let mut lines = vec!["Export controls apply to all software and technical data.".into()];
        lines.extend(std::iter::repeat_n(
            "Unrelated clause without the needle.".into(),
            20,
        ));
        lines.push("Export controls apply to all software and technical data.".into());
        let mut plan = Plan {
            ops: vec![Op::Replace {
                index: 5,
                old: "Export controls apply to all software and technical data.".into(),
                new: "EXPORT CONTROLS APPLY TO ALL SOFTWARE AND TECHNICAL DATA.".into(),
            }],
        };
        snap_plan(&mut plan, &lines);
        assert!(
            !replace_triples(&plan).iter().any(|(i, _, _)| *i >= 20),
            "walked to a far article: {:?}",
            replace_triples(&plan)
        );
    }

    #[test]
    fn whitespace_only_old_is_dropped() {
        let lines = vec!["Limitation of liability.".into()];
        let mut plan = Plan {
            ops: vec![
                Op::Replace {
                    index: 1,
                    old: "    ".into(),
                    new: "H3: LIMITATION OF LIABILITY".into(),
                },
                Op::Replace {
                    index: 1,
                    old: "Limitation of liability.".into(),
                    new: "LIMITATION OF LIABILITY.".into(),
                },
            ],
        };
        snap_plan(&mut plan, &lines);
        assert_eq!(
            replace_triples(&plan),
            vec![(
                1,
                "Limitation of liability.".into(),
                "LIMITATION OF LIABILITY.".into()
            )]
        );
    }

    #[test]
    fn view_heading_prefix_replace_is_dropped() {
        let lines = vec!["1| H1: SaaS Services Order Form".into()];
        let mut plan = Plan {
            ops: vec![Op::Replace {
                index: 1,
                old: "H1:".into(),
                new: "H1:".into(),
            }],
        };
        snap_plan(&mut plan, &lines);
        assert!(plan.ops.is_empty(), "{:?}", plan.ops);
    }

    #[test]
    fn all_caps_insert_ignores_placeholder_brackets() {
        let lines = vec!["Customer: | [Name] / Contact: | / / Address: |".into()];
        let mut plan = Plan {
            ops: vec![Op::Insert {
                index: 1,
                position: Position::Before,
                text: "CUSTOMER: [Name] / CONTACT: / / ADDRESS: /".into(),
            }],
        };
        snap_plan(&mut plan, &lines);
        assert_eq!(
            replace_triples(&plan),
            vec![(1, "Customer".into(), "CUSTOMER".into())]
        );
    }

    #[test]
    fn all_caps_insert_becomes_first_word_replace() {
        let lines = vec!["Indemnity covers third-party claims.".into()];
        let mut plan = Plan {
            ops: vec![Op::Insert {
                index: 1,
                position: Position::After,
                text: "INDEMNITY COVERS THIRD-PARTY CLAIMS.".into(),
            }],
        };
        snap_plan(&mut plan, &lines);
        assert_eq!(
            replace_triples(&plan),
            vec![(1, "Indemnity".into(), "INDEMNITY".into())]
        );
    }
}