1use std::io::Write;
27use std::path::{Path, PathBuf};
28use std::time::Duration;
29
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31pub enum Mode {
32 Hook,
33 Live,
34}
35
36impl Mode {
37 pub fn name(self) -> &'static str {
38 match self {
39 Mode::Hook => "hook",
40 Mode::Live => "live",
41 }
42 }
43}
44
45#[derive(Debug, Clone, PartialEq, Eq)]
48pub struct Resolved {
49 pub mode: Mode,
50 pub source: &'static str,
51 pub warning: Option<String>,
52}
53
54pub const DEFAULT: Mode = Mode::Live;
57
58pub fn resolve(env: Option<&str>, configured: Option<&str>) -> Resolved {
61 let pick = |v: &str, source: &'static str| match v.trim().to_ascii_lowercase().as_str() {
62 "hook" => Resolved { mode: Mode::Hook, source, warning: None },
63 "live" => Resolved { mode: Mode::Live, source, warning: None },
64 _ => Resolved { mode: DEFAULT, source, warning: Some(format!("{source}: mode {v:?} is neither \"hook\" nor \"live\"; using {}", DEFAULT.name())) },
65 };
66 match (env.filter(|v| !v.trim().is_empty()), configured.filter(|v| !v.trim().is_empty())) {
67 (Some(v), _) => pick(v, "BORG_MODE"),
68 (None, Some(v)) => pick(v, "config"),
69 (None, None) => Resolved { mode: DEFAULT, source: "default", warning: None },
70 }
71}
72
73pub fn of(cfg: Option<&crate::collective::Config>, name: &str) -> Resolved {
75 let configured = cfg.and_then(|c| c.collectives.iter().find(|e| e.name == name)).and_then(|e| e.mode.as_deref());
76 resolve(std::env::var("BORG_MODE").ok().as_deref(), configured)
77}
78
79pub fn current() -> Mode {
82 resolve(std::env::var("BORG_MODE").ok().as_deref(), None).mode
83}
84
85pub fn unsupported() -> Option<&'static str> {
88 if std::env::var("BORG_MATCH").as_deref() == Ok("bm25") {
89 Some("BORG_MATCH=bm25")
90 } else if std::env::var_os("BORG_ONLY").is_some() {
91 Some("BORG_ONLY")
92 } else if std::env::var_os("BORG_CRITIC").is_some() {
93 Some("BORG_CRITIC")
94 } else {
95 None
96 }
97}
98
99pub fn debounce_ms() -> i64 {
101 std::env::var("BORG_LIVE_DEBOUNCE_S").ok().and_then(|v| v.trim().parse::<i64>().ok()).unwrap_or(45).max(0) * 1000
102}
103
104pub fn stale_ms() -> i64 {
107 2 * crate::predict::timeout().as_millis() as i64 + 30_000
108}
109
110fn beside(ctx: &Path, ext: &str) -> PathBuf {
111 ctx.with_extension(ext)
112}
113
114pub fn counter_file(ctx: &Path) -> PathBuf {
115 beside(ctx, "live.n")
116}
117
118pub fn mark_file(ctx: &Path) -> PathBuf {
119 beside(ctx, "live.mark")
120}
121
122pub fn lock_file(ctx: &Path) -> PathBuf {
123 beside(ctx, "live.lock")
124}
125
126pub fn count(ctx: &Path) -> u64 {
128 std::fs::read_to_string(counter_file(ctx)).map_or(0, |t| t.lines().count() as u64)
129}
130
131pub fn bump(ctx: &Path, tool: &str) {
133 let _ = std::fs::OpenOptions::new().create(true).append(true).open(counter_file(ctx)).and_then(|mut f| writeln!(f, "{tool}"));
134}
135
136#[derive(Debug, Clone, Copy, PartialEq, Eq)]
138pub struct Mark {
139 pub covered: u64,
140 pub started_ms: i64,
141 pub turn: Option<u64>,
142}
143
144pub fn read_mark(ctx: &Path) -> Option<Mark> {
145 let t = std::fs::read_to_string(mark_file(ctx)).ok()?;
146 let mut it = t.split_whitespace();
147 Some(Mark { covered: it.next()?.parse().ok()?, started_ms: it.next()?.parse().ok()?, turn: it.next().and_then(|v| v.parse().ok()) })
148}
149
150pub fn write_mark(ctx: &Path, m: Mark) {
151 let turn = m.turn.map_or(String::new(), |t| format!(" {t}"));
152 let _ = std::fs::write(mark_file(ctx), format!("{} {}{turn}\n", m.covered, m.started_ms));
153}
154
155#[derive(Debug, Clone, Copy, PartialEq, Eq)]
156pub enum Lock {
157 Free,
158 Held,
159 Stale,
161}
162
163pub fn alive(pid: i32) -> bool {
165 pid > 0 && (unsafe { libc::kill(pid, 0) } == 0 || std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM))
167}
168
169fn state_of(text: &str, file_ms: i64, now: i64, stale_after: i64, alive: impl Fn(i32) -> bool) -> Lock {
172 let mut it = text.split_whitespace();
173 match (it.next().and_then(|p| p.parse::<i32>().ok()), it.next().and_then(|m| m.parse::<i64>().ok())) {
174 (Some(pid), Some(ms)) if alive(pid) && now - ms <= stale_after => Lock::Held,
175 (Some(_), Some(_)) => Lock::Stale,
176 _ if now - file_ms > stale_after => Lock::Stale,
177 _ => Lock::Held,
178 }
179}
180
181fn modified_ms(path: &Path) -> i64 {
182 std::fs::metadata(path).and_then(|m| m.modified()).ok().and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()).map_or(0, |d| d.as_millis() as i64)
183}
184
185pub fn lock_state(ctx: &Path, now: i64, stale_after: i64, alive: impl Fn(i32) -> bool) -> Lock {
187 let path = lock_file(ctx);
188 let Ok(t) = std::fs::read_to_string(&path) else { return Lock::Free };
189 state_of(&t, modified_ms(&path), now, stale_after, alive)
190}
191
192#[derive(Debug)]
194pub struct Guard {
195 path: PathBuf,
196 text: String,
197}
198
199impl Drop for Guard {
200 fn drop(&mut self) {
201 if std::fs::read_to_string(&self.path).is_ok_and(|t| t == self.text) {
202 let _ = std::fs::remove_file(&self.path);
203 }
204 }
205}
206
207pub fn acquire(ctx: &Path, now: i64) -> Option<Guard> {
213 let path = lock_file(ctx);
214 let pid = std::process::id();
215 let text = format!("{pid} {now}\n");
216 let tmp = path.with_extension(format!("lock.{pid}"));
217 std::fs::write(&tmp, &text).ok()?;
218 let mut got = None;
219 for _ in 0..2 {
220 if std::fs::hard_link(&tmp, &path).is_ok() {
221 got = Some(Guard { path: path.clone(), text: text.clone() });
222 break;
223 }
224 let Ok(seen) = std::fs::read_to_string(&path) else { continue };
225 if state_of(&seen, modified_ms(&path), now, stale_ms(), alive) != Lock::Stale {
226 break;
227 }
228 let aside = path.with_extension(format!("lock.stale.{pid}"));
229 if std::fs::rename(&path, &aside).is_err() {
230 continue;
231 }
232 let moved = std::fs::read_to_string(&aside).unwrap_or_default();
233 if moved != seen {
234 let _ = std::fs::hard_link(&aside, &path);
235 let _ = std::fs::remove_file(&aside);
236 break;
237 }
238 let _ = std::fs::remove_file(&aside);
239 }
240 let _ = std::fs::remove_file(&tmp);
241 got
242}
243
244pub fn locked<T>(file: &Path, f: impl FnOnce() -> T) -> T {
248 let held = lock_of(file).ok();
249 let out = f();
250 if let Some(l) = held {
251 let _ = l.unlock();
252 }
253 out
254}
255
256fn lock_of(file: &Path) -> std::io::Result<std::fs::File> {
258 let lock = std::fs::OpenOptions::new()
259 .create(true)
260 .truncate(false)
261 .write(true)
262 .open(file.with_extension(format!("{}.lock", file.extension().and_then(|e| e.to_str()).unwrap_or_default())))?;
263 lock.lock()?;
264 Ok(lock)
265}
266
267pub fn decide(mode: Mode, lock: Lock, count: u64, mark: Option<Mark>, now: i64, debounce: i64) -> Result<(), &'static str> {
270 if mode != Mode::Live {
271 return Err("hook mode");
272 }
273 if lock == Lock::Held {
274 return Err("running");
275 }
276 if count <= mark.map_or(0, |m| m.covered) {
277 return Err("nothing new");
278 }
279 if mark.is_some_and(|m| now - m.started_ms < debounce) {
280 return Err("debounce");
281 }
282 Ok(())
283}
284
285pub fn covered(lock: Lock, count: u64, mark: Option<Mark>, turn: u64) -> bool {
289 lock != Lock::Held && count > 0 && mark.is_some_and(|m| m.covered == count && m.turn == Some(turn))
290}
291
292pub fn wait_free(ctx: &Path, max_ms: u64) -> Lock {
294 let until = std::time::Instant::now() + std::time::Duration::from_millis(max_ms);
295 loop {
296 let l = lock_state(ctx, crate::learn::now_ms(), stale_ms(), alive);
297 if l != Lock::Held || std::time::Instant::now() >= until {
298 return l;
299 }
300 std::thread::sleep(std::time::Duration::from_millis(200));
301 }
302}
303
304pub const STOP_WAIT_MS: u64 = 15_000;
306
307pub fn stop_wait(budget: Option<Duration>) -> Duration {
310 let wait = Duration::from_millis(STOP_WAIT_MS);
311 budget.map_or(wait, |b| wait.min(b / 4))
312}
313
314pub fn call_limit(budget: Option<Duration>, spent: Duration) -> Duration {
317 let Some(b) = budget else { return crate::predict::timeout() };
318 crate::predict::timeout().min(b.saturating_sub(spent).saturating_sub(Duration::from_secs(3)))
319}
320
321#[cfg(test)]
322mod tests {
323 use super::*;
324
325 fn tmp(tag: &str) -> PathBuf {
326 let d = std::env::temp_dir().join(format!("borg-live-{tag}-{}", std::process::id()));
327 let _ = std::fs::remove_dir_all(&d);
328 std::fs::create_dir_all(&d).unwrap();
329 d.join("s1.ctx")
330 }
331
332 #[test]
333 fn env_beats_config_and_unknown_values_fall_back_to_the_default() {
334 assert_eq!(resolve(None, None), Resolved { mode: Mode::Live, source: "default", warning: None });
335 assert_eq!(resolve(None, Some("live")).mode, Mode::Live);
336 assert_eq!(resolve(Some("hook"), Some("live")), Resolved { mode: Mode::Hook, source: "BORG_MODE", warning: None });
337 assert_eq!(resolve(Some(" LIVE "), None).mode, Mode::Live);
338 assert_eq!(resolve(Some(""), Some("live")).source, "config", "an empty BORG_MODE is unset");
339 let r = resolve(None, Some("eager"));
340 assert_eq!(r.mode, Mode::Live);
341 assert!(r.warning.unwrap().contains("\"eager\""));
342 }
343
344 #[test]
345 fn a_check_starts_only_in_live_mode_with_new_changes_no_running_check_and_after_the_debounce() {
346 let m = |covered, started_ms| Some(Mark { covered, started_ms, turn: None });
347 assert_eq!(decide(Mode::Live, Lock::Free, 1, None, 0, 45_000), Ok(()), "the first change checks at once");
348 assert_eq!(decide(Mode::Hook, Lock::Free, 1, None, 0, 45_000), Err("hook mode"));
349 assert_eq!(decide(Mode::Live, Lock::Held, 3, m(1, 0), 100_000, 45_000), Err("running"));
350 assert_eq!(decide(Mode::Live, Lock::Stale, 3, m(1, 0), 100_000, 45_000), Ok(()), "a stale lock does not block");
351 assert_eq!(decide(Mode::Live, Lock::Free, 2, m(2, 0), 100_000, 45_000), Err("nothing new"));
352 assert_eq!(decide(Mode::Live, Lock::Free, 0, None, 0, 45_000), Err("nothing new"));
353 assert_eq!(decide(Mode::Live, Lock::Free, 3, m(2, 60_000), 100_000, 45_000), Err("debounce"));
354 assert_eq!(decide(Mode::Live, Lock::Free, 3, m(2, 55_000), 100_000, 45_000), Ok(()));
355 }
356
357 #[test]
358 fn the_lock_is_held_while_its_process_lives_and_stale_when_gone_or_too_old() {
359 let ctx = tmp("lock");
360 assert_eq!(lock_state(&ctx, 1000, 120_000, |_| true), Lock::Free);
361 let g = acquire(&ctx, 1000).expect("free lock taken");
362 assert!(acquire(&ctx, 1001).is_none(), "a second check does not run");
363 assert_eq!(lock_state(&ctx, 2000, 120_000, |_| true), Lock::Held);
364 assert_eq!(lock_state(&ctx, 2000, 120_000, |_| false), Lock::Stale, "its process is gone");
365 assert_eq!(lock_state(&ctx, 200_000, 120_000, |_| true), Lock::Stale, "older than twice the timeout");
366 drop(g);
367 assert_eq!(lock_state(&ctx, 2000, 120_000, |_| true), Lock::Free, "the guard removes it");
368 std::fs::write(lock_file(&ctx), format!("{} 1000\n", i32::MAX)).unwrap();
370 assert!(!alive(i32::MAX));
371 let g = acquire(&ctx, 2000).expect("stale lock taken over");
372 std::fs::write(lock_file(&ctx), "1 2000\n").unwrap();
374 drop(g);
375 assert!(lock_file(&ctx).exists(), "not this guard's lock any more");
376 }
377
378 #[test]
379 fn a_half_written_lock_is_held_until_its_file_is_old() {
380 assert_eq!(state_of("", 1000, 2000, 120_000, |_| false), Lock::Held, "being written: never taken over");
381 assert_eq!(state_of("12", 1000, 2000, 120_000, |_| false), Lock::Held);
382 assert_eq!(state_of("", 1000, 200_000, 120_000, |_| false), Lock::Stale, "left empty long ago");
383 assert_eq!(state_of("7 1000", 0, 2000, 120_000, |_| true), Lock::Held);
384 let ctx = tmp("half");
385 std::fs::write(lock_file(&ctx), "").unwrap();
386 assert!(acquire(&ctx, crate::learn::now_ms()).is_none(), "an empty, fresh lock is someone's");
387 }
388
389 #[test]
390 fn counter_and_mark_round_trip() {
391 let ctx = tmp("mark");
392 assert_eq!((count(&ctx), read_mark(&ctx)), (0, None));
393 bump(&ctx, "Edit");
394 bump(&ctx, "Bash");
395 assert_eq!(count(&ctx), 2);
396 write_mark(&ctx, Mark { covered: 2, started_ms: 77, turn: Some(9) });
397 assert_eq!(read_mark(&ctx), Some(Mark { covered: 2, started_ms: 77, turn: Some(9) }));
398 std::fs::write(mark_file(&ctx), "2 77\n").unwrap();
399 assert_eq!(read_mark(&ctx), Some(Mark { covered: 2, started_ms: 77, turn: None }), "a mark of before turns");
400 }
401
402 #[test]
403 fn the_stop_skips_only_when_a_check_of_this_turn_covered_every_change() {
404 let m = Some(Mark { covered: 3, started_ms: 0, turn: Some(40) });
405 assert!(covered(Lock::Free, 3, m, 40));
406 assert!(!covered(Lock::Held, 3, m, 40), "a running check");
407 assert!(!covered(Lock::Free, 4, m, 40), "a change after the check");
408 assert!(!covered(Lock::Free, 3, m, 41), "the check was an earlier turn's");
409 assert!(!covered(Lock::Free, 3, Some(Mark { covered: 3, started_ms: 0, turn: None }), 40), "a mark without its turn");
410 assert!(!covered(Lock::Free, 0, None, 40));
411 }
412
413 #[test]
414 fn the_stop_fits_its_wait_and_model_call_into_the_harness_budget() {
415 let s = Duration::from_secs;
416 assert_eq!((stop_wait(None), call_limit(None, s(30))), (s(15), s(45)), "Claude Code: unchanged");
417 assert_eq!((stop_wait(Some(s(90))), call_limit(Some(s(90)), s(15))), (s(15), s(45)), "opencode: room for both");
418 assert_eq!((stop_wait(Some(s(28))), call_limit(Some(s(28)), s(7))), (s(7), s(18)), "omp");
419 assert_eq!(call_limit(Some(s(28)), s(11)), s(14), "time spent before the call comes off it");
420 assert_eq!(call_limit(Some(s(28)), s(27)), Duration::ZERO);
421 assert_eq!(stop_wait(Some(s(8))), s(2));
422 }
423
424 #[test]
425 fn a_lock_that_cannot_be_taken_still_runs_f_unlocked() {
426 let d = tmp("try-locked");
428 let file = d.join("tasks.jsonl");
429 std::fs::create_dir_all(d.join("tasks.jsonl.lock")).unwrap();
430 assert!(locked(&file, || true));
431 let _ = std::fs::remove_dir_all(d);
432 }
433
434 #[test]
435 fn appends_under_the_queue_lock_never_land_in_a_taken_file() {
436 let ctx = tmp("queue");
437 let q = ctx.with_extension("queued");
438 let writers: Vec<_> = (0..8)
439 .map(|i| {
440 let q = q.clone();
441 std::thread::spawn(move || {
442 for j in 0..50 {
443 locked(&q, || std::fs::OpenOptions::new().create(true).append(true).open(&q).and_then(|mut f| writeln!(f, "{i}-{j}")).unwrap());
444 }
445 })
446 })
447 .collect();
448 let mut got = 0;
449 let taken = q.with_extension("queued.t");
450 while writers.iter().any(|w| !w.is_finished()) {
451 if locked(&q, || std::fs::rename(&q, &taken).is_ok()) {
452 got += std::fs::read_to_string(&taken).unwrap().lines().count();
453 }
454 }
455 for w in writers {
456 w.join().unwrap();
457 }
458 if std::fs::rename(&q, &taken).is_ok() {
459 got += std::fs::read_to_string(&taken).unwrap().lines().count();
460 }
461 assert_eq!(got, 400, "every line taken once");
462 }
463}