1#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16pub struct Limits {
17 pub max_words: usize,
18 pub max_chars: usize,
19}
20
21pub fn title_limits(word_target: u32) -> Limits {
24 Limits { max_words: word_target as usize + 8, max_chars: 200 }
25}
26
27pub const NAME: Limits = Limits { max_words: 12, max_chars: 100 };
29pub const PREVIEW: Limits = Limits { max_words: 24, max_chars: 240 };
31pub const NARRATION: Limits = Limits { max_words: 40, max_chars: 300 };
33pub const NEXT_PROMPT: Limits = Limits { max_words: 28, max_chars: 160 };
36
37const 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
61const 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
82fn normalized(text: &str) -> String {
85 text.replace(['\u{2019}', '\u{2018}'], "'").to_lowercase()
86}
87
88fn 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 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
110const 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 "keep",
138 "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
160const 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
176fn 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
196fn 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 if depth <= 0 && i != last {
218 return false;
219 }
220 }
221 }
222 depth == 0
223}
224
225const LEGACY_KEEP_TOKEN: &str = "KEEP";
227
228fn 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
248pub 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
274pub const STORED_TITLE: Limits = Limits { max_words: 28, max_chars: 200 };
277
278pub fn is_usable_title(stored: &str) -> bool {
284 accept_line(stored, &STORED_TITLE).is_some()
285}
286
287pub fn accept_next_prompt(raw: &str) -> Option<String> {
290 let text = accept_line(raw, &NEXT_PROMPT)?;
291 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 #[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 #[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 #[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 #[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 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 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(¶graph, &NARRATION), None);
514 }
515
516 #[test]
517 fn phrases_match_whole_words_only() {
518 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 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}