1use crate::message::Message;
15
16pub const MAX_NAME_CHARS: usize = 60;
19
20pub const UPGRADE_INPUT_CHARS: usize = 1_000;
23
24pub fn derive(opening: &str) -> Option<String> {
30 let line = opening
31 .lines()
32 .map(str::trim)
33 .find(|l| !l.is_empty())?
34 .trim_start_matches(['#', '>', '-', '*', '`', ' ']);
36 let one_line = line.split_whitespace().collect::<Vec<_>>().join(" ");
37 let one_line = one_line.trim();
38 if one_line.is_empty() {
39 return None;
40 }
41 let trimmed = one_line.trim_end_matches(['.', ',', ';', ':', '-', '?', '!']);
44 if trimmed.is_empty() {
45 return None;
46 }
47 Some(cap(trimmed))
48}
49
50fn cap(text: &str) -> String {
53 if text.chars().count() <= MAX_NAME_CHARS {
54 return text.to_string();
55 }
56 let mut cut = text
57 .char_indices()
58 .nth(MAX_NAME_CHARS)
59 .map(|(i, _)| i)
60 .unwrap_or(text.len());
61 let head = &text[..cut];
62 let halfway = text.chars().count() / 2;
63 if let Some(space) = head.rfind(' ') {
64 if head[..space].chars().count() >= halfway {
65 cut = space;
66 }
67 }
68 text[..cut].trim_end().to_string()
69}
70
71pub fn upgrade_prompt(opening: &str) -> Vec<Message> {
75 const SYSTEM: &str = "\
76You name conversations. Given the opening message of one, answer with a JSON object of exactly \
77one key: {\"title\": \"...\"}. The title is 3 to 7 words, lowercase unless a name needs capitals, \
78and says what the work is about — not that it is a conversation, not a summary of the whole \
79thing, no trailing full stop, no quotes inside. Answer with the JSON object and nothing else.";
80
81 let excerpt: String = opening.chars().take(UPGRADE_INPUT_CHARS).collect();
82 vec![
83 Message::system(SYSTEM),
84 Message::user(format!("OPENING MESSAGE:\n{excerpt}")),
85 ]
86}
87
88pub fn clean_reply(reply: &str, opening: &str) -> std::result::Result<String, String> {
95 let text = reply.trim();
96 if text.is_empty() {
97 return Err("the reply was empty".into());
98 }
99 let value: serde_json::Value = serde_json::from_str(text)
100 .map_err(|_| format!("the reply was not a JSON object: {}", head(text)))?;
101 let raw = match &value {
102 serde_json::Value::Object(map) => map
104 .get("title")
105 .and_then(|v| v.as_str())
106 .ok_or_else(|| "the reply had no `title` string".to_string())?,
107 serde_json::Value::String(s) => s.as_str(),
108 other => return Err(format!("the reply was a {}, not an object", kind(other))),
109 };
110 if raw.chars().any(char::is_control) {
113 return Err("the reply's title had control characters".into());
114 }
115 let name = tidy(raw);
116 if name.is_empty() {
117 return Err("the reply's title was empty".into());
118 }
119 let chars = name.chars().count();
120 if chars > MAX_NAME_CHARS {
121 return Err(format!("the reply's title was {chars} characters"));
122 }
123 let words = name.split_whitespace().count();
124 if words > 8 {
125 return Err(format!(
126 "the reply's title was {words} words, which is a summary"
127 ));
128 }
129 if name.ends_with('.') || name.ends_with(',') || name.ends_with(';') {
130 return Err("the reply's title ended like a sentence".into());
131 }
132 if let Some(derived) = derive(opening) {
135 let same = name.to_lowercase();
136 let derived_lower = derived.to_lowercase();
137 if same == derived_lower || (words <= 2 && derived_lower.starts_with(&same)) {
138 return Err("the reply's title was the opening message again".into());
139 }
140 }
141 Ok(name)
142}
143
144fn tidy(raw: &str) -> String {
147 let mut text = raw.trim();
148 for prefix in ["title:", "name:", "session:", "title -", "title \u{2013}"] {
149 if text.len() > prefix.len()
153 && text.is_char_boundary(prefix.len())
154 && text[..prefix.len()].eq_ignore_ascii_case(prefix)
155 {
156 text = &text[prefix.len()..];
157 break;
158 }
159 }
160 let text = text
161 .trim()
162 .trim_matches([
163 '"', '\'', '`', '*', '\u{201c}', '\u{201d}', '\u{2018}', '\u{2019}',
164 ])
165 .trim();
166 text.split_whitespace().collect::<Vec<_>>().join(" ")
167}
168
169fn head(text: &str) -> String {
170 let short: String = text.chars().take(40).collect();
171 if text.chars().count() > 40 {
172 format!("{short}…")
173 } else {
174 short
175 }
176}
177
178fn kind(value: &serde_json::Value) -> &'static str {
179 match value {
180 serde_json::Value::Null => "null",
181 serde_json::Value::Bool(_) => "boolean",
182 serde_json::Value::Number(_) => "number",
183 serde_json::Value::String(_) => "string",
184 serde_json::Value::Array(_) => "array",
185 serde_json::Value::Object(_) => "object",
186 }
187}
188
189#[cfg(test)]
190mod tests {
191 use super::*;
192
193 #[test]
196 fn the_first_line_is_the_name() {
197 assert_eq!(
198 derive("fix the gateway restart loop\nit happens on boot").as_deref(),
199 Some("fix the gateway restart loop")
200 );
201 assert_eq!(
202 derive("\n\n ## rename sessions \n").as_deref(),
203 Some("rename sessions")
204 );
205 assert_eq!(derive(" "), None, "nothing to name");
206 assert_eq!(derive("..."), None, "punctuation only is not a name");
207 }
208
209 #[test]
212 fn a_name_loses_the_full_stop_and_cuts_at_a_word() {
213 assert_eq!(
214 derive("add a title column to the store.").as_deref(),
215 Some("add a title column to the store")
216 );
217 let long = "word ".repeat(40);
218 let name = derive(&long).unwrap();
219 assert!(name.chars().count() <= MAX_NAME_CHARS, "{name}");
220 assert!(!name.ends_with(' '), "{name:?}");
221 assert!(name.ends_with("word"), "cut at a word boundary: {name:?}");
222 let huge = "é".repeat(200);
225 assert_eq!(derive(&huge).unwrap().chars().count(), MAX_NAME_CHARS);
226 }
227
228 #[test]
232 fn only_a_short_object_becomes_a_name() {
233 let opening = "the dashboard's session list is unreadable at a hundred sessions";
234 let ok = |r: &str| clean_reply(r, opening);
235 assert_eq!(
236 ok("{\"title\": \"session names from the model\"}").as_deref(),
237 Ok("session names from the model")
238 );
239 assert_eq!(
240 ok("{\"title\": \"Title: session names\"}").as_deref(),
241 Ok("session names"),
242 "a label is noise, not a name"
243 );
244 assert_eq!(
245 ok(" \"quoted name\" ").as_deref(),
246 Ok("quoted name"),
247 "a bare string still works"
248 );
249 assert!(
250 ok("Sure! Here is a title: session names").is_err(),
251 "prose is not JSON"
252 );
253 assert!(
254 ok("{\"name\": \"session names\"}").is_err(),
255 "the wrong key"
256 );
257 assert!(ok("{\"title\": \"\"}").is_err(), "an empty name");
258 assert!(ok("{\"title\": 42}").is_err(), "a number is not a name");
259 assert!(
260 ok("{\"title\": \"rename the sessions and add a title column to the store and then\"}")
261 .is_err(),
262 "eleven words is a summary"
263 );
264 assert!(
265 ok("{\"title\": \"a name that ends like a sentence.\"}").is_err(),
266 "a full stop"
267 );
268 assert!(
269 ok("{\"title\": \"two\\nlines\"}").is_err(),
270 "control characters"
271 );
272 }
273
274 #[test]
277 fn an_echo_of_the_opening_is_not_an_upgrade() {
278 let opening = "fix the gateway restart loop";
279 assert!(clean_reply("{\"title\": \"fix the gateway restart loop\"}", opening).is_err());
280 assert_eq!(
281 clean_reply("{\"title\": \"gateway restart loop\"}", opening).as_deref(),
282 Ok("gateway restart loop"),
283 "fewer words is a name, and not an echo"
284 );
285 }
286
287 #[test]
290 fn the_prompt_asks_for_one_object_and_sends_a_bounded_excerpt() {
291 let long = "x".repeat(5_000);
292 let asked = upgrade_prompt(&long);
293 assert_eq!(asked.len(), 2);
294 assert!(asked[0].content.as_deref().unwrap().contains("{\"title\""));
295 let sent = asked[1].content.as_deref().unwrap();
296 assert_eq!(
297 sent.chars().count(),
298 "OPENING MESSAGE:\n".chars().count() + UPGRADE_INPUT_CHARS
299 );
300 }
301}