use crate::message::Message;
pub const MAX_NAME_CHARS: usize = 60;
pub const UPGRADE_INPUT_CHARS: usize = 1_000;
pub fn derive(opening: &str) -> Option<String> {
let line = opening
.lines()
.map(str::trim)
.find(|l| !l.is_empty())?
.trim_start_matches(['#', '>', '-', '*', '`', ' ']);
let one_line = line.split_whitespace().collect::<Vec<_>>().join(" ");
let one_line = one_line.trim();
if one_line.is_empty() {
return None;
}
let trimmed = one_line.trim_end_matches(['.', ',', ';', ':', '-', '?', '!']);
if trimmed.is_empty() {
return None;
}
Some(cap(trimmed))
}
fn cap(text: &str) -> String {
if text.chars().count() <= MAX_NAME_CHARS {
return text.to_string();
}
let mut cut = text
.char_indices()
.nth(MAX_NAME_CHARS)
.map(|(i, _)| i)
.unwrap_or(text.len());
let head = &text[..cut];
let halfway = text.chars().count() / 2;
if let Some(space) = head.rfind(' ') {
if head[..space].chars().count() >= halfway {
cut = space;
}
}
text[..cut].trim_end().to_string()
}
pub fn upgrade_prompt(opening: &str) -> Vec<Message> {
const SYSTEM: &str = "\
You name conversations. Given the opening message of one, answer with a JSON object of exactly \
one key: {\"title\": \"...\"}. The title is 3 to 7 words, lowercase unless a name needs capitals, \
and says what the work is about — not that it is a conversation, not a summary of the whole \
thing, no trailing full stop, no quotes inside. Answer with the JSON object and nothing else.";
let excerpt: String = opening.chars().take(UPGRADE_INPUT_CHARS).collect();
vec![
Message::system(SYSTEM),
Message::user(format!("OPENING MESSAGE:\n{excerpt}")),
]
}
pub fn clean_reply(reply: &str, opening: &str) -> std::result::Result<String, String> {
let text = reply.trim();
if text.is_empty() {
return Err("the reply was empty".into());
}
let value: serde_json::Value = serde_json::from_str(text)
.map_err(|_| format!("the reply was not a JSON object: {}", head(text)))?;
let raw = match &value {
serde_json::Value::Object(map) => map
.get("title")
.and_then(|v| v.as_str())
.ok_or_else(|| "the reply had no `title` string".to_string())?,
serde_json::Value::String(s) => s.as_str(),
other => return Err(format!("the reply was a {}, not an object", kind(other))),
};
if raw.chars().any(char::is_control) {
return Err("the reply's title had control characters".into());
}
let name = tidy(raw);
if name.is_empty() {
return Err("the reply's title was empty".into());
}
let chars = name.chars().count();
if chars > MAX_NAME_CHARS {
return Err(format!("the reply's title was {chars} characters"));
}
let words = name.split_whitespace().count();
if words > 8 {
return Err(format!(
"the reply's title was {words} words, which is a summary"
));
}
if name.ends_with('.') || name.ends_with(',') || name.ends_with(';') {
return Err("the reply's title ended like a sentence".into());
}
if let Some(derived) = derive(opening) {
let same = name.to_lowercase();
let derived_lower = derived.to_lowercase();
if same == derived_lower || (words <= 2 && derived_lower.starts_with(&same)) {
return Err("the reply's title was the opening message again".into());
}
}
Ok(name)
}
fn tidy(raw: &str) -> String {
let mut text = raw.trim();
for prefix in ["title:", "name:", "session:", "title -", "title \u{2013}"] {
if text.len() > prefix.len()
&& text.is_char_boundary(prefix.len())
&& text[..prefix.len()].eq_ignore_ascii_case(prefix)
{
text = &text[prefix.len()..];
break;
}
}
let text = text
.trim()
.trim_matches([
'"', '\'', '`', '*', '\u{201c}', '\u{201d}', '\u{2018}', '\u{2019}',
])
.trim();
text.split_whitespace().collect::<Vec<_>>().join(" ")
}
fn head(text: &str) -> String {
let short: String = text.chars().take(40).collect();
if text.chars().count() > 40 {
format!("{short}…")
} else {
short
}
}
fn kind(value: &serde_json::Value) -> &'static str {
match value {
serde_json::Value::Null => "null",
serde_json::Value::Bool(_) => "boolean",
serde_json::Value::Number(_) => "number",
serde_json::Value::String(_) => "string",
serde_json::Value::Array(_) => "array",
serde_json::Value::Object(_) => "object",
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_first_line_is_the_name() {
assert_eq!(
derive("fix the gateway restart loop\nit happens on boot").as_deref(),
Some("fix the gateway restart loop")
);
assert_eq!(
derive("\n\n ## rename sessions \n").as_deref(),
Some("rename sessions")
);
assert_eq!(derive(" "), None, "nothing to name");
assert_eq!(derive("..."), None, "punctuation only is not a name");
}
#[test]
fn a_name_loses_the_full_stop_and_cuts_at_a_word() {
assert_eq!(
derive("add a title column to the store.").as_deref(),
Some("add a title column to the store")
);
let long = "word ".repeat(40);
let name = derive(&long).unwrap();
assert!(name.chars().count() <= MAX_NAME_CHARS, "{name}");
assert!(!name.ends_with(' '), "{name:?}");
assert!(name.ends_with("word"), "cut at a word boundary: {name:?}");
let huge = "é".repeat(200);
assert_eq!(derive(&huge).unwrap().chars().count(), MAX_NAME_CHARS);
}
#[test]
fn only_a_short_object_becomes_a_name() {
let opening = "the dashboard's session list is unreadable at a hundred sessions";
let ok = |r: &str| clean_reply(r, opening);
assert_eq!(
ok("{\"title\": \"session names from the model\"}").as_deref(),
Ok("session names from the model")
);
assert_eq!(
ok("{\"title\": \"Title: session names\"}").as_deref(),
Ok("session names"),
"a label is noise, not a name"
);
assert_eq!(
ok(" \"quoted name\" ").as_deref(),
Ok("quoted name"),
"a bare string still works"
);
assert!(
ok("Sure! Here is a title: session names").is_err(),
"prose is not JSON"
);
assert!(
ok("{\"name\": \"session names\"}").is_err(),
"the wrong key"
);
assert!(ok("{\"title\": \"\"}").is_err(), "an empty name");
assert!(ok("{\"title\": 42}").is_err(), "a number is not a name");
assert!(
ok("{\"title\": \"rename the sessions and add a title column to the store and then\"}")
.is_err(),
"eleven words is a summary"
);
assert!(
ok("{\"title\": \"a name that ends like a sentence.\"}").is_err(),
"a full stop"
);
assert!(
ok("{\"title\": \"two\\nlines\"}").is_err(),
"control characters"
);
}
#[test]
fn an_echo_of_the_opening_is_not_an_upgrade() {
let opening = "fix the gateway restart loop";
assert!(clean_reply("{\"title\": \"fix the gateway restart loop\"}", opening).is_err());
assert_eq!(
clean_reply("{\"title\": \"gateway restart loop\"}", opening).as_deref(),
Ok("gateway restart loop"),
"fewer words is a name, and not an echo"
);
}
#[test]
fn the_prompt_asks_for_one_object_and_sends_a_bounded_excerpt() {
let long = "x".repeat(5_000);
let asked = upgrade_prompt(&long);
assert_eq!(asked.len(), 2);
assert!(asked[0].content.as_deref().unwrap().contains("{\"title\""));
let sent = asked[1].content.as_deref().unwrap();
assert_eq!(
sent.chars().count(),
"OPENING MESSAGE:\n".chars().count() + UPGRADE_INPUT_CHARS
);
}
}