instinct-cli 0.3.8

Shared local memory for coding agents. Save a fix once and find it again in a new session or another connected tool.
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
//! Does this prompt correct the agent ("no, use pnpm", "I told you, tests live in tests/")? A pure,
//! std-only heuristic over the prompt text: no model, no store, no clock. It errs toward silence, because a
//! false alarm costs the agent a line of context and a wrong lesson, while a miss costs nothing the
//! agent's own `bank` call could not still catch.

mod terse;

/// Pasted logs and long briefs are not corrections; only the opening of a message is read.
const MAX_CHARS: usize = 600;

/// Of a message that passes the length gate, this much is read: the phrase lists cost length times count.
const READ_CHARS: usize = 320;


/// Verbs a negated instruction ("don't use", "never touch") is taken to be about. A closed list on
/// purpose: "don't forget", "don't worry" and "don't hesitate" are not on it.
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",
];

/// Imperative verbs that open "use X, not Y" style sentences.
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",
];

/// Things a user names when the agent picked the wrong one of them.
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",
];

/// Words that open a sentence without changing what it says.
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",
];

/// Starts of sentences that look like negation or correction and are not.
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",
];

/// The user fixing their own message, not the agent.
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",
];

/// Words that follow ", not" in ordinary prose and make no contrast.
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",
];

/// True when the prompt looks like the user correcting the agent about something it did or assumed.
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;
    }
    // A correction opens a message; the phrase lists cost length times count, so only the first lines are read.
    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)
}

/// "dont", "didnt", "thats": the apostrophe is the first thing a fast typist drops, and every word list in
/// this file spells these words with it.
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
}

/// Sentences with whether each ended in a question mark. A dot ends one only before whitespace, so
/// `src/lib.rs` and `v1.2` stay whole.
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 == '_'
}

/// `phrase` occurs in `s` with word boundaries on both sides.
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"
    )
}

/// Strips fillers from the front; says whether a refusal word ("no", "nope", "wait") was among them.
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();
        // "stop" and "come" are fillers only before a comma ("stop, use pnpm"), never before a verb.
        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()..];
    }
}

/// `prev_refused`: the sentence before was a bare "no" or "wait", so a rule that follows is a correction.
fn sentence(s: &str, question: bool, prev_refused: bool) -> bool {
    let ws = words(s);
    let Some(first) = ws.first() else { return false };
    // A question is a correction only in its "didn't I tell you" and "why do you keep" forms.
    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;
    }
    // "wait, i need to grab the logs": a pause is not a refusal unless a no follows it.
    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)
}

/// "Wrong directory.", "incorrect, the API returns snake_case": the sentence is the refusal.
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"))
}

/// "Not the root package.json, the one inside apps/web".
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))
}

/// "That's not what I asked / wanted / meant".
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
}

/// "Stop adding comments", "quit using mocks", "no more force-pushes".
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")
}

/// "You keep using npm", "you shouldn't touch the lockfile", "you ignored the style guide".
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;
            }
        }
        // "you used the wrong ...", "you edited the wrong ..."
        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;
        }
        // "you did it again", "you did that again"
        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
}

/// "No, use pnpm", "no, we use yarn here", "no, the tests are in tests/": a refusal followed by what to do.
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;
        }
        // "Wrong. Commit messages are lowercase here.": a local convention stated right after a refusal.
        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
}

/// "It's not in src, it's in lib", "that's not how we name things".
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;
            }
            // "it's not in src, it's in lib"
            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
}

/// "We always use pnpm here", "from now on ...": the user stating the house rule.
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
}

/// "I told you", "as I said", "I never asked you to": the user is repeating themselves.
fn remembered(s: &str) -> bool {
    // What may follow "I said": a rule or a quote of one, not "I said hi".
    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("");
        // "i said earlier that i'd review it today": a promise of the user's own, not an instruction.
        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;
        }
        // "i said rust not go", "i wanted a test, not a refactor": the instruction and the thing it ruled out.
        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" => {
                // "I didn't ask you to", "I did not say", "I never asked you"
                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")
}

/// A negated instruction at the start of a sentence: "don't use mocks", "never touch the lockfile".
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("");
    // A negated rule that is really a request to explain or discuss one is not a correction.
    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
}

/// "That's the wrong file", "you used the wrong runner", "that's wrong".
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;
        }
        // "the wrong version warning shows up": a noun phrase about a message, not a verdict on a pick.
        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
}

/// "Use pnpm, not npm", "tests live in tests/, not src/", "we deploy with fly, not heroku".
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 {
        // "use pnpm not npm": only for `use`, where the shape is unmistakable
        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```"));
    }

    /// Scores the detector on tests/fixtures/corrections-dev.tsv (`yes|message` or `no|message`).
    #[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}");
    }

    /// The prompt hook has about 15 ms in all; the detector gets a hundredth of that per message. The set is
    /// run in a loop and the fastest of nine rounds is judged, so one busy moment cannot fail it.
    #[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");
        // The longest message the detector reads (600 characters of plain prose, no correction in it).
        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");
        // Measured alone, the release build reads this in about 0.17 ms (0.6 ms limit). The unoptimised test build
        // needs about 1.4 ms at its fastest and 2.4 ms on a heavily loaded machine, so its limit is 5 ms: still far below
        // what a quadratic slowdown would cost on 590 characters.
        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));
        }
    }
}