Skip to main content

agentmux_srv_core/ambient/
validate.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! What a well-formed answer must still satisfy. The reply format (`reply`) has
5//! already turned away anything that isn't an `ANSWER:` or `SKIP`; these checks
6//! judge the answer text itself: its size, and whether it is a real title (a
7//! stored one too, from an older build), or a safe suggestion.
8//!
9//! The absence and refusal lists below are frozen. They judge titles that older
10//! builds stored, before the reply format existed, and the frontend's port of
11//! [`is_usable_title`] shares them through `title_corpus.json`. New wordings are
12//! the reply format's job, not a new list entry.
13
14/// Size bounds for a one-line reply.
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16pub struct Limits {
17    pub max_words: usize,
18    pub max_chars: usize,
19}
20
21/// A pane/session title asked for `word_target` words. The slack covers a model
22/// that runs a little over; a paragraph is still rejected.
23pub fn title_limits(word_target: u32) -> Limits {
24    Limits { max_words: word_target as usize + 8, max_chars: 200 }
25}
26
27/// A subagent or workflow-batch name (asked for ~5 words).
28pub const NAME: Limits = Limits { max_words: 12, max_chars: 100 };
29/// A definition's conversation preview (asked for 12 words or fewer).
30pub const PREVIEW: Limits = Limits { max_words: 24, max_chars: 240 };
31/// A one-sentence narration (asked for under 20 words).
32pub const NARRATION: Limits = Limits { max_words: 40, max_chars: 300 };
33/// A next-prompt suggestion is one short imperative; anything longer is an
34/// explanation, not a command.
35pub const NEXT_PROMPT: Limits = Limits { max_words: 28, max_chars: 160 };
36
37/// First-person refusals and offers: a model talking to the reader instead of
38/// producing the text. Specific enough not to fire on an ordinary title.
39const REFUSAL_PHRASES: &[&str] = &[
40    "i don't have",
41    "i do not have",
42    "i don't know",
43    "i cannot",
44    "i can't",
45    "i'm unable",
46    "i am unable",
47    "i'm not able",
48    "i would need",
49    "i'd need",
50    "i need to see",
51    "i need more",
52    "if you'd like",
53    "if you would like",
54    "if you want me",
55    "without knowing",
56    "not enough context",
57    "not enough information",
58    "as an ai",
59];
60
61/// Things a ghost suggestion must not propose on its own initiative: one Tab and
62/// Enter away from the user sending them without having thought of them.
63const RISKY_PHRASES: &[&str] = &[
64    "rm -rf",
65    "--force",
66    "force push",
67    "force-push",
68    "reset --hard",
69    "drop table",
70    "drop database",
71    "delete the database",
72    "delete all",
73    "wipe",
74    "password",
75    "secret",
76    "credential",
77    "api key",
78    "api_key",
79    "token",
80];
81
82/// Lower-cased text with typographic apostrophes straightened, for phrase
83/// matching only (the text handed back is untouched).
84fn normalized(text: &str) -> String {
85    text.replace(['\u{2019}', '\u{2018}'], "'").to_lowercase()
86}
87
88/// Whether `phrase` occurs in `lower` as whole words. A bare substring match
89/// would read "has an AI summary bug" as the refusal "as an ai".
90fn has_phrase(lower: &str, phrase: &str) -> bool {
91    let mut from = 0;
92    while let Some(found) = lower[from..].find(phrase) {
93        let start = from + found;
94        let end = start + phrase.len();
95        let before_ok = lower[..start].chars().next_back().map_or(true, |c| !c.is_alphanumeric());
96        let after_ok = lower[end..].chars().next().map_or(true, |c| !c.is_alphanumeric());
97        if before_ok && after_ok {
98            return true;
99        }
100        // Advance past this match's first character, staying on a char boundary.
101        from = start + lower[start..].chars().next().map_or(1, |c| c.len_utf8());
102    }
103    false
104}
105
106fn has_any(lower: &str, phrases: &[&str]) -> bool {
107    phrases.iter().any(|p| has_phrase(lower, p))
108}
109
110/// Text that is ABOUT the absence of a title rather than a title. Compared after
111/// [`absence_form`], so brackets, quotes and punctuation do not matter.
112///
113/// Exact entries are whole replies only: "none" must not reject "None of the tests
114/// pass on Windows". Prefix entries are specific enough that a real title is very
115/// unlikely to begin with them. The first real examples were `(none yet)`, which is
116/// the title prompt's own placeholder echoed back, and `no goal established yet`;
117/// see SPEC_AMBIENT_SWARM_SUMMARY_HARDENING_2026_10_02.md. The corpus in
118/// `title_corpus.json` is the contract, shared with the frontend.
119const ABSENCE_EXACT: &[&str] = &[
120    "none",
121    "n a",
122    "na",
123    "null",
124    "nothing",
125    "empty",
126    "unknown",
127    "untitled",
128    "untitled session",
129    "untitled conversation",
130    "untitled chat",
131    "tbd",
132    "to be determined",
133    "placeholder",
134    "pending",
135    // The abstain token the title prompts tell the model to use for "no change".
136    // It is not a title, so it must never be stored or shown.
137    "keep",
138    // A model that abstains in its own words instead of the exact token. Exact only:
139    // "Keep alive pings" is a real title.
140    "keep the current title",
141    "keep current title",
142    "keep it",
143    "no change",
144    "no changes",
145    "no update",
146    "unchanged",
147    "not set",
148    "not yet",
149    "no title",
150    "no title yet",
151    "title unavailable",
152    "no summary",
153    "no goal",
154    "no task",
155    "no activity",
156    "no recent activity",
157    "nothing yet",
158];
159
160/// Deliberately few and specific. A prefix rejects every title that begins with it,
161/// so "no title" and "title not" are NOT here: "No title bar on Windows" and "Title
162/// not updating in swarm row" are real titles (ReAgent on #4185). Anything that is
163/// only absence when it is the WHOLE reply belongs in `ABSENCE_EXACT`.
164const ABSENCE_PREFIXES: &[&str] = &[
165    "none yet",
166    "no summary yet",
167    "no goal established",
168    "no goal yet",
169    "no goal set",
170    "no task yet",
171    "no activity yet",
172    "nothing yet",
173    "not yet established",
174];
175
176/// Lower-case, every non-alphanumeric run collapsed to one space, trimmed. So
177/// `(None yet)`, `"none yet."` and `none-yet` all become `none yet`, while
178/// `No-op rename threshold` becomes `no op rename threshold`.
179fn absence_form(text: &str) -> String {
180    let mut out = String::with_capacity(text.len());
181    let mut gap = false;
182    for c in normalized(text).chars() {
183        if c.is_alphanumeric() {
184            if gap && !out.is_empty() {
185                out.push(' ');
186            }
187            gap = false;
188            out.push(c);
189        } else {
190            gap = true;
191        }
192    }
193    out
194}
195
196/// A reply that is entirely a parenthetical or bracketed note. A title is not a
197/// note about the title.
198///
199/// Only ONE balanced pair that wraps the WHOLE text counts. `(WIP) Fix login redirect
200/// (again)` and `[Windows] Fix installer crash [x64]` start and end with brackets but
201/// are real titles: the first pair closes before the end (ReAgent on #4185).
202fn is_wrapped_note(text: &str) -> bool {
203    let t = text.trim();
204    let (open, close) = match (t.chars().next(), t.chars().last()) {
205        (Some('('), Some(')')) => ('(', ')'),
206        (Some('['), Some(']')) => ('[', ']'),
207        _ => return false,
208    };
209    let last = t.chars().count() - 1;
210    let mut depth = 0i32;
211    for (i, c) in t.chars().enumerate() {
212        if c == open {
213            depth += 1;
214        } else if c == close {
215            depth -= 1;
216            // The opening bracket closed before the end: not one wrapping pair.
217            if depth <= 0 && i != last {
218                return false;
219            }
220        }
221    }
222    depth == 0
223}
224
225/// The word the title prompts used for "no change" before the reply format.
226const LEGACY_KEEP_TOKEN: &str = "KEEP";
227
228/// A reply that LEADS with the abstain token in capitals, "KEEP — the title still
229/// fits": the model said "no change" and explained itself. Case-sensitive on purpose:
230/// "Keep alive pings" and "Keep the swarm summary fresh" are real titles, while an
231/// upper-case KEEP is the token the prompt asked for.
232fn leads_with_abstain_token(text: &str) -> bool {
233    let first = text.trim().split_whitespace().next().unwrap_or("");
234    first.trim_matches(|c: char| !c.is_alphanumeric()) == LEGACY_KEEP_TOKEN
235}
236
237fn is_absence(text: &str) -> bool {
238    if is_wrapped_note(text) || leads_with_abstain_token(text) {
239        return true;
240    }
241    let form = absence_form(text);
242    ABSENCE_EXACT.contains(&form.as_str())
243        || ABSENCE_PREFIXES
244            .iter()
245            .any(|p| form == *p || form.strip_prefix(*p).is_some_and(|rest| rest.starts_with(' ')))
246}
247
248/// Returns the line to use, or `None` if the reply is not usable text: empty,
249/// multi-line, over the limits, a placeholder, or a model refusal. This is the
250/// check every ambient reply gets.
251pub fn accept_line(raw: &str, limits: &Limits) -> Option<String> {
252    let text = raw.trim();
253    if text.is_empty() || text.contains('\n') {
254        return None;
255    }
256    if text.chars().count() > limits.max_chars
257        || text.split_whitespace().count() > limits.max_words
258    {
259        return None;
260    }
261    if !text.chars().any(|c| c.is_alphabetic()) {
262        return None;
263    }
264    if is_absence(text) {
265        return None;
266    }
267    let lower = normalized(text);
268    if has_any(&lower, REFUSAL_PHRASES) {
269        return None;
270    }
271    Some(text.to_string())
272}
273
274/// Bounds for judging a title that is ALREADY stored. Generous: a title written
275/// under an older word target or by an older build may be longer than today's.
276pub const STORED_TITLE: Limits = Limits { max_words: 28, max_chars: 200 };
277
278/// Is this stored value a real title? The one predicate behind accepting a reply,
279/// feeding a stored title back into a prompt, and (in the frontend's port of it)
280/// displaying one. A value already in a database from before the check existed,
281/// such as `(none yet)`, is judged here too, so it is never fed back to the model
282/// and never shown.
283pub fn is_usable_title(stored: &str) -> bool {
284    accept_line(stored, &STORED_TITLE).is_some()
285}
286
287/// Returns the suggestion to show, or `None` if the answer is not a usable next
288/// prompt: anything [`accept_line`] rejects, a question, or a risky command.
289pub fn accept_next_prompt(raw: &str) -> Option<String> {
290    let text = accept_line(raw, &NEXT_PROMPT)?;
291    // A question is the model asking, not the user telling.
292    if text.ends_with('?') {
293        return None;
294    }
295    if has_any(&normalized(&text), RISKY_PHRASES) {
296        return None;
297    }
298    Some(text)
299}
300
301#[cfg(test)]
302mod tests {
303    use super::*;
304
305    #[test]
306    fn a_short_imperative_passes_through() {
307        assert_eq!(accept_next_prompt("Run the tests"), Some("Run the tests".into()));
308        assert_eq!(
309            accept_next_prompt("  Debug the blank preview bug next  "),
310            Some("Debug the blank preview bug next".into())
311        );
312    }
313
314    #[test]
315    fn the_reported_refusal_is_rejected() {
316        let reported = "I don't have access to the details of the recent activity beyond the cost summary. \
317            Without knowing what work was done or what the current state of the project is, I cannot \
318            plausibly predict the next instruction. If you'd like me to predict your next step, I'd \
319            need to see the actual recent work or conversation history.";
320        assert_eq!(accept_next_prompt(reported), None);
321        assert_eq!(accept_line(reported, &title_limits(7)), None);
322    }
323
324    #[test]
325    fn short_refusals_and_meta_talk_are_rejected() {
326        for s in [
327            "I cannot predict the next step",
328            "I don't have enough information",
329            "I don\u{2019}t have enough information",
330            "If you'd like me to continue, say so",
331            "Not enough context to decide",
332        ] {
333            assert_eq!(accept_next_prompt(s), None, "{s}");
334        }
335    }
336
337    /// The shared corpus (see `title_corpus.json`): what is about the absence of a
338    /// title is rejected, and a real title that merely contains such a word is not.
339    #[test]
340    fn the_shared_corpus_is_honoured() {
341        #[derive(serde::Deserialize)]
342        struct Corpus {
343            rejected: Vec<String>,
344            accepted: Vec<String>,
345        }
346        let corpus: Corpus = serde_json::from_str(include_str!("title_corpus.json")).expect("corpus parses");
347        assert!(corpus.rejected.len() >= 30 && corpus.accepted.len() >= 10, "the corpus must not be hollowed out");
348        for s in &corpus.rejected {
349            assert_eq!(accept_line(s, &title_limits(7)), None, "must reject {s:?}");
350            assert!(!is_usable_title(s), "a stored {s:?} is not a usable title");
351        }
352        for s in &corpus.accepted {
353            assert!(accept_line(s, &title_limits(7)).is_some(), "must accept {s:?}");
354            assert!(is_usable_title(s), "a stored {s:?} is a usable title");
355        }
356    }
357
358    /// The two values actually found in the owner's database on 2026-10-02.
359    #[test]
360    fn the_values_found_in_the_wild_are_not_titles() {
361        assert!(!is_usable_title("(none yet)"));
362        assert!(!is_usable_title("no goal established yet"));
363        assert!(is_usable_title("Develop hardening spec for swarm ambient summary quality"));
364    }
365
366    // ReAgent on #4185: both of these were false rejects in the first version.
367    #[test]
368    fn titles_that_merely_start_with_a_risky_prefix_or_end_in_brackets_are_accepted() {
369        for s in [
370            "No title bar on Windows",
371            "Title not updating in swarm row",
372            "(WIP) Fix login redirect (again)",
373            "[Windows] Fix installer crash [x64]",
374            "(Draft) Review the plan",
375        ] {
376            assert!(accept_line(s, &title_limits(7)).is_some(), "{s:?}");
377            assert!(is_usable_title(s), "{s:?}");
378        }
379    }
380
381    #[test]
382    fn only_one_balanced_pair_wrapping_the_whole_text_is_a_note() {
383        for note in ["(none yet)", "[no summary]", "(waiting for the user's first message)", "((none yet))", "([x] pending)"] {
384            assert!(is_wrapped_note(note), "{note:?}");
385        }
386        for title in ["(a) b (c)", "[a] b [c]", "(a) (b)", "(a", "a)", "plain"] {
387            assert!(!is_wrapped_note(title), "{title:?}");
388        }
389    }
390
391    // The real model returned the exact token in every abstain case when tried live, but
392    // a reply that abstains in its own words must not overwrite a good title either.
393    #[test]
394    fn an_abstain_in_the_models_own_words_is_not_a_title() {
395        for s in [
396            "KEEP — the title still fits",
397            "KEEP: unchanged",
398            "KEEP the current title",
399            "Keep current title",
400            "keep the current title",
401            "No change",
402            "Unchanged",
403            "No update",
404        ] {
405            assert_eq!(accept_line(s, &title_limits(7)), None, "{s:?}");
406        }
407        for s in ["Keep alive pings", "Keep the swarm summary fresh", "Unchanged files report fix"] {
408            assert!(accept_line(s, &title_limits(7)).is_some(), "{s:?}");
409        }
410    }
411
412    #[test]
413    fn the_abstain_token_is_never_a_title() {
414        for s in ["KEEP", "keep", "Keep.", "(KEEP)", " KEEP "] {
415            assert_eq!(accept_line(s, &title_limits(7)), None, "{s:?}");
416        }
417    }
418
419    #[test]
420    fn whole_word_matching_keeps_real_titles_that_start_with_an_absence_word() {
421        for s in ["None of the tests pass", "Untitled-tab bug", "Nothing else matters here fix", "Keep alive pings"] {
422            assert!(accept_line(s, &title_limits(7)).is_some(), "{s:?}");
423        }
424    }
425
426    #[test]
427    fn empty_and_placeholder_text_is_rejected() {
428        for s in ["", "   ", "...", "-", "None", "N/A", "none.", "(empty)", "null"] {
429            assert_eq!(accept_next_prompt(s), None, "{s:?}");
430            assert_eq!(accept_line(s, &NAME), None, "{s:?}");
431        }
432    }
433
434    #[test]
435    fn questions_are_rejected_as_next_prompts_but_not_as_titles() {
436        assert_eq!(accept_next_prompt("Should I run the tests?"), None);
437        assert_eq!(accept_next_prompt("What should happen next?"), None);
438        assert_eq!(
439            accept_line("Why does login fail?", &title_limits(7)),
440            Some("Why does login fail?".into())
441        );
442    }
443
444    #[test]
445    fn multi_line_and_over_long_text_is_rejected() {
446        assert_eq!(accept_next_prompt("Run the tests\nthen push"), None);
447        let long = "Fix ".to_string() + &"the thing and ".repeat(20);
448        assert_eq!(accept_next_prompt(&long), None);
449        let many_words = vec!["go"; 30].join(" ");
450        assert_eq!(accept_next_prompt(&many_words), None);
451    }
452
453    #[test]
454    fn risky_commands_are_rejected() {
455        for s in [
456            "Run rm -rf on the build folder",
457            "Force push the branch",
458            "Push with --force",
459            "git reset --hard origin/main",
460            "Print the API token",
461            "Drop table users",
462            "Wipe the disk",
463        ] {
464            assert_eq!(accept_next_prompt(s), None, "{s}");
465        }
466    }
467
468    #[test]
469    fn ordinary_commands_pass_and_over_blocking_is_deliberate() {
470        // Plurals ("tokens", "secrets") are separate words and are NOT matched by
471        // "token"/"secret": add them to the list if that ever matters.
472        assert_eq!(
473            accept_next_prompt("Merge the PR once CI is green"),
474            Some("Merge the PR once CI is green".into())
475        );
476    }
477
478    #[test]
479    fn the_text_handed_back_is_not_rewritten() {
480        // Apostrophes are straightened for matching only.
481        assert_eq!(
482            accept_line("Fix the user\u{2019}s login", &NAME),
483            Some("Fix the user\u{2019}s login".into())
484        );
485    }
486
487    #[test]
488    fn titles_and_names_may_name_problems_and_secrets_in_ordinary_words() {
489        assert_eq!(
490            accept_line("Fix insufficient permissions error", &title_limits(7)),
491            Some("Fix insufficient permissions error".into())
492        );
493        assert_eq!(
494            accept_line("Rotate the API token flow", &NAME),
495            Some("Rotate the API token flow".into())
496        );
497    }
498
499    #[test]
500    fn titles_and_names_reject_refusals_paragraphs_and_overruns() {
501        assert_eq!(accept_line("I cannot determine a title without more context", &title_limits(7)), None);
502        assert_eq!(accept_line("Task\nName: login", &NAME), None);
503        let long = vec!["word"; 40].join(" ");
504        assert_eq!(accept_line(&long, &NAME), None);
505        assert_eq!(accept_line(&long, &title_limits(7)), None);
506        assert!(accept_line("Fix login blank screen bug", &NAME).is_some());
507    }
508
509    #[test]
510    fn narration_allows_a_sentence_but_not_a_paragraph() {
511        assert!(accept_line("I started the dev server in the background.", &NARRATION).is_some());
512        let paragraph = vec!["word"; 60].join(" ");
513        assert_eq!(accept_line(&paragraph, &NARRATION), None);
514    }
515
516    #[test]
517    fn phrases_match_whole_words_only() {
518        // "has an AI" contains the substring "as an ai".
519        for t in ["Fix pane has an AI summary bug", "Agent was an AI wrapper", "Rewire the bias in token counts"] {
520            assert_eq!(accept_line(t, &title_limits(7)).as_deref(), Some(t), "{t}");
521        }
522        assert_eq!(accept_line("As an AI, I have no title", &NAME), None);
523        assert_eq!(accept_line("Sorry, as an AI model I can't say", &NAME), None);
524        assert!(has_phrase("sorry. i cannot do that", "i cannot"));
525        assert!(!has_phrase("lexi cannot", "i cannot"));
526    }
527
528    #[test]
529    fn risky_words_inside_other_words_no_longer_block_a_next_prompt() {
530        // "secret" used to block "secretary"; whole-word matching fixes the false
531        // positive while "secrets" and "tokens" stay out of reach by design.
532        assert_eq!(accept_next_prompt("Email the secretary"), Some("Email the secretary".into()));
533        assert_eq!(accept_next_prompt("Print the secret"), None);
534    }
535
536    #[test]
537    fn title_limits_scale_with_the_requested_word_count() {
538        assert_eq!(title_limits(7).max_words, 15);
539        assert_eq!(title_limits(20).max_words, 28);
540    }
541}