1use std::collections::HashSet;
15
16use crate::ambient::validate::is_usable_title;
17use crate::backend::obj::{self, Block};
18use crate::backend::storage::store::Store;
19
20pub const META_TITLE: &str = "term:ambient_summary";
22
23pub const META_TITLE_AT: &str = "term:ambient_summary_at";
28pub const META_TITLE_TURN: &str = "term:ambient_summary_turn";
29
30const META_HUMAN_TURNS: &str = "term:human_turns";
33
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36pub enum Replace {
37 IfEmpty,
40 IfNews,
43}
44
45pub fn store_title(
50 store: &Store,
51 block_id: &str,
52 title: &str,
53 replace: Replace,
54 turn: Option<u32>,
55 still_current: impl Fn() -> bool,
56) -> Result<bool, String> {
57 store_title_at(store, block_id, title, replace, turn, agentmux_common::time::now_ms(), still_current)
58}
59
60fn stamp(block: &mut Block, turn: Option<u32>, now: i64) {
63 let turn = turn.map(i64::from).or_else(|| block.meta.get(META_HUMAN_TURNS).and_then(serde_json::Value::as_i64));
64 block.meta.insert(META_TITLE_AT.to_string(), serde_json::Value::from(now));
65 match turn {
66 Some(t) => block.meta.insert(META_TITLE_TURN.to_string(), serde_json::Value::from(t)),
67 None => block.meta.remove(META_TITLE_TURN),
68 };
69}
70
71fn store_title_at(
72 store: &Store,
73 block_id: &str,
74 title: &str,
75 replace: Replace,
76 turn: Option<u32>,
77 now: i64,
78 still_current: impl Fn() -> bool,
79) -> Result<bool, String> {
80 if !is_usable_title(title) {
81 return Ok(false);
82 }
83 store
84 .with_tx(|tx| {
85 if !still_current() {
86 return Ok(false);
87 }
88 let mut block = tx.must_get::<Block>(block_id)?;
89 let current = obj::meta_get_string(&block.meta, META_TITLE, "");
90 if is_usable_title(¤t) {
91 let keep = match replace {
92 Replace::IfEmpty => true,
93 Replace::IfNews => !is_title_news(¤t, title),
94 };
95 if keep {
96 return Ok(false);
97 }
98 }
99 block.meta.insert(META_TITLE.to_string(), serde_json::Value::String(title.to_string()));
100 stamp(&mut block, turn, now);
101 tx.update(&mut block)?;
102 Ok(true)
103 })
104 .map_err(|e| e.to_string())
105}
106
107pub fn confirm_title(
114 store: &Store,
115 block_id: &str,
116 candidate: &str,
117 turn: Option<u32>,
118 still_current: impl Fn() -> bool,
119) -> Result<bool, String> {
120 confirm_title_at(store, block_id, candidate, turn, agentmux_common::time::now_ms(), still_current)
121}
122
123fn confirm_title_at(
124 store: &Store,
125 block_id: &str,
126 candidate: &str,
127 turn: Option<u32>,
128 now: i64,
129 still_current: impl Fn() -> bool,
130) -> Result<bool, String> {
131 if !is_usable_title(candidate) {
132 return Ok(false);
133 }
134 store
135 .with_tx(|tx| {
136 if !still_current() {
137 return Ok(false);
138 }
139 let mut block = tx.must_get::<Block>(block_id)?;
140 let current = obj::meta_get_string(&block.meta, META_TITLE, "");
141 if !is_usable_title(¤t) || is_title_news(¤t, candidate) {
142 return Ok(false);
143 }
144 stamp(&mut block, turn, now);
145 tx.update(&mut block)?;
146 Ok(true)
147 })
148 .map_err(|e| e.to_string())
149}
150
151const STOP_WORDS: &[&str] = &[
153 "a", "an", "the", "and", "or", "of", "to", "for", "in", "on", "with", "by", "at", "from", "into", "its", "it",
154];
155
156const NEWS_MAX_OVERLAP: f64 = 0.5;
158
159fn topic_words(title: &str) -> HashSet<String> {
160 title
161 .to_lowercase()
162 .split(|c: char| !c.is_ascii_alphanumeric())
163 .filter(|w| !w.is_empty() && !STOP_WORDS.contains(w))
164 .map(str::to_string)
165 .collect()
166}
167
168pub fn is_title_news(current: &str, candidate: &str) -> bool {
172 let a = topic_words(current);
173 let b = topic_words(candidate);
174 if a.is_empty() || b.is_empty() {
175 return a.len() != b.len();
176 }
177 let shared = a.intersection(&b).count();
178 let overlap = shared as f64 / (a.len() + b.len() - shared) as f64;
179 overlap < NEWS_MAX_OVERLAP
180}
181
182#[cfg(test)]
183mod tests {
184 use super::*;
185
186 #[test]
187 fn a_rewording_is_not_news() {
188 for (current, candidate) in [
189 ("Fix the login race", "Fix login race condition"),
190 ("Fix the login race", "fix the LOGIN race"),
191 ("Harden the swarm ambient summary", "Harden swarm summary"),
192 ] {
193 assert!(!is_title_news(current, candidate), "{current:?} -> {candidate:?}");
194 }
195 }
196
197 #[test]
198 fn a_new_topic_is_news() {
199 for (current, candidate) in [
200 ("Fix the login race", "Set up CI for the docs site"),
201 ("Harden the swarm ambient summary", "Add UDP discovery for LAN peers"),
202 ("Review PR 4230", "Write the multi-host swarm spec"),
203 ] {
204 assert!(is_title_news(current, candidate), "{current:?} -> {candidate:?}");
205 }
206 }
207
208 fn store_with_block(meta: &[(&str, &str)]) -> Store {
209 let store = Store::open_in_memory().unwrap();
210 let mut block = Block {
211 oid: "b1".to_string(),
212 parentoref: String::new(),
213 version: 0,
214 runtimeopts: None,
215 stickers: None,
216 meta: obj::MetaMapType::new(),
217 subblockids: None,
218 };
219 for (k, v) in meta {
220 block.meta.insert(k.to_string(), serde_json::Value::String(v.to_string()));
221 }
222 store.insert(&mut block).unwrap();
223 store
224 }
225
226 fn title_of(store: &Store) -> String {
227 obj::meta_get_string(&store.must_get::<Block>("b1").unwrap().meta, META_TITLE, "")
228 }
229
230 #[test]
231 fn either_writer_fills_an_empty_or_placeholder_title() {
232 for replace in [Replace::IfEmpty, Replace::IfNews] {
233 for before in [&[][..], &[(META_TITLE, "(none yet)")][..]] {
234 let store = store_with_block(before);
235 assert_eq!(store_title(&store, "b1", "Fix the login race", replace, None, || true), Ok(true));
236 assert_eq!(title_of(&store), "Fix the login race");
237 }
238 }
239 }
240
241 #[test]
242 fn recovery_never_replaces_a_title() {
243 let store = store_with_block(&[(META_TITLE, "Set up CI for the docs site")]);
244 assert_eq!(store_title(&store, "b1", "Something else entirely", Replace::IfEmpty, None, || true), Ok(false));
245 assert_eq!(title_of(&store), "Set up CI for the docs site");
246 }
247
248 #[test]
249 fn the_pane_replaces_a_title_only_with_news() {
250 let store = store_with_block(&[(META_TITLE, "Fix the login race")]);
251 assert_eq!(store_title(&store, "b1", "Fix login race condition", Replace::IfNews, None, || true), Ok(false));
252 assert_eq!(title_of(&store), "Fix the login race");
253 assert_eq!(store_title(&store, "b1", "Set up CI for the docs site", Replace::IfNews, None, || true), Ok(true));
254 assert_eq!(title_of(&store), "Set up CI for the docs site");
255 }
256
257 #[test]
258 fn a_superseded_request_stores_nothing() {
259 let store = store_with_block(&[(META_TITLE, "Set up CI for the docs site")]);
260 assert_eq!(store_title(&store, "b1", "Fix the login race", Replace::IfNews, None, || false), Ok(false));
261 assert_eq!(title_of(&store), "Set up CI for the docs site");
262 }
263
264 #[test]
265 fn a_placeholder_is_never_stored() {
266 let store = store_with_block(&[]);
267 assert_eq!(store_title(&store, "b1", "(none yet)", Replace::IfNews, None, || true), Ok(false));
268 assert_eq!(title_of(&store), "");
269 }
270
271 #[test]
272 fn other_meta_survives_the_write() {
273 let store = store_with_block(&[("agentName", "AgentX")]);
274 store_title(&store, "b1", "Fix the login race", Replace::IfEmpty, None, || true).unwrap();
275 let meta = store.must_get::<Block>("b1").unwrap().meta;
276 assert_eq!(obj::meta_get_string(&meta, "agentName", ""), "AgentX");
277 }
278 fn number_of(store: &Store, key: &str) -> Option<i64> {
279 store.must_get::<Block>("b1").unwrap().meta.get(key).and_then(serde_json::Value::as_i64)
280 }
281
282 fn set_number(store: &Store, key: &str, value: i64) {
283 let mut block = store.must_get::<Block>("b1").unwrap();
284 block.meta.insert(key.to_string(), serde_json::Value::from(value));
285 store.update(&mut block).unwrap();
286 }
287
288 #[test]
289 fn a_stored_title_is_stamped_with_its_time_and_the_callers_turn() {
290 let store = store_with_block(&[]);
291 assert_eq!(store_title_at(&store, "b1", "Fix the login race", Replace::IfNews, Some(7), 1_000, || true), Ok(true));
292 assert_eq!(number_of(&store, META_TITLE_AT), Some(1_000));
293 assert_eq!(number_of(&store, META_TITLE_TURN), Some(7));
294 }
295
296 #[test]
297 fn without_a_turn_the_stamp_takes_the_sessions_human_turn_count() {
298 let store = store_with_block(&[]);
299 set_number(&store, META_HUMAN_TURNS, 4);
300 store_title_at(&store, "b1", "Fix the login race", Replace::IfEmpty, None, 1_000, || true).unwrap();
301 assert_eq!(number_of(&store, META_TITLE_TURN), Some(4));
302 }
303
304 #[test]
305 fn a_title_that_is_kept_is_not_restamped_by_a_store() {
306 let store = store_with_block(&[(META_TITLE, "Fix the login race")]);
307 set_number(&store, META_TITLE_AT, 5);
308 assert_eq!(store_title_at(&store, "b1", "Fix login race condition", Replace::IfNews, Some(9), 1_000, || true), Ok(false));
309 assert_eq!(number_of(&store, META_TITLE_AT), Some(5));
310 }
311
312 #[test]
313 fn a_rewording_found_on_a_refresh_confirms_the_title_and_restamps_it() {
314 let store = store_with_block(&[(META_TITLE, "Fix the login race")]);
315 set_number(&store, META_TITLE_AT, 0);
316 assert_eq!(confirm_title_at(&store, "b1", "Fix login race condition", Some(12), 9_000, || true), Ok(true));
317 assert_eq!(title_of(&store), "Fix the login race");
318 assert_eq!(number_of(&store, META_TITLE_AT), Some(9_000));
319 assert_eq!(number_of(&store, META_TITLE_TURN), Some(12));
320 }
321
322 #[test]
323 fn a_new_goal_or_an_abstention_does_not_confirm_the_old_title() {
324 let store = store_with_block(&[(META_TITLE, "Fix the login race")]);
325 set_number(&store, META_TITLE_AT, 0);
326 assert_eq!(confirm_title_at(&store, "b1", "Set up CI for the docs site", Some(12), 9_000, || true), Ok(false));
327 assert_eq!(confirm_title_at(&store, "b1", "(none yet)", Some(12), 9_000, || true), Ok(false));
328 assert_eq!(confirm_title_at(&store, "b1", "Fix login race condition", Some(12), 9_000, || false), Ok(false));
329 assert_eq!(number_of(&store, META_TITLE_AT), Some(0));
330 }
331}