1use std::path::{Path, PathBuf};
15
16use serde::{Deserialize, Serialize};
17use serde_json::Value;
18
19use crate::learn;
20
21pub const IDLE_MS: i64 = 30 * 60 * 1000;
24pub const PRUNE_MS: i64 = crate::clock::DAY_MS;
27pub const FILES: usize = 3;
29const PROMPT_CHARS: usize = 100;
31
32#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
33pub struct Presence {
34 pub session: String,
35 pub harness: String,
36 #[serde(default)]
38 pub engineer: String,
39 #[serde(default)]
41 pub repo: String,
42 pub collective: String,
43 #[serde(default)]
45 pub prompt: String,
46 #[serde(default)]
48 pub files: Vec<String>,
49 pub event: String,
51 pub ms: i64,
52 pub started: i64,
54 #[serde(default, skip_serializing_if = "Option::is_none")]
56 pub pid: Option<u32>,
57}
58
59#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
60#[serde(rename_all = "lowercase")]
61pub enum State {
62 Working,
63 Waiting,
64 Idle,
65 Ended,
66}
67
68impl State {
69 pub fn name(self) -> &'static str {
70 match self {
71 State::Working => "working",
72 State::Waiting => "waiting",
73 State::Idle => "idle",
74 State::Ended => "ended",
75 }
76 }
77}
78
79pub fn dir(home: &Path) -> PathBuf {
80 home.join("presence")
81}
82
83pub fn safe(session: &str) -> String {
85 session.chars().filter(|c| c.is_ascii_alphanumeric() || *c == '-').collect()
86}
87
88pub fn path(home: &Path, session: &str) -> PathBuf {
89 dir(home).join(format!("{}.json", safe(session)))
90}
91
92pub fn remote_path(home: &Path) -> PathBuf {
94 home.join("mesh").join("presence.jsonl")
95}
96
97pub fn read(home: &Path, session: &str) -> Option<Presence> {
98 serde_json::from_slice(&std::fs::read(path(home, session)).ok()?).ok()
99}
100
101fn file_of(input: &Value, cwd: &str) -> Option<String> {
103 let ti = input.get("tool_input")?;
104 let f = ["file_path", "notebook_path"].iter().find_map(|k| ti.get(*k).and_then(Value::as_str)).filter(|f| !f.trim().is_empty())?;
105 let rel = Path::new(f).strip_prefix(cwd).ok().map(|p| p.display().to_string()).filter(|p| !p.is_empty());
106 Some(rel.unwrap_or_else(|| f.to_string()))
107}
108
109pub fn first_line(prompt: &str) -> String {
111 let line = prompt.lines().map(str::trim).find(|l| !l.is_empty()).unwrap_or_default();
112 let mut out: String = line.chars().take(PROMPT_CHARS).collect();
113 if line.chars().count() > PROMPT_CHARS {
114 out.push('…');
115 }
116 out
117}
118
119pub fn update(
122 prev: Option<Presence>,
123 collective: &str,
124 harness: &str,
125 event: &str,
126 input: &Value,
127 now: i64,
128 who: impl FnOnce(&str) -> (String, String),
129) -> Presence {
130 let cwd = input.get("cwd").and_then(Value::as_str).unwrap_or_default();
131 let session = input.get("session_id").and_then(Value::as_str).unwrap_or("unknown");
132 let mut p = prev.unwrap_or_else(|| {
133 let (engineer, repo) = who(cwd);
134 Presence {
135 session: session.into(),
136 harness: harness.into(),
137 engineer,
138 repo,
139 collective: collective.into(),
140 prompt: String::new(),
141 files: Vec::new(),
142 event: String::new(),
143 ms: now,
144 started: now,
145 pid: None,
146 }
147 });
148 p.event = event.into();
149 p.ms = now;
150 if let Some(pid) = input.get("pid").and_then(Value::as_u64).and_then(|v| u32::try_from(v).ok()) {
151 p.pid = Some(pid);
152 }
153 match event {
154 "prompt" => {
155 let line = first_line(input.get("prompt").and_then(Value::as_str).unwrap_or_default());
156 if !line.is_empty() {
157 p.prompt = line;
158 }
159 }
160 "post_tool" | "post_tool_failure" => {
161 if let Some(f) = file_of(input, cwd) {
162 p.files.retain(|x| *x != f);
163 p.files.insert(0, f);
164 p.files.truncate(FILES);
165 }
166 }
167 _ => {}
168 }
169 p
170}
171
172pub fn touch(home: &Path, collective: &str, harness: &str, event: &str, input: &Value, now: i64) -> Option<Presence> {
175 let session = input.get("session_id").and_then(Value::as_str).unwrap_or("unknown");
176 let p = update(read(home, session), collective, harness, event, input, now, |cwd| {
177 (learn::engineer(cwd), borg_trace::repo_key(cwd).rsplit('/').next().unwrap_or_default().to_string())
178 });
179 write(home, &p).ok()?;
180 if event == "prompt" {
181 prune(home, now);
182 }
183 Some(p)
184}
185
186pub fn write(home: &Path, p: &Presence) -> std::io::Result<()> {
187 let d = dir(home);
188 std::fs::create_dir_all(&d)?;
189 let target = path(home, &p.session);
190 let tmp = d.join(format!(".{}.{}.tmp", safe(&p.session), std::process::id()));
191 std::fs::write(&tmp, serde_json::to_vec(p).unwrap_or_default())?;
192 std::fs::rename(&tmp, &target).inspect_err(|_| {
193 let _ = std::fs::remove_file(&tmp);
194 })
195}
196
197pub fn prune(home: &Path, now: i64) {
199 let Ok(rd) = std::fs::read_dir(dir(home)) else { return };
200 for e in rd.flatten() {
201 let old = e
202 .metadata()
203 .and_then(|m| m.modified())
204 .ok()
205 .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
206 .is_some_and(|d| now - d.as_millis() as i64 > PRUNE_MS);
207 if old {
208 let _ = std::fs::remove_file(e.path());
211 if let Some(session) = e.path().file_stem().and_then(|s| s.to_str()).filter(|s| !s.starts_with('.')) {
213 crate::listen::forget(home, session);
214 }
215 }
216 }
217}
218
219pub fn local(home: &Path, now: i64) -> Vec<Presence> {
221 let Ok(rd) = std::fs::read_dir(dir(home)) else { return Vec::new() };
222 let mut v: Vec<Presence> = rd
223 .flatten()
224 .filter(|e| e.path().extension().is_some_and(|x| x == "json"))
225 .filter_map(|e| serde_json::from_slice::<Presence>(&std::fs::read(e.path()).ok()?).ok())
226 .filter(|p| now - p.ms <= PRUNE_MS)
227 .collect();
228 v.sort_by(|a, b| (a.started, &a.session).cmp(&(b.started, &b.session)));
229 v
230}
231
232#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
235pub struct Remote {
236 pub p: Presence,
237 pub key: String,
238 pub sig: String,
239}
240
241pub fn remote(home: &Path, now: i64) -> Vec<Remote> {
243 let text = std::fs::read_to_string(remote_path(home)).unwrap_or_default();
244 let mut v: Vec<Remote> = text.lines().filter_map(|l| serde_json::from_str::<Remote>(l).ok()).filter(|r| now - r.p.ms <= PRUNE_MS).collect();
245 v.sort_by(|a, b| (&a.key, &a.p.session, b.p.ms).cmp(&(&b.key, &b.p.session, a.p.ms)));
246 v.dedup_by(|a, b| a.key == b.key && a.p.session == b.p.session);
247 v
248}
249
250pub fn synced_path(home: &Path) -> PathBuf {
255 home.join("mesh").join("synced.json")
256}
257
258pub fn synced(home: &Path) -> std::collections::BTreeMap<String, i64> {
260 std::fs::read_to_string(synced_path(home)).ok().and_then(|t| serde_json::from_str(&t).ok()).unwrap_or_default()
261}
262
263pub fn note_synced(home: &Path, key: &str, ms: i64) -> std::io::Result<()> {
269 let mut all = synced(home);
270 if all.get(key).is_some_and(|&held| held >= ms && held <= crate::learn::now_ms()) {
271 return Ok(());
272 }
273 all.insert(key.into(), ms);
274 write_synced(home, &all)
275}
276
277pub fn forget_synced(home: &Path, key: &str) -> std::io::Result<()> {
279 let mut all = synced(home);
280 if all.remove(key).is_none() {
281 return Ok(());
282 }
283 write_synced(home, &all)
284}
285
286fn write_synced(home: &Path, all: &std::collections::BTreeMap<String, i64>) -> std::io::Result<()> {
287 write_mesh(home, &synced_path(home), all)
288}
289
290pub(crate) fn write_mesh<T: Serialize>(home: &Path, p: &Path, all: &T) -> std::io::Result<()> {
292 std::fs::create_dir_all(home.join("mesh"))?;
293 let tmp = p.with_extension(format!("{}.tmp", std::process::id())); std::fs::write(&tmp, serde_json::to_string(all).unwrap_or_default())?;
295 std::fs::rename(&tmp, p)
296}
297
298pub use crate::protocol::{Mismatch, forget_mismatch, mismatches, note_mismatch, protocols_path, retain_mismatches};
299
300pub fn reads_path(home: &Path) -> PathBuf {
306 home.join("mesh").join("reads.json")
307}
308
309pub fn reads(home: &Path) -> std::collections::BTreeMap<String, u8> {
311 std::fs::read_to_string(reads_path(home)).ok().and_then(|t| serde_json::from_str(&t).ok()).unwrap_or_default()
312}
313
314pub fn note_reads(home: &Path, key: &str, v: u8) -> std::io::Result<()> {
317 let mut all = reads(home);
318 if all.get(key) == Some(&v) {
319 return Ok(());
320 }
321 all.insert(key.into(), v);
322 write_mesh(home, &reads_path(home), &all)
323}
324
325pub fn retain_reads(home: &Path, keep: impl Fn(&str) -> bool) -> std::io::Result<()> {
329 let mut all = reads(home);
330 let before = all.len();
331 all.retain(|k, _| keep(k));
332 if all.len() == before {
333 return Ok(());
334 }
335 write_mesh(home, &reads_path(home), &all)
336}
337
338pub fn mesh_checks(routes: &[crate::collective::Route]) -> Vec<(crate::harness::Level, String)> {
344 use crate::collective::Route;
345 routes
346 .iter()
347 .filter_map(|r| match r {
348 Route::Collective { name, home, .. } => Some((name, home)),
349 Route::Off => None,
350 })
351 .flat_map(|(name, home)| {
352 let mismatched = mismatches(home);
353 let versions: Vec<_> = crate::protocol::versions(home)
354 .into_iter()
355 .filter(|(k, _)| !mismatched.contains_key(k))
356 .filter_map(|(k, v)| crate::protocol::check(&k, &v, crate::update::VERSION))
357 .map(|(level, line)| (level, format!("mesh {name}: {line}")))
358 .collect();
359 let lines = mismatched.into_iter().map(move |(k, m)| (crate::harness::Level::Warn, format!("mesh {name}: {}", m.line(&k))));
360 lines.chain(versions)
361 })
362 .collect()
363}
364
365pub fn state(p: &Presence, now: i64, alive: impl Fn(u32) -> bool) -> State {
367 if p.event == "end" || p.pid.is_some_and(|pid| !alive(pid)) {
368 State::Ended
369 } else if now - p.ms > IDLE_MS {
370 State::Idle
371 } else if p.event == "stop" {
372 State::Waiting
373 } else {
374 State::Working
375 }
376}
377
378pub fn alive(pid: u32) -> bool {
380 i32::try_from(pid).is_ok_and(crate::live::alive)
381}
382
383#[cfg(test)]
384mod tests {
385 use super::*;
386 use serde_json::json;
387
388 fn tmp(tag: &str) -> PathBuf {
389 let d = std::env::temp_dir().join(format!("borg-presence-{tag}-{}", std::process::id()));
390 let _ = std::fs::remove_dir_all(&d);
391 d
392 }
393
394 fn who(_: &str) -> (String, String) {
395 ("alice@x".into(), "app".into())
396 }
397
398 #[test]
401 fn a_members_last_session_never_moves_back() {
402 let h = tmp("synced");
403 assert!(synced(&h).is_empty());
404 note_synced(&h, "k1", 200).unwrap();
405 note_synced(&h, "k1", 100).unwrap();
406 note_synced(&h, "k2", 50).unwrap();
407 assert_eq!(synced(&h).into_iter().collect::<Vec<_>>(), [("k1".to_string(), 200), ("k2".to_string(), 50)]);
408 note_synced(&h, "k1", 300).unwrap();
409 assert_eq!(synced(&h)["k1"], 300);
410 forget_synced(&h, "k1").unwrap();
411 assert_eq!(synced(&h).into_keys().collect::<Vec<_>>(), ["k2"], "a failed dial drops the member");
412 let _ = std::fs::remove_dir_all(&h);
413 }
414
415 #[test]
416 fn doctor_names_a_member_on_another_mesh_protocol() {
417 use crate::collective::Route;
418 use crate::harness::Level;
419 let home = tmp("protocols-doctor");
420 let route = Route::Collective { name: "team".into(), home: home.clone(), share: crate::collective::Share::Team };
421 assert!(mesh_checks(std::slice::from_ref(&route)).is_empty());
422 let m = Mismatch { theirs: "borg/mesh/5".into(), ours: "borg/mesh/10".into(), ms: 1 };
423 note_mismatch(&home, "abcdef0123456789", m).unwrap();
424 let checks = mesh_checks(&[route, Route::Off]);
425 assert_eq!(checks.len(), 1, "{checks:?}");
426 assert_eq!(checks[0].0, Level::Warn);
427 assert!(checks[0].1.starts_with("mesh team: peer abcdef012345 speaks borg/mesh/5") && checks[0].1.ends_with("upgrade it"), "{checks:?}");
428 let n = crate::protocol::current();
430 let v = |borg: &str, protocol| crate::protocol::PeerVersion { borg: Some(borg.into()), protocol, ms: 1, engineer: None };
431 crate::protocol::note_version(&home, "k-old", &v("0.6.0", n - 1)).unwrap();
432 crate::protocol::note_version(&home, "k-new", &v("99.0.0", n)).unwrap();
433 crate::protocol::note_version(&home, "abcdef0123456789", &v("0.1.0", n - 9)).unwrap();
434 let checks = mesh_checks(std::slice::from_ref(&Route::Collective { name: "team".into(), home: home.clone(), share: crate::collective::Share::Team }));
435 assert_eq!(checks.len(), 3, "a mismatched member is named once: {checks:?}");
436 assert_eq!(
437 (checks[1].0, checks[1].1.as_str()),
438 (Level::Ok, format!("mesh team: peer k-new runs borg 99.0.0 (borg/mesh/{n}), this node {}", crate::update::VERSION).as_str())
439 );
440 assert_eq!(checks[2].0, Level::Warn);
441 assert!(checks[2].1.ends_with(crate::protocol::note(n).unwrap()), "{checks:?}");
442 let _ = std::fs::remove_dir_all(&home);
443 }
444
445 #[test]
447 fn a_protocol_mismatch_is_kept_until_a_session_completes() {
448 let h = tmp("protocols");
449 assert!(mismatches(&h).is_empty());
450 let old = Mismatch { theirs: "borg/mesh/5".into(), ours: "borg/mesh/10".into(), ms: 1 };
451 note_mismatch(&h, "abcdef0123456789", old.clone()).unwrap();
452 note_mismatch(&h, "k2", Mismatch { theirs: "borg/mesh/11".into(), ..old.clone() }).unwrap();
453 let all = mismatches(&h);
454 assert_eq!(
455 all["abcdef0123456789"].line("abcdef0123456789"),
456 "peer abcdef012345 speaks borg/mesh/5, this node borg/mesh/10: nothing syncs with it; upgrade it"
457 );
458 assert!(all["k2"].line("k2").ends_with("upgrade this node"), "a newer peer: this node is the old one");
459 forget_mismatch(&h, "abcdef0123456789").unwrap();
460 assert_eq!(mismatches(&h).into_keys().collect::<Vec<_>>(), ["k2"]);
461 let _ = std::fs::remove_dir_all(&h);
462 }
463
464 #[test]
465 fn a_record_ahead_of_the_clock_gives_way() {
466 let h = tmp("synced-skew");
468 let now = crate::learn::now_ms();
469 note_synced(&h, "k1", now + 3_600_000).unwrap();
470 note_synced(&h, "k1", now).unwrap();
471 assert_eq!(synced(&h)["k1"], now);
472 let _ = std::fs::remove_dir_all(&h);
473 }
474
475 #[test]
476 fn a_session_record_follows_its_hooks() {
477 let ev = |e: &str, extra: Value| {
478 let mut v = json!({"session_id": "s1", "cwd": "/w/app"});
479 v.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
480 (e.to_string(), v)
481 };
482 let mut p = None;
483 let steps = [
484 ev("prompt", json!({"prompt": "\n fix the flaky sync test\nand more", "pid": 4242})),
485 ev("post_tool", json!({"tool_name": "Edit", "tool_input": {"file_path": "/w/app/src/a.rs"}})),
486 ev("post_tool", json!({"tool_name": "Read", "tool_input": {"file_path": "/w/app/src/b.rs"}})),
487 ev("post_tool", json!({"tool_name": "Bash", "tool_input": {"command": "ls"}})),
488 ev("post_tool", json!({"tool_name": "Edit", "tool_input": {"file_path": "/w/app/src/a.rs"}})),
489 ev("post_tool", json!({"tool_name": "Write", "tool_input": {"file_path": "/elsewhere/c.rs"}})),
490 ev("post_tool", json!({"tool_name": "Write", "tool_input": {"file_path": "/w/app/d.rs"}})),
491 ];
492 for (i, (e, input)) in steps.iter().enumerate() {
493 p = Some(update(p, "corp", "claude", e, input, 1000 + i as i64, who));
494 }
495 let p = p.unwrap();
496 assert_eq!(p.prompt, "fix the flaky sync test", "first non-empty line");
497 assert_eq!(p.files, ["d.rs", "/elsewhere/c.rs", "src/a.rs"], "newest first, deduped, at most 3, relative inside cwd");
498 assert_eq!((p.started, p.ms, p.pid, p.engineer.as_str(), p.repo.as_str()), (1000, 1006, Some(4242), "alice@x", "app"));
499 let long = "x".repeat(300);
500 assert_eq!(first_line(&long).chars().count(), PROMPT_CHARS + 1);
501 }
502
503 #[test]
504 fn write_read_prune_and_state() {
505 let home = tmp("wrp");
506 let input = json!({"session_id": "s/../1", "cwd": "/w/app", "prompt": "hello"});
507 let p = update(None, "corp", "omp", "prompt", &input, 5_000, who);
508 write(&home, &p).unwrap();
509 assert_eq!(read(&home, "s/../1"), Some(p.clone()));
510 assert_eq!(path(&home, "s/../1"), dir(&home).join("s1.json"), "a session id never escapes the directory");
511 assert_eq!(local(&home, 5_000), vec![p.clone()]);
512 assert!(std::fs::read_dir(dir(&home)).unwrap().count() == 1, "no temp file left behind");
513
514 assert_eq!(state(&p, 5_000, |_| true), State::Working);
515 assert_eq!(state(&Presence { event: "stop".into(), ..p.clone() }, 5_000, |_| true), State::Waiting);
516 assert_eq!(state(&p, 5_000 + IDLE_MS + 1, |_| true), State::Idle);
517 assert_eq!(state(&Presence { event: "end".into(), ..p.clone() }, 5_000, |_| true), State::Ended);
518 assert_eq!(state(&Presence { pid: Some(7), ..p.clone() }, 5_000, |_| false), State::Ended, "the harness process is gone");
519
520 assert!(local(&home, 5_000 + PRUNE_MS + 1).is_empty());
522 let far = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_millis() as i64 + PRUNE_MS + 1000;
523 prune(&home, far);
524 assert!(read(&home, "s/../1").is_none());
525 let _ = std::fs::remove_dir_all(&home);
526 }
527
528 #[test]
529 fn remote_keeps_the_latest_per_member_and_session() {
530 let home = tmp("remote");
531 std::fs::create_dir_all(home.join("mesh")).unwrap();
532 let p = |s: &str, ms: i64| Presence {
533 session: s.into(),
534 harness: "claude".into(),
535 engineer: "bob@x".into(),
536 repo: "r".into(),
537 collective: "corp".into(),
538 prompt: format!("at {ms}"),
539 files: vec![],
540 event: "prompt".into(),
541 ms,
542 started: 1,
543 pid: None,
544 };
545 let line = |s: &str, ms: i64, key: &str| serde_json::to_string(&Remote { p: p(s, ms), key: key.into(), sig: "00".into() }).unwrap();
546 let text = [line("a", 10, "k1"), line("a", 30, "k1"), line("a", 20, "k1"), line("a", 5, "k2"), "garbage".into()].join("\n");
547 std::fs::write(remote_path(&home), text).unwrap();
548 let r = remote(&home, 40);
549 assert_eq!(r.iter().map(|r| (r.key.as_str(), r.p.ms)).collect::<Vec<_>>(), [("k1", 30), ("k2", 5)]);
550 assert!(remote(&home, 40 + PRUNE_MS).is_empty(), "a day old: gone");
551 let _ = std::fs::remove_dir_all(&home);
552 }
553
554 #[test]
557 fn a_resumed_session_is_not_shown_its_messages_again() {
558 let home = tmp("resume");
559 let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_millis() as i64;
560 let input = json!({"session_id": "s2"});
561 write(&home, &update(None, "corp", "claude", "prompt", &input, now, who)).unwrap();
562 let from = crate::msg::Sender { by: "s1".into(), name: "Two of Five".into(), harness: "claude".into(), node: "n1".into() };
563 crate::msg::send(&home, crate::msg::Message::new(crate::msg::TELL, &from, "s2", None, now, "the API is stable"), now).unwrap();
564 let caps = crate::harness::by_name("claude").expect("a harness").caps();
565 assert!(crate::msg::deliver(&home, caps, "prompt", &input, Some(now), now, None).is_some(), "shown");
566
567 let later = now + PRUNE_MS + 60_000;
568 prune(&home, later);
569 assert!(read(&home, "s2").is_none(), "the presence is pruned");
570 write(&home, &update(None, "corp", "claude", "prompt", &input, later, who)).unwrap();
571 assert_eq!(crate::msg::deliver(&home, caps, "prompt", &input, Some(later), later, None), None, "not shown again");
572 let _ = std::fs::remove_dir_all(&home);
573 }
574}