File size: 6,046 Bytes
99fb72f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
//! Invisible Unicode watermark & typographic artifact forensics and pure sanitizer.
//!
//! Law (Idempotence): `forall s, sanitize_text(&sanitize_text(s).cleaned) == sanitize_text(s).cleaned`.

use crate::model::{UnitScore, WatermarkFinding};

/// Aggregated Unicode & typographic forensic metrics for an article.
#[derive(Debug, Clone)]
pub struct WatermarkScan {
    /// Normalized AI artifact signal (`[0.0, 1.0]`).
    pub signal_score: UnitScore,
    /// Count of invisible zero-width or narrow non-breaking spaces removable by sanitizer.
    pub removable_invisible_count: usize,
    /// Density of em-dashes per 1000 non-whitespace characters.
    pub em_dash_per_kchar: f64,
    /// Specific named findings with non-zero counts.
    pub findings: Vec<WatermarkFinding>,
}

/// Output of the pure text sanitizer.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SanitizedOutput {
    /// Cleaned UTF-8 string with invisible watermarks stripped and special spaces normalized.
    pub cleaned: String,
    /// Number of invisible zero-width scalar values removed.
    pub removed_zero_width: usize,
    /// Number of narrow/non-breaking spaces normalized to ASCII `0x20`.
    pub normalized_spaces: usize,
}

/// Semantic predicate: returns `true` if `ch` is an invisible zero-width formatting character
/// frequently injected by LLM web UIs, watermarking schemes, or copy-paste pipelines.
#[must_use]
pub const fn is_zero_width_watermark(ch: char) -> bool {
    matches!(
        ch,
        '\u{200B}' // Zero Width Space (ZWSP)
        | '\u{200C}' // Zero Width Non-Joiner (ZWNJ)
        | '\u{200D}' // Zero Width Joiner (ZWJ)
        | '\u{2060}' // Word Joiner (WJ)
        | '\u{2061}' // Function Application
        | '\u{2062}' // Invisible Times
        | '\u{2063}' // Invisible Separator
        | '\u{2064}' // Invisible Plus
        | '\u{FEFF}' // Zero Width No-Break Space / BOM
        | '\u{00AD}' // Soft Hyphen
    )
}

/// Semantic predicate: returns `true` if `ch` is an unusual non-ASCII space (`U+202F` NNBSP,
/// `U+00A0` NBSP, `U+2007` Figure Space, `U+2009` Thin Space) often emitted by frontier LLMs.
#[must_use]
pub const fn is_atypical_llm_space(ch: char) -> bool {
    matches!(
        ch,
        '\u{202F}' | '\u{00A0}' | '\u{2007}' | '\u{2009}' | '\u{200A}'
    )
}

/// Scans UTF-8 prose for invisible Unicode watermarks and LLM typographic habits.
#[must_use]
pub fn scan_watermarks(text: &str, non_ws_chars: usize) -> WatermarkScan {
    let mut zwsp = 0usize;
    let mut zwnj_zwj = 0usize;
    let mut word_joiner_bom = 0usize;
    let mut nnbsp = 0usize;
    let mut nbsp = 0usize;
    let mut em_dashes = 0usize;

    for ch in text.chars() {
        match ch {
            '\u{200B}' | '\u{00AD}' => zwsp = zwsp.saturating_add(1),
            '\u{200C}' | '\u{200D}' => zwnj_zwj = zwnj_zwj.saturating_add(1),
            '\u{2060}' | '\u{2061}' | '\u{2062}' | '\u{2063}' | '\u{2064}' | '\u{FEFF}' => {
                word_joiner_bom = word_joiner_bom.saturating_add(1);
            }
            '\u{202F}' => nnbsp = nnbsp.saturating_add(1),
            '\u{00A0}' | '\u{2007}' | '\u{2009}' | '\u{200A}' => nbsp = nbsp.saturating_add(1),
            '—' => em_dashes = em_dashes.saturating_add(1),
            _ => {}
        }
    }

    let mut findings = Vec::new();
    if zwsp > 0 {
        findings.push(WatermarkFinding {
            code: "U+200B",
            label: "Zero-Width Space / Soft Hyphen Watermark",
            count: zwsp,
        });
    }
    if nnbsp > 0 {
        findings.push(WatermarkFinding {
            code: "U+202F",
            label: "Narrow No-Break Space (LLM Tokenizer Signature)",
            count: nnbsp,
        });
    }
    if word_joiner_bom > 0 {
        findings.push(WatermarkFinding {
            code: "U+2060",
            label: "Invisible Word Joiner / Inline BOM",
            count: word_joiner_bom,
        });
    }
    if zwnj_zwj > 0 {
        findings.push(WatermarkFinding {
            code: "U+200C/D",
            label: "Zero-Width Joiner / Non-Joiner Sequence",
            count: zwnj_zwj,
        });
    }
    if nbsp > 0 {
        findings.push(WatermarkFinding {
            code: "U+00A0",
            label: "Non-Breaking / Thin Typographic Space",
            count: nbsp,
        });
    }

    let denom = (non_ws_chars.max(1)) as f64;
    let em_dash_per_kchar = (em_dashes as f64) * 1000.0 / denom;
    if em_dashes >= 3 && em_dash_per_kchar >= 4.5 {
        findings.push(WatermarkFinding {
            code: "U+2014",
            label: "Elevated Em-Dash Parenthetical Density",
            count: em_dashes,
        });
    }

    let invisible_total = zwsp
        .saturating_add(zwnj_zwj)
        .saturating_add(word_joiner_bom)
        .saturating_add(nnbsp);
    let removable_invisible_count = invisible_total.saturating_add(nbsp);

    let zw_component = ((invisible_total as f64) * 0.30).min(0.85);
    let nbsp_component = ((nbsp as f64) * 0.06).min(0.22);

    WatermarkScan {
        signal_score: UnitScore::clamped(zw_component + nbsp_component),
        removable_invisible_count,
        em_dash_per_kchar,
        findings,
    }
}

/// Strips invisible zero-width watermarks and normalizes atypical non-breaking spaces to `' '`.
///
/// Post: `!result.cleaned.chars().any(|c| is_zero_width_watermark(c) || is_atypical_llm_space(c))`.
#[must_use]
pub fn sanitize_text(raw: &str) -> SanitizedOutput {
    let mut cleaned = String::with_capacity(raw.len());
    let mut removed_zero_width = 0usize;
    let mut normalized_spaces = 0usize;

    for ch in raw.chars() {
        if is_zero_width_watermark(ch) {
            removed_zero_width = removed_zero_width.saturating_add(1);
        } else if is_atypical_llm_space(ch) {
            normalized_spaces = normalized_spaces.saturating_add(1);
            cleaned.push(' ');
        } else {
            cleaned.push(ch);
        }
    }

    SanitizedOutput {
        cleaned,
        removed_zero_width,
        normalized_spaces,
    }
}