agent-doc-core 0.34.65

Pure document data layer for agent-doc (component parsing, frontmatter, template, CRDT, pending, diff classification, model tier)
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
//! Extracted from `write.rs` (large-module split). See parent module for context.

use super::*;

pub fn remove_post_exchange_duplicate_prompt_comments(doc: &str) -> Option<String> {
    remove_post_exchange_duplicate_prompt_comments_preserving_docs(doc, &[])
}

/// Like `remove_post_exchange_duplicate_prompt_comments`, but keeps duplicate-
/// looking comment lines that were already present in `preserve_doc`.
///
/// Closeout, route, and preflight use this as an ownership proof: stale
/// duplicate residue created during the current response cycle can be scrubbed,
/// while pre-existing scratch comments below `agent:exchange` remain user-owned.
pub fn remove_post_exchange_duplicate_prompt_comments_preserving(
    doc: &str,
    preserve_doc: Option<&str>,
) -> Option<String> {
    match preserve_doc {
        Some(preserve_doc) => {
            remove_post_exchange_duplicate_prompt_comments_preserving_docs(doc, &[preserve_doc])
        }
        None => remove_post_exchange_duplicate_prompt_comments_preserving_docs(doc, &[]),
    }
}

/// Like `remove_post_exchange_duplicate_prompt_comments_preserving`, but accepts
/// several ownership-proof documents and preserves the union of their ordinary
/// post-exchange comment lines.
pub fn remove_post_exchange_duplicate_prompt_comments_preserving_docs(
    doc: &str,
    preserve_docs: &[&str],
) -> Option<String> {
    let components = component::parse(doc).ok()?;
    let exchange = components
        .iter()
        .find(|component| component.name == "exchange")?;
    let prompts = exchange_prompt_comment_targets(exchange.content(doc));
    if prompts.is_empty() {
        return None;
    }

    let protected_ranges = components
        .iter()
        .filter(|component| component.name != "exchange")
        .map(|component| (component.open_start, component.close_end))
        .collect::<Vec<_>>();
    let mut preserved_comment_lines = HashSet::new();
    for preserve_doc in preserve_docs {
        preserved_comment_lines.extend(post_exchange_comment_line_preserve_set(preserve_doc));
    }

    let mut replacements = Vec::<(usize, usize, String)>::new();
    for (start, end) in component::find_non_agent_html_comment_ranges(doc) {
        if start < exchange.close_end {
            continue;
        }
        if protected_ranges
            .iter()
            .any(|(protected_start, protected_end)| {
                start >= *protected_start && end <= *protected_end
            })
        {
            continue;
        }
        let original = &doc[start..end];
        if !original.ends_with("-->") {
            continue;
        }
        let body = &doc[start + 4..end - 3];
        let Some(cleaned_body) =
            strip_duplicate_prompt_comment_body(body, &prompts, &preserved_comment_lines)
        else {
            replacements.push((start, end, empty_html_comment_like(body)));
            continue;
        };
        if cleaned_body != body {
            replacements.push((start, end, format!("<!--{}-->", cleaned_body)));
        }
    }

    if replacements.is_empty() {
        return None;
    }

    let mut cleaned = doc.to_string();
    for (start, end, replacement) in replacements.into_iter().rev() {
        cleaned.replace_range(start..end, &replacement);
    }
    Some(cleaned)
}

pub(crate) fn post_exchange_comment_line_preserve_set(doc: &str) -> HashSet<String> {
    let Ok(components) = component::parse(doc) else {
        return HashSet::new();
    };
    let Some(exchange) = components
        .iter()
        .find(|component| component.name == "exchange")
    else {
        return HashSet::new();
    };
    let protected_ranges = components
        .iter()
        .filter(|component| component.name != "exchange")
        .map(|component| (component.open_start, component.close_end))
        .collect::<Vec<_>>();

    let mut preserved = HashSet::new();
    for (start, end) in component::find_non_agent_html_comment_ranges(doc) {
        if start < exchange.close_end {
            continue;
        }
        if protected_ranges
            .iter()
            .any(|(protected_start, protected_end)| {
                start >= *protected_start && end <= *protected_end
            })
        {
            continue;
        }
        let original = &doc[start..end];
        if !original.ends_with("-->") {
            continue;
        }
        let body = &doc[start + 4..end - 3];
        for line in comment_body_lines(body) {
            if let Some(normalized) = normalize_prompt_comment_text(line) {
                preserved.insert(normalized);
            }
        }
    }
    preserved
}

/// Remove a prompt tail after the latest exchange boundary when that tail is an
/// exact duplicate of a prompt block already answered earlier in the exchange.
///
/// This covers delayed route/editor replay that re-adds the just-answered
/// prompt after closeout. The cleanup is intentionally narrow: every
/// non-comment tail line must (a) carry the `❯ ` answered-form marker — proof it
/// is a copy of an answered prompt rather than a freshly-typed live prompt — and
/// (b) match a contiguous prompt block immediately before an existing response
/// heading. A bare unprefixed post-boundary prompt is always preserved.
pub fn remove_duplicate_answered_exchange_prompt_tail(doc: &str) -> Option<String> {
    let components = component::parse(doc).ok()?;
    let exchange = components
        .iter()
        .find(|component| component.name == "exchange")?;
    let exchange_content = exchange.content(doc);
    let duplicate_start = duplicate_answered_exchange_prompt_tail_start(exchange_content)?;

    let mut cleaned_exchange = exchange_content[..duplicate_start].to_string();
    if !cleaned_exchange.ends_with('\n') {
        cleaned_exchange.push('\n');
    }
    Some(exchange.replace_content(doc, &cleaned_exchange))
}

pub(crate) fn duplicate_answered_exchange_prompt_tail_start(exchange: &str) -> Option<usize> {
    let lines = exchange_line_spans(exchange);
    let boundary_idx = lines
        .iter()
        .rposition(|(_, _, line)| line.trim().starts_with("<!-- agent:boundary:"))?;
    let tail_start = lines
        .get(boundary_idx)
        .map(|(_, end, _)| *end)
        .unwrap_or(exchange.len());
    let tail = duplicate_exchange_tail_prompt_lines(&lines[boundary_idx + 1..])?;
    if answered_exchange_prompt_blocks_before_boundary(&lines, boundary_idx)
        .into_iter()
        .any(|block| block == tail)
    {
        Some(tail_start)
    } else {
        None
    }
}

pub(crate) fn exchange_line_spans(text: &str) -> Vec<(usize, usize, &str)> {
    let mut spans = Vec::new();
    let mut offset = 0usize;
    for segment in text.split_inclusive('\n') {
        let start = offset;
        offset += segment.len();
        spans.push((start, offset, segment));
    }
    if spans.is_empty() && !text.is_empty() {
        spans.push((0, text.len(), text));
    }
    spans
}

pub(crate) fn duplicate_exchange_tail_prompt_lines(
    lines: &[(usize, usize, &str)],
) -> Option<Vec<String>> {
    let mut prompt_lines = Vec::new();
    for (_, _, line) in lines {
        let trimmed = line.trim();
        if trimmed.is_empty() || trimmed.starts_with("<!--") {
            continue;
        }
        if is_exchange_turn_heading(trimmed) {
            return None;
        }
        // Ownership proof: only an answered-form line (carrying the `❯ ` prompt
        // marker) can be delayed-replay residue, because the marker is added by
        // the answer/normalize cycle, never by a user typing a fresh prompt. A
        // bare, unprefixed post-boundary line is a LIVE prompt the user just
        // typed — even when its text matches a previously-answered prompt (e.g.
        // a re-typed "go"/"yes"/"continue") — and must never be scrubbed.
        // Without this guard the text-only match silently ate live prompts
        // (#ipcfullprompt-recur: "go" on monsterrodholders.md).
        if !trimmed.starts_with('❯') {
            return None;
        }
        prompt_lines.push(normalize_duplicate_exchange_prompt_line(trimmed)?);
    }
    if prompt_lines.is_empty() {
        None
    } else {
        Some(prompt_lines)
    }
}

pub(crate) fn answered_exchange_prompt_blocks_before_boundary(
    lines: &[(usize, usize, &str)],
    boundary_idx: usize,
) -> Vec<Vec<String>> {
    let mut blocks = Vec::new();
    for response_idx in 0..boundary_idx {
        if !is_exchange_turn_heading(lines[response_idx].2.trim()) {
            continue;
        }
        let mut block = Vec::new();
        let mut cursor = response_idx;
        while cursor > 0 {
            cursor -= 1;
            let trimmed = lines[cursor].2.trim();
            if trimmed.is_empty() || trimmed.starts_with("<!--") {
                if block.is_empty() {
                    continue;
                }
                break;
            }
            if trimmed.starts_with('❯')
                && let Some(normalized) = normalize_duplicate_exchange_prompt_line(trimmed)
            {
                block.push(normalized);
                continue;
            }
            if block.is_empty()
                && looks_like_prompt_comment_target(trimmed)
                && let Some(normalized) = normalize_duplicate_exchange_prompt_line(trimmed)
            {
                block.push(normalized);
                continue;
            }
            break;
        }
        if !block.is_empty() {
            block.reverse();
            blocks.push(block);
        }
    }
    blocks
}

pub(crate) fn normalize_duplicate_exchange_prompt_line(line: &str) -> Option<String> {
    let unprefixed = line.trim().strip_prefix('❯').unwrap_or(line.trim()).trim();
    let normalized = unprefixed.split_whitespace().collect::<Vec<_>>().join(" ");
    if normalized.is_empty() {
        None
    } else {
        Some(normalized)
    }
}

/// Fail closed when prompt text already recorded in `agent:exchange` still
/// appears as freeform Markdown after the exchange close marker.
///
/// Ordinary post-exchange HTML comments are scrubbed by
/// `remove_post_exchange_duplicate_prompt_comments`; tracked components such as
/// backlog/queue have their own mutation rules. Anything else is ambiguous
/// enough that closeout must not silently commit or dispatch it.
pub fn guard_no_duplicate_prompt_residue_outside_exchange(doc: &str) -> Result<()> {
    let components = match component::parse(doc) {
        Ok(components) => components,
        Err(err)
            if err
                .chain()
                .any(|cause| cause.to_string().contains("without matching open")) =>
        {
            return Ok(());
        }
        Err(err) => return Err(err).context("failed to parse components"),
    };
    let Some(exchange) = components
        .iter()
        .find(|component| component.name == "exchange")
    else {
        return Ok(());
    };
    let prompts = exchange_prompt_comment_targets(exchange.content(doc));
    if prompts.is_empty() {
        return Ok(());
    }

    let protected_ranges = components
        .iter()
        .filter(|component| component.name != "exchange")
        .map(|component| (component.open_start, component.close_end))
        .collect::<Vec<_>>();
    let in_protected_component = |pos: usize| {
        protected_ranges
            .iter()
            .any(|(start, end)| pos >= *start && pos < *end)
    };
    let ordinary_comment_ranges = component::find_non_agent_html_comment_ranges(doc);
    let in_ordinary_comment = |pos: usize| {
        ordinary_comment_ranges
            .iter()
            .any(|(start, end)| pos >= *start && pos < *end)
    };

    let mut offset = 0usize;
    for segment in doc.split_inclusive('\n') {
        let line_start = offset;
        offset += segment.len();
        if line_start < exchange.close_end
            || in_protected_component(line_start)
            || in_ordinary_comment(line_start)
        {
            continue;
        }
        let trimmed = segment.trim();
        if !is_duplicate_prompt_comment_text(trimmed, &prompts) {
            continue;
        }
        anyhow::bail!(
            "duplicate prompt residue outside `<!-- agent:exchange -->`; refusing to commit or dispatch ambiguous Markdown tail. First duplicate line: `{}`",
            trimmed.chars().take(120).collect::<String>()
        );
    }

    Ok(())
}

pub(crate) fn empty_html_comment_like(body: &str) -> String {
    if body.contains('\n') {
        "<!--\n-->".to_string()
    } else {
        "<!-- -->".to_string()
    }
}

pub(crate) fn strip_duplicate_prompt_comment_body(
    body: &str,
    prompts: &[String],
    preserved_comment_lines: &HashSet<String>,
) -> Option<String> {
    if !body.contains('\n') && is_duplicate_prompt_comment_text(body, prompts) {
        if normalized_comment_line_is_preserved(body, preserved_comment_lines) {
            return Some(body.to_string());
        }
        return None;
    }

    let mut changed = false;
    let mut cleaned = String::new();
    for segment in body.split_inclusive('\n') {
        let line = segment.strip_suffix('\n').unwrap_or(segment);
        if is_duplicate_prompt_comment_text(line, prompts) {
            if normalized_comment_line_is_preserved(line, preserved_comment_lines) {
                cleaned.push_str(segment);
                continue;
            }
            changed = true;
            continue;
        }
        cleaned.push_str(segment);
    }

    if !changed {
        return Some(body.to_string());
    }
    if cleaned.trim().is_empty() {
        None
    } else {
        Some(cleaned)
    }
}

pub(crate) fn comment_body_lines(body: &str) -> Vec<&str> {
    if body.contains('\n') {
        body.split_inclusive('\n')
            .map(|segment| segment.strip_suffix('\n').unwrap_or(segment))
            .collect()
    } else {
        vec![body]
    }
}

pub(crate) fn normalized_comment_line_is_preserved(
    line: &str,
    preserved_comment_lines: &HashSet<String>,
) -> bool {
    normalize_prompt_comment_text(line)
        .map(|normalized| preserved_comment_lines.contains(&normalized))
        .unwrap_or(false)
}

pub(crate) fn exchange_prompt_comment_targets(exchange: &str) -> Vec<String> {
    let mut targets = Vec::new();
    let mut seen = HashSet::new();
    let mut in_response_block = false;
    let mut in_fence = false;

    for line in exchange.lines() {
        let trimmed = line.trim();
        if is_fence_delimiter(trimmed) {
            in_fence = !in_fence;
            continue;
        }
        if in_fence {
            continue;
        }
        if trimmed.starts_with("<!-- agent:boundary:") {
            in_response_block = false;
            continue;
        }
        if trimmed.starts_with("### Re:") || trimmed.starts_with("## Assistant") {
            in_response_block = true;
            continue;
        }
        if in_response_block {
            continue;
        }
        let Some(normalized) = normalize_prompt_comment_text(trimmed) else {
            continue;
        };
        if seen.insert(normalized.clone()) {
            targets.push(normalized);
        }
    }

    targets
}

pub(crate) fn looks_like_prompt_comment_target(text: &str) -> bool {
    let trimmed = text.trim();
    let lower = trimmed.to_lowercase();
    trimmed.starts_with('❯')
        || trimmed.contains('#')
        || trimmed.ends_with('?')
        || lower.starts_with("do ")
        || lower.starts_with("fix ")
        || lower.starts_with("run ")
        || lower.starts_with("please ")
        || lower.contains(" spec-test-")
        || lower.contains(" reproduce ")
}

pub(crate) fn normalize_prompt_comment_text(text: &str) -> Option<String> {
    let trimmed = text.trim();
    if trimmed.is_empty()
        || trimmed.starts_with("<!--")
        || trimmed.starts_with("### Re:")
        || trimmed.starts_with("## Assistant")
        || trimmed.starts_with("## User")
        || is_markdown_heading(trimmed)
    {
        return None;
    }
    let unprefixed = trimmed.strip_prefix('❯').unwrap_or(trimmed).trim();
    let collapsed = unprefixed.split_whitespace().collect::<Vec<_>>().join(" ");
    if collapsed.len() < 32 {
        None
    } else {
        Some(collapsed)
    }
}

pub(crate) fn is_markdown_heading(trimmed: &str) -> bool {
    let hashes = trimmed.bytes().take_while(|byte| *byte == b'#').count();
    (1..=6).contains(&hashes) && trimmed.as_bytes().get(hashes) == Some(&b' ')
}

pub(crate) fn is_fence_delimiter(trimmed: &str) -> bool {
    let Some(first) = trimmed.chars().next() else {
        return false;
    };
    if first != '`' && first != '~' {
        return false;
    }
    trimmed.chars().take_while(|ch| *ch == first).count() >= 3
}

pub(crate) fn is_duplicate_prompt_comment_text(candidate: &str, prompts: &[String]) -> bool {
    let Some(candidate) = normalize_prompt_comment_text(candidate) else {
        return false;
    };
    let candidate_lower = candidate.to_lowercase();
    let candidate_tokens = prompt_comment_tokens(&candidate);
    if candidate_tokens.len() < 8 {
        return false;
    }

    prompts.iter().any(|prompt| {
        let prompt_lower = prompt.to_lowercase();
        if candidate_lower == prompt_lower
            || prompt_lower.contains(&candidate_lower)
            || candidate_lower.contains(&prompt_lower)
        {
            return true;
        }

        let prompt_tokens = prompt_comment_tokens(prompt);
        if prompt_tokens.len() < 8 {
            return false;
        }
        ordered_token_coverage(&candidate_tokens, &prompt_tokens) >= 0.85
            || ordered_token_coverage(&prompt_tokens, &candidate_tokens) >= 0.85
    })
}

pub(crate) fn prompt_comment_tokens(text: &str) -> Vec<String> {
    text.split(|ch: char| !ch.is_alphanumeric())
        .filter(|token| !token.is_empty())
        .map(|token| token.to_lowercase())
        .collect()
}

pub(crate) fn ordered_token_coverage(needle: &[String], haystack: &[String]) -> f64 {
    if needle.is_empty() {
        return 0.0;
    }
    let mut matched = 0usize;
    for token in haystack {
        if needle.get(matched).is_some_and(|needle| needle == token) {
            matched += 1;
            if matched == needle.len() {
                break;
            }
        }
    }
    matched as f64 / needle.len() as f64
}

pub(crate) fn is_safe_duplicate_template_scaffold(segment: &str) -> bool {
    let trimmed = segment.trim();
    if trimmed.is_empty() {
        return false;
    }
    if trimmed.contains("### Re:")
        || trimmed.contains("## User")
        || trimmed.contains("## Assistant")
        || trimmed.contains("❯ ")
    {
        return false;
    }

    let has_scaffold_component = trimmed.contains("<!-- agent:queue -->")
        || trimmed.contains("<!-- agent:backlog")
        || trimmed.contains("<!-- agent:pending")
        || trimmed.contains("<!-- agent:done");
    if !has_scaffold_component {
        return false;
    }
    if !duplicate_scaffold_has_only_structural_residue(trimmed) {
        return false;
    }

    let wrapped = format!("<!-- agent:scaffold -->\n{trimmed}\n<!-- /agent:scaffold -->\n");
    let Ok(components) = component::parse(&wrapped) else {
        return false;
    };
    let allowed = ["scaffold", "queue", "backlog", "pending", "icebox", "done"];
    components
        .iter()
        .all(|component| allowed.contains(&component.name.as_str()))
}

pub(crate) fn duplicate_scaffold_has_only_structural_residue(segment: &str) -> bool {
    let mut residue = segment.to_string();
    if let Ok(components) = component::parse(segment) {
        let mut ranges: Vec<(usize, usize)> = components
            .iter()
            .filter(|component| {
                matches!(
                    component.name.as_str(),
                    "queue" | "backlog" | "pending" | "icebox" | "done"
                )
            })
            .map(|component| (component.open_start, component.close_end))
            .collect();
        ranges.sort_by_key(|range| std::cmp::Reverse(range.0));
        for (start, end) in ranges {
            residue.replace_range(start..end, "");
        }
    }

    let residue = strip_html_comments(&residue);
    residue.lines().all(|line| {
        let trimmed = line.trim();
        trimmed.is_empty() || trimmed.starts_with('#')
    })
}

pub(crate) fn strip_html_comments(text: &str) -> String {
    let mut result = String::with_capacity(text.len());
    let mut rest = text;
    loop {
        let Some(start) = rest.find("<!--") else {
            result.push_str(rest);
            break;
        };
        result.push_str(&rest[..start]);
        let after_start = &rest[start + 4..];
        let Some(end) = after_start.find("-->") else {
            break;
        };
        rest = &after_start[end + 3..];
    }
    result
}

#[cfg(test)]
mod tests {
    #![allow(unused_imports)]
    use super::*;
    use std::path::Path;
    use tempfile::TempDir;
    #[test]
    fn guard_no_duplicate_prompt_residue_outside_exchange_rejects_plain_markdown_duplicate() {
        let prompt =
            "Please keep this exact sentence around for duplicate residue coverage in markdown";
        let doc = format!(
            concat!(
                "<!-- agent:exchange patch=append -->\n",
                "❯ {prompt}\n",
                "### Re: duplicate residue — gpt-5\n\n",
                "Answered.\n",
                "<!-- agent:boundary:head -->\n",
                "<!-- /agent:exchange -->\n\n",
                "# Notes\n\n",
                "{prompt}\n"
            ),
            prompt = prompt
        );

        let err = guard_no_duplicate_prompt_residue_outside_exchange(&doc).unwrap_err();

        assert!(
            err.to_string().contains("duplicate prompt residue outside"),
            "unexpected error: {err}"
        );
    }
    #[test]
    fn guard_no_duplicate_prompt_residue_outside_exchange_allows_tracked_components() {
        let prompt =
            "Please keep this exact sentence around for duplicate residue coverage in markdown";
        let doc = format!(
            concat!(
                "<!-- agent:exchange patch=append -->\n",
                "❯ {prompt}\n",
                "### Re: duplicate residue — gpt-5\n\n",
                "Answered.\n",
                "<!-- agent:boundary:head -->\n",
                "<!-- /agent:exchange -->\n\n",
                "<!-- agent:backlog -->\n",
                "{prompt}\n",
                "<!-- /agent:backlog -->\n"
            ),
            prompt = prompt
        );

        guard_no_duplicate_prompt_residue_outside_exchange(&doc).unwrap();
    }
    #[test]
    fn remove_duplicate_answered_tail_scrubs_prefixed_replay_residue() {
        // Answered-form residue (carries `❯ `) re-added below the boundary is
        // safely removable replay residue.
        let doc = concat!(
            "---\nagent_doc_format: template\n---\n\n",
            "<!-- agent:exchange patch=append -->\n",
            "❯ go\n",
            "### Re: go — gpt-5\n\n",
            "Did the thing.\n",
            "<!-- agent:boundary:head -->\n",
            "❯ go\n",
            "<!-- /agent:exchange -->\n",
        );
        let cleaned = remove_duplicate_answered_exchange_prompt_tail(doc)
            .expect("prefixed answered-form residue should be scrubbed");
        assert!(
            !cleaned.contains("head -->\n❯ go"),
            "answered-form residue tail must be removed:\n{cleaned}"
        );
        assert!(
            cleaned.contains("❯ go\n### Re: go"),
            "answered history must be preserved:\n{cleaned}"
        );
    }
    #[test]
    fn remove_duplicate_answered_tail_preserves_unprefixed_live_prompt() {
        // #ipcfullprompt-recur: a freshly-typed prompt (no `❯ `) that matches a
        // previously-answered prompt is a LIVE prompt and must never be scrubbed.
        let doc = concat!(
            "---\nagent_doc_format: template\n---\n\n",
            "<!-- agent:exchange patch=append -->\n",
            "❯ go\n",
            "### Re: go — gpt-5\n\n",
            "Did the thing.\n",
            "<!-- agent:boundary:head -->\n",
            "go\n",
            "<!-- /agent:exchange -->\n",
        );
        assert!(
            remove_duplicate_answered_exchange_prompt_tail(doc).is_none(),
            "a bare re-typed live prompt must be preserved"
        );
    }
}