mod terse;
const MAX_CHARS: usize = 600;
const READ_CHARS: usize = 320;
const RULE_VERBS: &[&str] = &[
"use", "add", "create", "edit", "touch", "change", "modify", "delete", "remove", "run", "commit", "push",
"write", "put", "install", "import", "rename", "overwrite", "reformat", "refactor", "mock", "make",
"call", "ask", "rewrite", "move", "hardcode", "pin", "bump", "format", "amend", "force", "reorder",
"reindent", "stub", "inline", "wrap", "assume", "guess", "invent", "squash", "merge", "revert",
];
const LEAD_VERBS: &[&str] = &[
"use", "run", "put", "call", "write", "name", "import", "edit", "open", "check", "set", "add", "keep",
"store", "place", "save", "create", "make", "do", "try", "go", "switch", "read", "look", "pick", "choose",
"follow", "stick", "install", "build", "test", "start", "move", "rename", "change", "update", "fix",
];
const THINGS: &[&str] = &[
"file", "files", "directory", "dir", "folder", "path", "branch", "approach", "way", "one", "command", "tool",
"version", "package", "place", "repo", "location", "name", "function", "method", "class", "module", "flag",
"option", "port", "env", "config", "language", "library", "framework", "test", "tests", "script", "target",
"commit", "table", "column", "field", "key", "variable", "line", "manager", "runner", "format", "style",
"convention", "package-manager",
];
const FILLERS: &[&str] = &[
"no", "nope", "nah", "wait", "hold", "on", "hey", "ugh", "oh", "ok", "okay", "well", "so", "but", "and",
"please", "actually", "again", "listen", "look", "man", "dude", "claude", "agent", "sigh", "damn",
"seriously", "honestly", "ahh", "ah", "argh", "aargh", "gah", "come", "stop", "no,", "yeah", "yes", "right", "alright", "hmm", "uh", "um", "now",
];
const NOT_CORRECTIONS: &[&str] = &[
"don't forget", "do not forget", "don't worry", "do not worry", "no rush", "no problem", "no worries",
"no need", "don't hesitate", "do not hesitate", "never mind", "nevermind", "no way", "there is no",
"there's no", "no longer", "can't wait", "don't mind", "do not mind", "don't be shy", "no idea",
"don't know", "do not know", "don't understand", "don't see", "don't think", "don't have", "don't get",
"don't need", "no one", "no matter", "no thanks", "no thank you", "don't bother", "no hurry", "no, thanks",
"no, thank you", "no, that's fine", "no, that is fine", "no, it's fine", "no, it is fine", "no, it's ok",
"no, all good", "no, that works", "no, looks good", "no, perfect", "no, great", "no, nothing", "no, not yet",
"no, i don't", "no, i do not", "no, i haven't", "no, i have not", "no, i can't", "no, i cannot", "no, i won't",
"no, i am not", "no, i'm not", "no, i didn't", "no, i did not", "no, not really", "no, just", "no, only",
];
const SELF_FIX: &[&str] = &[
"sorry", "oops", "typo", "my bad", "my mistake", "mistyped", "misspoke", "misspelled", "autocorrect",
"scratch that", "ignore that", "ignore my", "i mean", "correction:", "edit:", "i misread", "i was wrong",
"i meant to", "i mistyped", "i wrote the wrong", "i wrote it wrong", "that was me", "my fault", "disregard", "never mind", "nevermind",
];
const NOT_CONTRAST: &[&str] = &[
"sure", "only", "just", "yet", "really", "at", "too", "to", "now", "bad", "great", "good", "very", "much",
"necessarily", "quite", "even", "always", "exactly", "been", "working", "sorry", "able", "going", "happy",
"i", "we", "you", "it", "that", "this", "there", "he", "she", "they", "so", "all", "everything", "anything",
"something", "because", "if", "when", "until", "unless", "enough", "needed", "required", "important",
"urgent", "critical", "blocking", "applicable", "relevant", "perfect", "ideal", "fast", "slow", "clear",
"long", "short", "big", "small", "like", "supposed", "expected",
];
pub fn correction(prompt: &str) -> bool {
let text: String = prompt.chars().take(MAX_CHARS + 1).collect();
if text.chars().count() > MAX_CHARS || text.contains("```") {
return false;
}
let text = normalize(&text.chars().take(READ_CHARS).collect::<String>());
if SELF_FIX.iter().any(|m| has(&text, m)) {
return false;
}
if terse::message(&text) {
return true;
}
let mut prev_refused = false;
for (s, question) in sentences(&text) {
if sentence(&s, question, prev_refused) {
return true;
}
let (rest, refused) = strip_openers(&s);
prev_refused = (refused && rest.is_empty()) || matches!(words(&s).as_slice(), ["wrong"] | ["incorrect"] | ["wrong", "again"]);
}
false
}
fn normalize(s: &str) -> String {
let lowered: String = s
.chars()
.map(|c| match c {
'\u{2018}' | '\u{2019}' | '\u{02bc}' | '`' => '\'',
'\u{201c}' | '\u{201d}' => '"',
'\u{2013}' | '\u{2014}' => '-',
c => c,
})
.collect::<String>()
.to_lowercase();
restore_apostrophes(&lowered)
}
fn restore_apostrophes(s: &str) -> String {
const MAP: &[(&str, &str)] = &[
("dont", "don't"), ("doesnt", "doesn't"), ("didnt", "didn't"), ("isnt", "isn't"), ("wasnt", "wasn't"),
("arent", "aren't"), ("cant", "can't"), ("wont", "won't"), ("wouldnt", "wouldn't"), ("shouldnt", "shouldn't"),
("couldnt", "couldn't"), ("havent", "haven't"), ("hasnt", "hasn't"), ("thats", "that's"), ("whats", "what's"),
("youre", "you're"), ("theres", "there's"), ("im", "i'm"), ("ive", "i've"), ("werent", "weren't"),
("u", "you"), ("pls", "please"), ("plz", "please"),
];
fn flush(word: &mut String, out: &mut String) {
match MAP.iter().find(|(k, _)| *k == word.as_str()) {
Some((_, v)) => out.push_str(v),
None => out.push_str(word),
}
word.clear();
}
let mut out = String::with_capacity(s.len() + 8);
let mut word = String::new();
for c in s.chars() {
if is_word_char(c) {
word.push(c);
} else {
flush(&mut word, &mut out);
out.push(c);
}
}
flush(&mut word, &mut out);
out
}
fn sentences(s: &str) -> Vec<(String, bool)> {
let chars: Vec<char> = s.chars().collect();
let mut out = Vec::new();
let mut cur = String::new();
for (i, &c) in chars.iter().enumerate() {
let end = match c {
'\n' | '!' | '?' | ';' => true,
'.' => chars.get(i + 1).is_none_or(|n| n.is_whitespace()),
_ => false,
};
if end {
let t = cur.trim();
if !t.is_empty() {
out.push((t.to_owned(), c == '?'));
}
cur.clear();
} else {
cur.push(c);
}
}
let t = cur.trim();
if !t.is_empty() {
out.push((t.to_owned(), false));
}
out
}
fn is_word_char(c: char) -> bool {
c.is_alphanumeric() || c == '\'' || c == '_'
}
fn has(s: &str, phrase: &str) -> bool {
let mut from = 0;
while let Some(i) = s[from..].find(phrase) {
let a = from + i;
let b = a + phrase.len();
let before = s[..a].chars().next_back().is_none_or(|c| !is_word_char(c));
let after = s[b..].chars().next().is_none_or(|c| !is_word_char(c));
if before && after {
return true;
}
from = a + s[a..].chars().next().map_or(1, char::len_utf8);
if from >= s.len() {
break;
}
}
false
}
fn starts(s: &str, phrase: &str) -> bool {
s.starts_with(phrase) && s[phrase.len()..].chars().next().is_none_or(|c| !is_word_char(c))
}
fn words(s: &str) -> Vec<&str> {
s.split(|c: char| !is_word_char(c) && c != '-').filter(|w| !w.is_empty()).collect()
}
fn is_interrogative(first: &str) -> bool {
matches!(
first,
"is" | "are" | "was" | "were" | "do" | "does" | "did" | "can" | "could" | "would" | "will" | "should"
| "why" | "what" | "how" | "which" | "who" | "where" | "when" | "has" | "have" | "shall" | "am"
| "isn't" | "aren't" | "don't" | "doesn't" | "wasn't" | "won't" | "wouldn't" | "couldn't"
)
}
fn strip_openers(s: &str) -> (&str, bool) {
let mut rest = s;
let mut refused = false;
loop {
let t = rest.trim_start_matches(|c: char| c == ',' || c == '-' || c == ':' || c.is_whitespace());
let w: String = t.chars().take_while(|c| is_word_char(*c)).collect();
let is_filler = FILLERS.contains(&w.as_str())
&& (!matches!(w.as_str(), "stop" | "come" | "on" | "hold" | "look" | "right" | "now" | "so" | "and" | "but")
|| t[w.len()..].trim_start().starts_with(',')
|| matches!(w.as_str(), "on" | "hold" | "and" | "but" | "so" | "now"));
if w.is_empty() || !is_filler {
return (t, refused);
}
if matches!(w.as_str(), "no" | "nope" | "nah" | "wait" | "hold" | "ugh") {
refused = true;
}
rest = &t[w.len()..];
}
}
fn sentence(s: &str, question: bool, prev_refused: bool) -> bool {
let ws = words(s);
let Some(first) = ws.first() else { return false };
if question {
return has(s, "how many times")
|| terse::blame(s)
|| ((starts(s, "didn't i") || starts(s, "did i not") || starts(s, "haven't i"))
&& (has(s, "tell") || has(s, "say") || has(s, "ask") || has(s, "mention")))
|| ((starts(s, "why do you") || starts(s, "why are you") || starts(s, "why must you"))
&& (has(s, "keep") || has(s, "always") || has(s, "still") || has(s, "never")));
}
if terse::missing_thing(s) {
return true;
}
if NOT_CORRECTIONS.iter().any(|p| starts(s, p)) {
return false;
}
if terse::frustrated(s) || remembered(s) || not_what(s) || terse::blame(s) || terse::you_blame(s) || terse::quoted_claim(s) || terse::repeat(s)
|| terse::claim(s) || terse::missing_thing(s) || terse::contrast_fact(s) || terse::hard_no(s)
{
return true;
}
let (rest, refused) = strip_openers(s);
if rest.is_empty() {
return false;
}
if NOT_CORRECTIONS.iter().any(|p| starts(rest, p))
|| is_interrogative(first) && !refused && !starts(s, "don't") && !starts(s, "do not")
{
return false;
}
let soft = matches!(*first, "wait" | "hold" | "ugh") && !ws.iter().take(4).any(|x| matches!(*x, "no" | "nope" | "nah"));
let refused = (refused && !soft) || prev_refused;
let actually = starts(s, "actually");
flat_no(rest) || stop_it(rest, s) || about_you(s) || negated_rule(rest)
|| directed(rest, refused || actually) || wrong_thing(rest) || not_it(rest) || contrast(rest, s)
|| standing_rule(rest) || leading_not(rest)
}
fn flat_no(rest: &str) -> bool {
let w = words(rest);
matches!(w.first(), Some(&"wrong") | Some(&"incorrect"))
&& (w.get(1).is_some_and(|x| THINGS.contains(x) || matches!(*x, "again" | "thing" | "answer" | "idea" | "guess")) || rest.starts_with("wrong,") || rest.starts_with("incorrect,") || w.len() == 1)
&& w.get(1).is_none_or(|x| !matches!(*x, "answer" | "number" | "result" | "output" | "type" | "error" | "label"))
}
fn leading_not(rest: &str) -> bool {
let w = words(rest);
starts(rest, "not") && rest.contains(',') && w.len() >= 4 && w.get(1).is_some_and(|n| !NOT_CONTRAST.contains(n))
}
fn not_what(s: &str) -> bool {
for lead in ["that's not what", "that is not what", "this is not what", "this isn't what", "that isn't what", "it's not what", "it is not what", "not what"] {
if let Some(i) = s.find(lead) {
let tail = &s[i + lead.len()..];
let t = words(tail);
if t.first().is_some_and(|w| matches!(*w, "i" | "we" | "you")) && t.iter().take(5).any(|w| matches!(*w, "asked" | "wanted" | "meant" | "said" | "told" | "ask" | "want" | "mean" | "need" | "needed" | "requested" | "expected" | "intended" | "say" | "had")) {
return true;
}
}
}
false
}
fn stop_it(rest: &str, s: &str) -> bool {
let w = words(rest);
let ing = |x: &&str| x.len() > 4 && x.ends_with("ing") && !matches!(*x, "anything" | "something" | "nothing" | "everything" | "thing" | "string");
if matches!(w.first(), Some(&"stop") | Some(&"quit")) {
return w.get(1).is_some_and(ing) || matches!(w.get(1), Some(&"it") | Some(&"that") | Some(&"this") | Some(&"doing"));
}
if starts(rest, "please stop") || starts(rest, "just stop") || starts(rest, "you need to stop") || starts(rest, "you have to stop") || starts(rest, "you must stop") || starts(rest, "i need you to stop") || starts(rest, "i told you to stop") {
return w.iter().skip(1).any(|x| *x == "stop") && w.iter().skip_while(|x| **x != "stop").nth(1).is_some_and(|x| ing(x) || matches!(*x, "it" | "that" | "this"));
}
if starts(rest, "no more") && w.get(2).is_some_and(ing) {
return true;
}
has(s, "you need to stop") || has(s, "you have to stop") || has(s, "you must stop") || has(s, "i need you to stop")
}
fn about_you(s: &str) -> bool {
let w = words(s);
for (i, x) in w.iter().enumerate() {
if *x != "you" && *x != "you're" && *x != "youre" {
continue;
}
let a = w.get(i + 1).copied().unwrap_or("");
let b = w.get(i + 2).copied().unwrap_or("");
let c = w.get(i + 3).copied().unwrap_or("");
let ing = |x: &str| x.len() > 4 && x.ends_with("ing");
if (matches!(a, "keep" | "kept" | "always" | "constantly" | "again" | "still" | "once" | "also") && ing(b)) || (matches!(a, "keep" | "kept") && ing(b)) {
return true;
}
if matches!(a, "always" | "still" | "again") && (RULE_VERBS.contains(&b) || matches!(b, "forget" | "use" | "used" | "ignore" | "ignored")) {
return true;
}
if matches!(a, "shouldn't" | "mustn't" | "can't" | "cannot" | "may not" | "should not" | "must not")
&& RULE_VERBS.contains(&b)
{
return true;
}
if matches!(a, "should" | "must" | "can" | "may") && b == "not" && RULE_VERBS.contains(&c) {
return true;
}
if matches!(a, "didn't" | "did" | "never" | "haven't" | "failed" | "forgot" | "ignored" | "ignoring" | "missed") {
let (v, tail) = if a == "did" && b == "not" { (c, w.get(i + 4).copied().unwrap_or("")) } else { (b, c) };
if matches!(a, "forgot" | "ignored" | "missed" | "failed") && matches!(b, "to" | "the" | "my" | "our" | "that" | "what" | "it") {
return true;
}
if matches!(v, "listen" | "read" | "follow" | "check" | "respect" | "obey" | "notice") || (matches!(v, "do" | "use" | "run" | "update" | "add") && matches!(tail, "what" | "as" | "the" | "it" | "that" | "my")) {
return true;
}
}
if b == "the" && c == "wrong" || a == "the" && b == "wrong" || (a == "used" || a == "edited" || a == "picked" || a == "chose" || a == "ran" || a == "opened") && w.get(i + 2) == Some(&"wrong") {
return true;
}
if matches!(a, "did" | "made" | "used" | "forgot" | "broke" | "deleted" | "added" | "changed" | "touched" | "edited" | "wrote" | "ran" | "put" | "created" | "ignored") && w[i + 1..].contains(&"again") && !matches!(w[0], "can" | "could" | "would" | "please" | "let's" | "try") {
return true;
}
}
false
}
fn directed(rest: &str, refused: bool) -> bool {
let w = words(rest);
let Some(first) = w.first().copied() else { return false };
if refused {
if LEAD_VERBS.contains(&first) && w.len() >= 2 {
return true;
}
if matches!(first, "we" | "our" | "i" | "it's" | "its" | "the" | "that's" | "they" | "tests" | "this") {
let mark = w.iter().skip(1).any(|x| {
matches!(
*x,
"use" | "uses" | "using" | "always" | "never" | "only" | "live" | "lives" | "go" | "goes" | "belong" | "belongs"
| "want" | "need" | "meant" | "said" | "asked" | "prefer" | "should" | "must" | "instead" | "not"
| "wrong" | "supposed" | "named" | "called" | "stored" | "located"
)
});
let calm = w.iter().any(|x| matches!(*x, "fine" | "good" | "ok" | "okay" | "great" | "perfect" | "thanks" | "works" | "correct" | "right" | "nice" | "needed" | "important" | "sure" | "yet" | "ready" | "done"));
return mark && !calm && w.len() >= 3;
}
if first == "don't" || first == "do" || first == "never" {
return false;
}
let local = w.iter().any(|x| matches!(*x, "here" | "repo" | "project" | "codebase"));
let calm = w.iter().any(|x| matches!(*x, "fine" | "good" | "ok" | "okay" | "great" | "perfect" | "thanks" | "works" | "nice" | "yet" | "sure"));
if local && !calm && w.len() >= 3 && !matches!(first, "more" | "lets" | "let's") {
return true;
}
}
if matches!(first, "use" | "run" | "put" | "do" | "try" | "go") && w.len() <= 9 && w.iter().skip(1).any(|x| *x == "instead") {
return true;
}
if first == "from" && w.get(1) == Some(&"now") && w.get(2) == Some(&"on") {
return true;
}
if (starts(rest, "going forward") || starts(rest, "in the future") || starts(rest, "next time") || starts(rest, "from here on"))
&& w.iter().any(|x| RULE_VERBS.contains(x) || matches!(*x, "always" | "never" | "check" | "read" | "look"))
{
return true;
}
false
}
fn not_it(s: &str) -> bool {
for lead in ["that's not", "that is not", "this is not", "this isn't", "that isn't", "it's not", "it is not", "it isn't", "thats not"] {
if let Some(rest) = s.strip_prefix(lead) {
let t = words(rest);
let first = t.first().copied().unwrap_or("");
if matches!(first, "how" | "where" | "the" | "right" | "correct") && t.len() >= 3 && !t.iter().take(3).any(|x| matches!(*x, "problem" | "issue" | "bug" | "big" | "deal" | "end" | "world")) {
if first == "right" || first == "correct" {
return t.len() >= 1;
}
return true;
}
if let Some(i) = rest.find(',') {
let after = words(&rest[i + 1..]);
if matches!(after.first(), Some(&"it's") | Some(&"its") | Some(&"it") | Some(&"that's") | Some(&"use") | Some(&"the") | Some(&"we") | Some(&"they")) && !after.iter().take(3).any(|x| matches!(*x, "ok" | "fine" | "good")) {
return !matches!(first, "a" | "an" | "working" | "possible" | "clear" | "urgent" | "important" | "needed" | "required" | "ready" | "available" | "done" | "sure" | "yet" | "my" | "your" | "our" | "just" | "really");
}
}
}
}
false
}
fn standing_rule(s: &str) -> bool {
let w = words(s);
if w.first() == Some(&"we") || w.first() == Some(&"our") {
let rule_adverb = w.get(1).is_some_and(|x| matches!(*x, "always" | "never" | "only" | "don't" | "do"));
let verb = w.iter().skip(1).take(4).any(|x| RULE_VERBS.contains(x) || matches!(*x, "name" | "keep" | "store" | "put" | "live" | "write"));
let here = w.windows(2).any(|p| matches!((p[0], p[1]), ("in", "this") | ("in", "the") | ("on", "this")) ) || w.contains(&"here") || w.contains(&"repo") || w.contains(&"project") || w.contains(&"codebase");
return rule_adverb && verb && here && !w.iter().any(|x| matches!(*x, "need" | "want" | "should" | "can" | "could" | "would" | "if"));
}
false
}
fn remembered(s: &str) -> bool {
const RULE_START: &[&str] = &[
"use", "to", "not", "no", "we", "it", "it's", "that", "always", "never", "only", "don't", "do", "you", "put", "run",
"the", "this", "our", "they", "so", "earlier", "before", "already", "clearly", "explicitly", "tabs", "spaces", "dont",
"keep", "leave", "one", "other", "a", "an", "no", "test", "tests",
];
let ws = words(s);
for (i, w) in ws.iter().enumerate() {
if !matches!(*w, "i" | "i've" | "ive" | "i'd") {
continue;
}
let mut j = i + 1;
while ws.get(j).is_some_and(|x| matches!(*x, "already" | "just" | "have" | "clearly" | "literally" | "explicitly" | "also" | "even" | "really" | "previously" | "repeatedly" | "twice" | "keep" | "specifically" | "distinctly" | "expressly" | "definitely")) {
j += 1;
}
let Some(&verb) = ws.get(j) else { continue };
let next = ws.get(j + 1).copied().unwrap_or("");
if ws[j + 1..].iter().take(5).any(|x| matches!(*x, "i'd" | "i'll" | "i'm" | "we'll" | "we'd" | "hi" | "hello" | "yes" | "thanks")) && !has(s, "i said i") {
continue;
}
if matches!(verb, "said" | "meant" | "wanted" | "asked" | "told") {
let tail = &ws[j + 1..];
const AUX: &[&str] = &["is", "are", "was", "were", "does", "did", "do", "it's", "that's", "there's", "isn't", "can", "could", "would", "should", "will", "has", "have", "be", "been", "i", "you", "we", "to", "know", "why"];
if tail.len() <= 8 && tail.iter().position(|x| *x == "not").is_some_and(|k| k >= 1 && !AUX.contains(&tail[k - 1]) && !tail[..k].contains(&"why")) {
return true;
}
}
match verb {
"told" if next == "you" => return true,
"said" | "mentioned" | "explained" | "specified" | "stated" if RULE_START.contains(&next) => return true,
"telling" | "saying" | "asking" if matches!(next, "you" | "this" | "that") => return true,
"asked" if matches!(next, "you" | "for") && (j > i + 1 || has(s, "not")) => return true,
"didn't" | "did" | "never" | "haven't" | "have" => {
let after: Vec<&str> = ws[j + 1..].iter().copied().take(3).collect();
let k = after.iter().position(|x| matches!(*x, "ask" | "asked" | "say" | "said" | "tell" | "told" | "request" | "requested"));
if let Some(k) = k {
if after.get(k + 1).is_some_and(|x| matches!(*x, "you" | "for" | "to" | "that" | "anything" | "it")) {
return true;
}
}
}
_ => {}
}
}
has(s, "as i said") || has(s, "like i said") || has(s, "as i told you") || has(s, "like i told you")
|| has(s, "i said so") || has(s, "read what i wrote") || has(s, "read my message")
|| has(s, "read the instructions again") || has(s, "how many times") || has(s, "for the last time")
|| has(s, "for the third time") || has(s, "for the second time") || has(s, "i keep telling you")
|| has(s, "i keep saying") || has(s, "i shouldn't have to") || has(s, "we talked about this")
|| has(s, "we already discussed") || has(s, "we have a rule") || has(s, "our convention is") || has(s, "against our") || has(s, "we've been over this") || has(s, "i've said this")
}
fn negated_rule(rest: &str) -> bool {
let w = words(rest);
let mut i = 0;
if matches!(w.first(), Some(&"please") | Some(&"just")) {
i = 1;
}
let (neg, mut j) = match w.get(i) {
Some(&"don't") | Some(&"dont") | Some(&"never") => (true, i + 1),
Some(&"do") if w.get(i + 1) == Some(&"not") => (true, i + 2),
_ => (false, 0),
};
if !neg {
return false;
}
if matches!(w.get(j), Some(&"ever") | Some(&"just")) {
j += 1;
}
let verb = w.get(j).copied().unwrap_or("");
let asks = w.iter().any(|x| matches!(*x, "explain" | "why" | "describe" | "tell" | "discuss" | "risks" | "whether" | "show" | "how" | "yet" | "until" | "list" | "review" | "now"));
RULE_VERBS.contains(&verb) && !asks
}
fn wrong_thing(rest: &str) -> bool {
const LEADS: &[&str] = &[
"is", "was", "are", "were", "that's", "it's", "thats", "this", "that", "used", "edited", "opened", "picked", "chose",
"ran", "got", "in", "to", "wrote", "modified", "changed", "touched",
];
let w = words(rest);
for (i, x) in w.iter().enumerate() {
if *x != "wrong" || !w.get(i + 1).is_some_and(|n| THINGS.contains(n)) {
continue;
}
let compound = w.get(i + 2).is_some_and(|n| matches!(*n, "warning" | "warnings" | "error" | "errors" | "message" | "messages" | "label" | "text" | "string" | "output" | "result" | "answer" | "number" | "password" | "credentials" | "type"));
if !compound && (i == 0 || (w[i - 1] == "the" && (i == 1 || LEADS.contains(&w[i - 2])))) {
return true;
}
}
if matches!(w.first(), Some(&"that's") | Some(&"that") | Some(&"this") | Some(&"thats")) {
let wrong = w.iter().take(5).any(|x| matches!(*x, "wrong" | "incorrect"));
let not_right = w.windows(2).take(4).any(|p| p[0] == "not" && matches!(p[1], "right" | "correct"));
return (wrong || not_right) && w.len() <= 10 && !w.iter().any(|x| matches!(*x, "if" | "when" | "why" | "because" | "with" | "about"));
}
false
}
fn contrast(rest: &str, s: &str) -> bool {
const LEADS: &[&str] = &[
"use", "run", "put", "call", "name", "store", "place", "save", "keep", "switch", "stick", "follow", "pick",
"choose", "go", "import", "set", "using",
];
const SUBJECTS: &[&str] = &["we", "our", "it's", "its", "they", "the", "tests", "that's"];
let Some(i) = s.find(", not ") else {
let w = words(rest);
if matches!(w.first(), Some(&"use") | Some(&"using")) && w.len() >= 4 {
if let Some(p) = w.iter().position(|x| *x == "not") {
return p >= 2
&& w.get(p + 1).is_some_and(|n| !NOT_CONTRAST.contains(n))
&& !matches!(w[p - 1], "do" | "does" | "is" | "are" | "should" | "would" | "can" | "will" | "but" | "and" | "or");
}
}
return false;
};
let before = words(&s[..i]);
let after = words(&s[i + 6..]);
let Some(next) = after.first() else { return false };
before.len() >= 2
&& !NOT_CONTRAST.contains(next)
&& !before.iter().any(|x| matches!(*x, "if" | "when" | "because" | "while" | "although" | "sure" | "but" | "though" | "should"))
&& (LEADS.contains(&before[0]) || SUBJECTS.contains(&before[0]))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn clear_corrections_are_found() {
for p in [
"No, use pnpm not npm",
"I told you, tests live in tests/",
"That's the wrong file, it's src/lib.rs",
"Stop adding comments to every function",
"Don't use mocks, I said use the real database",
"that's not what I asked for",
"You keep using npm. We use pnpm here.",
] {
assert!(correction(p), "{p}");
}
}
#[test]
fn tricky_negatives_stay_quiet() {
for p in [
"no rush, take your time",
"don't forget to add tests",
"is there no way to skip the build?",
"sorry, I meant pnpm, typo",
"Add a retry to the fetch helper",
"why is the build wrong on windows?",
"can you run the tests again?",
] {
assert!(!correction(p), "{p}");
}
}
#[test]
fn long_pastes_and_code_are_never_corrections() {
assert!(!correction(&format!("No, use pnpm {}", "x".repeat(700))));
assert!(!correction("No, use pnpm\n```\nstack trace\n```"));
}
#[test]
fn dev_set_precision_and_recall() {
let text = include_str!("../tests/fixtures/corrections-dev.tsv");
let (mut tp, mut fp, mut miss, mut tn) = (0, 0, 0, 0);
for line in text.lines().filter(|l| !l.trim().is_empty()) {
let (label, msg) = line.split_once('|').unwrap();
match (label, correction(msg)) {
("yes", true) => tp += 1,
("no", true) => {
fp += 1;
eprintln!("FALSE POSITIVE: {msg}");
}
("yes", false) => {
miss += 1;
eprintln!("MISS: {msg}");
}
_ => tn += 1,
}
}
let p = tp as f64 / (tp + fp).max(1) as f64;
let r = tp as f64 / (tp + miss).max(1) as f64;
let fa = fp as f64 * 100.0 / (fp + tn).max(1) as f64;
eprintln!("dev precision {p:.3} recall {r:.3} false alarms per 100 non-corrections {fa:.2} (tp {tp} fp {fp} miss {miss} tn {tn})");
assert!(p >= 0.97 && r >= 0.9 && fa <= 1.0, "dev precision {p:.3} recall {r:.3} false alarms/100 {fa:.2}");
}
#[test]
fn detector_costs_under_a_fifth_of_a_millisecond_per_message() {
let text = include_str!("../tests/fixtures/corrections-dev.tsv");
let msgs: Vec<&str> = text.lines().filter_map(|l| l.split_once('|')).map(|(_, m)| m).collect();
assert!(msgs.len() > 500);
let mut best = f64::MAX;
for _ in 0..9 {
let start = std::time::Instant::now();
let mut hits = 0usize;
for _ in 0..4 {
for m in &msgs {
hits += usize::from(correction(std::hint::black_box(m)));
}
}
std::hint::black_box(hits);
best = best.min(start.elapsed().as_secs_f64() * 1000.0 / (4 * msgs.len()) as f64);
}
eprintln!("detector: {best:.4} ms per message (unoptimised test build)");
let limit_avg = if cfg!(debug_assertions) { 0.4 } else { 0.2 };
assert!(best < limit_avg, "{best:.4} ms per message");
let long = "please look at the parser module and tell me how the retry loop decides when to stop, then add a test for the empty input case and update the notes. ".repeat(4);
let long = &long[..590];
let mut per = f64::MAX;
for _ in 0..9 {
let start = std::time::Instant::now();
for _ in 0..100 {
std::hint::black_box(correction(std::hint::black_box(long)));
}
per = per.min(start.elapsed().as_secs_f64() * 1000.0 / 100.0);
}
eprintln!("detector: {per:.4} ms for a 590-character message");
let limit = if cfg!(debug_assertions) { 5.0 } else { 0.6 };
assert!(per < limit, "{per:.4} ms for a 590-character message");
}
#[test]
fn terse_frustrated_indirect_and_sarcastic_corrections_are_found() {
for p in [
"nope", "wrong", "undo that", "stop", "no", "nah", "revert it", "not like that", "stop stop stop",
"no, use pnpm", "nah the port is 8080", "uh no, i wanted the other approach",
"dude what the hell, i said dont touch main", "ffs i said use pnpm", "jesus christ stop rewriting everything",
"again?? i told you twice", "this is the 4th time. no emojis", "how many times do i have to say it",
"why did you delete the tests", "why are you using npm", "who told you to refactor that", "that's not what i asked",
"you deleted the migration", "you just ignored everything i said", "i didnt ask for that",
"it's not running, check the logs", "still the same error", "you said it passed but it fails",
"too long, cut it in half", "make it shorter", "no emojis", "be more concise",
"great, now nothing builds", "nice, you broke the tests", "thanks for nothing, still doesnt work",
] {
assert!(correction(p), "missed: {p}");
}
}
#[test]
fn lookalikes_stay_quiet() {
for p in [
"dude nice", "perfect ship it", "no rush, add a test", "don't forget the docs", "no worries", "yes do it",
"why does the cache use LRU?", "why did you pick a hashmap here, just curious", "did you run the tests?",
"stop the dev server and run the tests again", "revert the last commit and push",
"undo the last commit and split it in two", "wrong password error on login, can you debug",
"error: cannot find module foo. can you fix it", "getting ECONNREFUSED on 5432, can you check the db is up",
"this is not working, the page is blank", "it crashes when the input is empty, add a guard",
"great, now add docs", "thanks, that fixed it", "awesome, tests pass now", "go ahead", "no, thanks",
"make the output shorter when there is only one match", "keep the summary under 100 words",
"the output is too long for the terminal, add a pager flag", "wait, i need to grab the logs",
"i said earlier that i'd review it today", "use a hashmap instead of a vec for the lookup",
"holy shit thats fast", "fuck, my laptop died, where were we", "wtf is this error, explain it",
] {
assert!(!correction(p), "false alarm: {p}");
}
}
#[test]
fn odd_text_never_panics() {
for p in [
"", " ", "?", "!!!", "no,", ",", "...", "nooooooo", "ñó, usa pnpm", "不对,用 pnpm", "🙄 no", "😡😡😡",
"ünïcödé wrong", "1st", "4th time", "th", "99th time", "ß", "i said ß", "you ß", "why you ß",
"oh \u{1F600}\u{1F600}\u{1F600}\u{1F600}\u{1F600}\u{1F600}\u{1F600}\u{1F600} great", "great\u{301}, now nothing builds",
] {
let _ = correction(p);
let _ = correction(&p.repeat(40));
}
}
}