Skip to main content

talk_core/
cleanup.rs

1/// Cleanup intensity. Plan 3 wires this into the LLM rewrite; deterministic-Light
2/// is the instant, always-present layer.
3#[derive(Clone, Copy, Debug, PartialEq, Eq)]
4pub enum Level { None, Light, Medium, High }
5
6/// Words the GUARD treats as droppable (disfluencies + conversational filler), so a
7/// rewrite that removes them still passes `guard_accepts`.
8///
9/// KNOWN LIMIT (Plan 3 code review): the guard drops these from BOTH sides of its
10/// comparison, so it permits removing a *content* use of you/know/like/so/well/i/
11/// mean anywhere (e.g. `guard_accepts("do you know the way", "do the way")` is
12/// true). This is a moat for an LLM rewriter, not an instruction to remove them.
13/// `deterministic_light` deliberately does NOT strip from this set — see
14/// `LEADING_DISFLUENCIES`.
15const FILLERS: &[&str] = &["um", "uh", "er", "ah", "like", "you", "know", "so", "well", "i", "mean"];
16
17/// The ONLY words `deterministic_light` strips from the phrase start: non-lexical
18/// vocalizations that are never content. The broader `FILLERS` set is NOT used
19/// here — a leading `i`/`you`/`so`/`well`/`like` is almost always a real sentence
20/// opener ("I think…", "You know what…", "So I realized…"), and dropping it
21/// silently rewrites the user's meaning. Restraint wins: when a leading word is a
22/// real dictionary word, keep it.
23const LEADING_DISFLUENCIES: &[&str] = &["um", "uh", "er", "ah", "mm", "hmm", "uhm", "erm", "hm"];
24
25fn content_words(text: &str) -> Vec<String> {
26    text.to_lowercase()
27        .split(|c: char| !c.is_alphanumeric())
28        .filter(|w| !w.is_empty())
29        .filter(|w| !FILLERS.contains(w))
30        .map(|w| w.to_string())
31        .collect()
32}
33
34/// The moat: accept a rewrite only if it preserves every content word from the
35/// input, in order, adding/removing nothing but allowed fillers. Guards *harm*
36/// (a substituted/dropped meaning word) rather than edit *volume*.
37pub fn guard_accepts(input: &str, output: &str) -> bool {
38    content_words(input) == content_words(output)
39}
40
41/// Apply spoken formatting commands deterministically. Padding the input with
42/// spaces lets a command at the phrase start or end match too (the replacements
43/// are space-delimited). Note: back-to-back identical commands ("new line new
44/// line") collapse to one — an accepted Plan-1 edge case.
45pub fn apply_spoken_commands(text: &str) -> String {
46    format!(" {} ", text)
47        .replace(" new paragraph ", "\n\n")
48        .replace(" new line ", "\n")
49        .replace(" period ", ". ")
50        .replace(" comma ", ", ")
51        .trim()
52        .to_string()
53}
54
55/// Find `needle_lower` (lowercase ASCII) in `hay` at word boundaries, returning
56/// a byte offset valid in `hay`. Case-insensitive without lowercasing `hay`, so
57/// the offset never lands mid-codepoint (a prior bug: offsets from a lowercased
58/// copy were sliced against the original and panicked on case-shrinking chars).
59fn find_word_bounded(hay: &str, needle_lower: &str) -> Option<usize> {
60    let hb = hay.as_bytes();
61    let nb = needle_lower.as_bytes();
62    let nlen = nb.len();
63    if nlen == 0 || hb.len() < nlen { return None; }
64    let mut i = 0;
65    while i + nlen <= hb.len() {
66        // ASCII needle bytes can only match ASCII haystack bytes, so a match
67        // always starts/ends on a char boundary.
68        if (0..nlen).all(|k| hb[i + k].to_ascii_lowercase() == nb[k]) {
69            let before_ok = i == 0 || !hb[i - 1].is_ascii_alphanumeric();
70            let after = i + nlen;
71            let after_ok = after == hb.len() || !hb[after].is_ascii_alphanumeric();
72            if before_ok && after_ok { return Some(i); }
73        }
74        i += 1;
75    }
76    None
77}
78
79/// Remove a self-correction: when a backtrack trigger appears AS A WHOLE PHRASE,
80/// drop the words immediately preceding it (the spec's >3-word-reduction guard:
81/// only fire when at least 3 words precede the trigger, so we don't nuke a short
82/// true clause). Word-bounded so it never deletes content words it matched inside.
83pub fn apply_backtrack(text: &str) -> String {
84    const TRIGGERS: &[&str] = &["scratch that", "actually no"];
85    let mut result = text.to_string();
86    for trigger in TRIGGERS {
87        while let Some(pos) = find_word_bounded(&result, trigger) {
88            let before = result[..pos].trim_end();
89            let after = &result[pos + trigger.len()..];
90            let kept: Vec<&str> = before.split_whitespace().collect();
91            if kept.len() >= 3 {
92                // Drop everything back to the previous sentence boundary.
93                let cut = before.rfind(['.', '\n']).map(|i| i + 1).unwrap_or(0);
94                result = format!("{}{}", &before[..cut], after);
95            } else {
96                // Too short to be a real correction — just remove the trigger.
97                result = format!("{} {}", before, after.trim_start());
98            }
99        }
100    }
101    result.split_whitespace().collect::<Vec<_>>().join(" ")
102}
103
104/// Continuation function-words: common enough as sentence-internal openers that
105/// lowercasing them when a sentence spans a pause is safe. Deliberately excludes
106/// anything proper-noun-shaped — we never lowercase an arbitrary capitalized token.
107const CONTINUATIONS: &[&str] = &[
108    "and", "but", "so", "or", "the", "a", "an", "it", "that", "this", "these",
109    "those", "all", "then", "because", "which", "who",
110];
111
112/// Lowercase the first letter of `text` when it CONTINUES the previous block —
113/// the previous block didn't end a sentence (no terminal `.!?`) AND the first word
114/// is an allow-listed continuation word. Whisper cases each segment as a fresh
115/// sentence; this undoes the spurious mid-sentence capital when a sentence spans a
116/// pause. Conservative by construction (only the allow-list; never a proper noun).
117pub fn decapitalize_continuation(text: &str, prev_clean: Option<&str>) -> String {
118    let continues = prev_clean.is_some_and(|p| {
119        // Look past trailing closing quotes/brackets so `."` reads as terminated;
120        // a Unicode ellipsis is a deliberate trail-off, also terminal.
121        let tail = p.trim_end().trim_end_matches(['"', '\'', ')', ']', '”', '’']);
122        !matches!(tail.chars().last(), Some('.' | '!' | '?' | '…') | None)
123    });
124    if !continues {
125        return text.to_string();
126    }
127    let first = text.split_whitespace().next().unwrap_or("");
128    let bare = first.trim_matches(|c: char| !c.is_alphanumeric()).to_lowercase();
129    if !CONTINUATIONS.contains(&bare.as_str()) {
130        return text.to_string();
131    }
132    let mut chars = text.chars();
133    match chars.next() {
134        Some(c) if c.is_uppercase() => c.to_lowercase().collect::<String>() + chars.as_str(),
135        _ => text.to_string(),
136    }
137}
138
139/// Format a pass-2 Whisper revise. Whisper already cased + punctuated, so this does
140/// NOT re-capitalize sentence starts or force terminal punctuation (that re-creates
141/// the per-segment mid-sentence capital). It applies only the spoken-command and
142/// `scratch that` backtrack features and the continuation de-capitalizer.
143///
144/// Order is DELIBERATELY the reverse of the commit path's
145/// `apply_backtrack(apply_spoken_commands(raw))` (live.rs/session.rs/format.rs):
146/// `apply_backtrack` ends with `split_whitespace().join(" ")`, which collapses the
147/// `\n` that spoken commands insert. Running backtrack FIRST (on whitespace-only
148/// text) and spoken commands LAST lets a spoken `new line` survive into the output.
149/// Do not "tidy" this back to the commit order — it silently drops newlines.
150pub fn format_revise(whisper: &str, prev_clean: Option<&str>) -> String {
151    let pre = apply_spoken_commands(&apply_backtrack(whisper));
152    decapitalize_continuation(&pre, prev_clean)
153}
154
155/// Deterministic "Light": capitalize sentence starts, ensure terminal
156/// punctuation, strip leading fillers. Always guard-safe by construction.
157pub fn deterministic_light(text: &str) -> String {
158    let trimmed = text.trim();
159    let without_lead = strip_leading_fillers(trimmed);
160    let capped = capitalize_sentences(&without_lead);
161    ensure_terminal(&capitalize_standalone_i(&capped))
162}
163
164/// Capitalize a standalone `i` (and its contractions — the `'` after it is a
165/// non-alphanumeric boundary, so `i'm`/`i'll` qualify) anywhere in the phrase.
166/// The Plan-3 T1 spike showed this is the LLM's main visible improvement over the
167/// deterministic layer — and it's free, and invisible to the case-insensitive
168/// content-word guard.
169fn capitalize_standalone_i(text: &str) -> String {
170    let chars: Vec<char> = text.chars().collect();
171    let mut out = String::with_capacity(text.len());
172    for (idx, &ch) in chars.iter().enumerate() {
173        let alone_before = idx == 0 || !chars[idx - 1].is_alphanumeric();
174        let alone_after = idx + 1 == chars.len() || !chars[idx + 1].is_alphanumeric();
175        out.push(if ch == 'i' && alone_before && alone_after { 'I' } else { ch });
176    }
177    out
178}
179
180fn strip_leading_fillers(text: &str) -> String {
181    let mut words: Vec<&str> = text.split_whitespace().collect();
182    while let Some(first) = words.first() {
183        // Strip trailing punctuation so "um," / "uh." still match the bare token.
184        let lw = first.trim_matches(|c: char| !c.is_alphanumeric()).to_lowercase();
185        if LEADING_DISFLUENCIES.contains(&lw.as_str()) { words.remove(0); } else { break; }
186    }
187    words.join(" ")
188}
189
190fn capitalize_sentences(text: &str) -> String {
191    let mut out = String::with_capacity(text.len());
192    let mut at_start = true;
193    for ch in text.chars() {
194        if at_start && ch.is_alphabetic() {
195            out.extend(ch.to_uppercase());
196            at_start = false;
197        } else {
198            out.push(ch);
199            if ch == '.' || ch == '!' || ch == '?' { at_start = true; }
200        }
201    }
202    out
203}
204
205fn ensure_terminal(text: &str) -> String {
206    let t = text.trim_end();
207    if t.is_empty() || matches!(t.chars().last(), Some('.') | Some('!') | Some('?')) {
208        t.to_string()
209    } else {
210        format!("{}.", t)
211    }
212}
213
214/// Parse a config string into a `Level` (defaults to Light — the safe, restrained
215/// default — on anything unrecognized).
216pub fn parse_level(s: &str) -> Level {
217    match s.trim().to_lowercase().as_str() {
218        "none" => Level::None,
219        "medium" => Level::Medium,
220        "high" => Level::High,
221        _ => Level::Light,
222    }
223}
224
225/// The constrained-rewrite prompt for the LLM formatter (consumed by the Candle
226/// façade in T7). `system` is hard restraint that holds at every level; the
227/// per-level rule only *widens* which edits are permitted. Restraint is the
228/// wording, so it lives here in the pure core, not in the inference façade.
229pub struct RewritePrompt {
230    pub system: String,
231    pub user: String,
232}
233
234/// Build the per-level rewrite prompt for T7's Candle façade. The Light rule keeps
235/// filler removal to LEADING disfluencies only — mid-sentence `you know`/`i mean`
236/// removal is deliberately NOT requested, because the content-word guard would
237/// accept such drops (see the `FILLERS` note). T7 must preserve this restriction.
238pub fn rewrite_prompt(level: Level, text: &str) -> RewritePrompt {
239    let restraint = "You clean up raw voice transcripts. Return ONLY the cleaned text, nothing else — no preamble, no quotes. NEVER change meaning: never swap a word for a different one, never add words that change meaning, never drop a negation, never reorder clauses. When unsure, leave it as it is.";
240    let rule = match level {
241        Level::None => "Return the text exactly as given.",
242        Level::Light => "Fix only capitalization and punctuation, and drop leading non-lexical filler (um, uh, er, ah). Remove no other words.",
243        Level::Medium => "Also remove disfluencies and false starts and join fragments into sentences. Keep every meaning-bearing word.",
244        Level::High => "Also break into paragraphs at topic shifts and turn spoken lists into bullets. Keep every meaning-bearing word.",
245    };
246    RewritePrompt {
247        system: format!("{restraint} {rule}"),
248        user: format!("Clean this transcript:\n{text}"),
249    }
250}
251
252#[cfg(test)]
253mod tests {
254    use super::*;
255
256    #[test]
257    fn accepts_pure_punctuation_and_filler_cleanup() {
258        assert!(guard_accepts(
259            "um so the thing is i keep avoiding it",
260            "The thing is, I keep avoiding it.",
261        ));
262    }
263
264    #[test]
265    fn rejects_a_substituted_meaning_word() {
266        // "love" -> "loathe": tiny edit distance, catastrophic meaning change.
267        assert!(!guard_accepts("i love her", "I loathe her."));
268    }
269
270    #[test]
271    fn rejects_a_dropped_content_word() {
272        assert!(!guard_accepts("i never said that", "I said that."));
273    }
274
275    #[test]
276    fn rejects_an_added_content_word() {
277        assert!(!guard_accepts("i am tired", "I am very tired."));
278    }
279
280    #[test]
281    fn guard_permits_dropping_filler_homographs_known_limit() {
282        // Documents the Plan-3 review limit: filler-set words can be dropped even
283        // as content. deterministic_light never does this (leading-only); the T7
284        // LLM prompt must not request mid-sentence filler removal.
285        assert!(guard_accepts("do you know the way", "do the way"));
286        assert!(guard_accepts("i like it a lot", "it a lot"));
287    }
288
289    #[test]
290    fn deterministic_light_caps_and_terminates() {
291        assert_eq!(deterministic_light("um the thing is"), "The thing is.");
292    }
293
294    #[test]
295    fn does_not_strip_a_leading_content_word() {
296        // The reported "cleaning up too much" bug: a leading subject pronoun or
297        // discourse opener is CONTENT, not a disfluency — it must survive.
298        assert_eq!(deterministic_light("i sometimes forget the small things"),
299            "I sometimes forget the small things.");
300        assert_eq!(deterministic_light("you should go now"), "You should go now.");
301        assert_eq!(deterministic_light("so i realized the answer"), "So I realized the answer.");
302        assert_eq!(deterministic_light("well that is the thing"), "Well that is the thing.");
303    }
304
305    #[test]
306    fn still_strips_leading_nonlexical_disfluencies() {
307        assert_eq!(deterministic_light("um uh the thing is"), "The thing is.");
308        assert_eq!(deterministic_light("ah i see it now"), "I see it now.");
309        // Trailing punctuation on the disfluency token must not shield it.
310        assert_eq!(deterministic_light("um, the thing is"), "The thing is.");
311    }
312
313    #[test]
314    fn a_leading_pure_punctuation_token_survives() {
315        // It trims to "" which is not a disfluency, so the loop stops and the token
316        // is kept — no panic, no over-strip. (Capitalization still lands on the
317        // first real word.)
318        assert_eq!(deterministic_light("-- the thing is"), "-- The thing is.");
319    }
320
321    #[test]
322    fn standalone_i_is_capitalized_mid_sentence() {
323        assert_eq!(
324            deterministic_light("the thing is i keep avoiding it"),
325            "The thing is I keep avoiding it."
326        );
327        assert_eq!(
328            deterministic_light("i'm sure i'll try what i've found"),
329            "I'm sure I'll try what I've found."
330        );
331        // never inside words
332        assert_eq!(deterministic_light("it is in the bin"), "It is in the bin.");
333    }
334
335    #[test]
336    fn deterministic_light_is_guard_safe() {
337        let raw = "um so i keep avoiding the hard conversation";
338        assert!(guard_accepts(raw, &deterministic_light(raw)));
339    }
340
341    #[test]
342    fn spoken_command_becomes_newline() {
343        assert_eq!(apply_spoken_commands("a new line b"), "a\nb");
344    }
345
346    #[test]
347    fn backtrack_drops_preceding_clause() {
348        let out = apply_backtrack("the answer is yes scratch that the answer is no");
349        assert!(!out.contains("yes"));
350        assert!(out.contains("the answer is no"));
351    }
352
353    #[test]
354    fn backtrack_does_not_fire_inside_a_word() {
355        // "actually no" must NOT match inside "actually nobody" (word-bounded).
356        let out = apply_backtrack("well actually nobody knows the truth");
357        assert!(out.contains("nobody"));
358        assert!(out.contains("the truth"));
359    }
360
361    #[test]
362    fn spoken_command_at_phrase_start_and_end() {
363        assert_eq!(apply_spoken_commands("new line b"), "b");
364        assert_eq!(apply_spoken_commands("a new line"), "a");
365    }
366
367    #[test]
368    fn backtrack_handles_non_ascii_without_panicking() {
369        // 'ẞ' lowercases to fewer bytes; offsets must stay on char boundaries.
370        let out = apply_backtrack("aa bb ẞ scratch that ẞ tail");
371        assert!(out.contains("tail"));
372        assert!(!out.contains("scratch that"));
373    }
374
375    #[test]
376    fn parse_level_maps_known_and_defaults_to_light() {
377        assert_eq!(parse_level("none"), Level::None);
378        assert_eq!(parse_level("Medium"), Level::Medium);
379        assert_eq!(parse_level("HIGH"), Level::High);
380        assert_eq!(parse_level("light"), Level::Light);
381        assert_eq!(parse_level("nonsense"), Level::Light);
382    }
383
384    #[test]
385    fn rewrite_prompt_widens_by_level_and_carries_the_text() {
386        assert!(rewrite_prompt(Level::Light, "x").system.to_lowercase().contains("capitalization"));
387        assert!(rewrite_prompt(Level::Medium, "x").system.to_lowercase().contains("disfluencies"));
388        assert!(rewrite_prompt(Level::High, "x").system.to_lowercase().contains("paragraph"));
389        assert!(rewrite_prompt(Level::Light, "the raw phrase").user.contains("the raw phrase"));
390    }
391
392    #[test]
393    fn rewrite_prompt_always_states_the_restraint() {
394        for lvl in [Level::Light, Level::Medium, Level::High] {
395            assert!(rewrite_prompt(lvl, "x").system.to_lowercase().contains("never change meaning"));
396        }
397    }
398
399    #[test]
400    fn decapitalize_lowercases_an_allowlist_continuation_after_unterminated_prior() {
401        assert_eq!(
402            decapitalize_continuation("All these edge cases get sorted out.", Some("with their product")),
403            "all these edge cases get sorted out."
404        );
405    }
406
407    #[test]
408    fn decapitalize_keeps_capital_after_a_terminated_prior() {
409        assert_eq!(
410            decapitalize_continuation("All these edge cases.", Some("That worked.")),
411            "All these edge cases."
412        );
413    }
414
415    #[test]
416    fn decapitalize_never_lowercases_a_non_allowlist_word_protecting_proper_nouns() {
417        assert_eq!(
418            decapitalize_continuation("Whisper does the rest", Some("the tool i use is")),
419            "Whisper does the rest"
420        );
421    }
422
423    #[test]
424    fn format_revise_trusts_whisper_casing_and_applies_features() {
425        assert_eq!(format_revise("hello there", None), "hello there");
426        assert_eq!(format_revise("first line new line second", None), "first line\nsecond");
427    }
428}