1use crate::program::TOP;
29use std::io::{Read, Seek, SeekFrom};
30use std::path::{Path, PathBuf};
31use std::time::{Duration, Instant, SystemTime};
32
33use crate::commands::stream::{self, SessionTarget};
34
35pub const MAX_AGE: Duration = Duration::from_secs(30 * 24 * 60 * 60);
38
39pub const MAX_SESSIONS: usize = 10;
43
44pub const MAX_SCANNED: usize = 50;
48
49pub const MAX_UNSENT_BYTES: u64 = 8 * 1024 * 1024;
53
54pub const BUDGET: Duration = Duration::from_secs(3);
56
57const HOOK_LATEST: Duration = Duration::from_secs(10)
61 .saturating_sub(stream::IN_FLIGHT_GRACE)
62 .saturating_sub(Duration::from_secs(1));
63
64pub fn deadline(hook_started: Instant, now: Instant) -> Instant {
68 (now + BUDGET).min(hook_started + HOOK_LATEST)
69}
70
71const MARKER: &[u8] = br#""cost-state""#;
73
74#[derive(Debug, PartialEq, Eq)]
76pub struct Candidate {
77 pub session_id: String,
78 pub session_dir: PathBuf,
79 pub transcript: PathBuf,
80 pub worktree_top: String,
83}
84
85#[cfg(test)]
90pub fn candidates(
91 project_root: &Path,
92 current_session: &str,
93 now: SystemTime,
94 deadline: Instant,
95) -> Vec<Candidate> {
96 candidates_with(project_root, vec![], current_session, now, deadline)
97}
98
99pub fn candidates_with(
103 project_root: &Path,
104 external: Vec<PathBuf>,
105 current_session: &str,
106 now: SystemTime,
107 deadline: Instant,
108) -> Vec<Candidate> {
109 let local = crate::layout::existing_sessions_dirs(project_root)
111 .into_iter()
112 .filter_map(|dir| std::fs::read_dir(dir).ok())
113 .flatten();
114 let mut unsent: Vec<(SystemTime, String, PathBuf, PathBuf, u64)> = local
117 .take_while(|_| Instant::now() < deadline)
118 .flatten()
119 .map(|entry| entry.path())
120 .chain(external)
121 .filter_map(|session_dir| {
122 let session_id = session_dir.file_name()?.to_str()?.to_string();
123 if session_id == current_session
124 || !crate::session_state::is_safe_session_id(&session_id)
125 {
126 return None;
127 }
128 let transcript = transcript_path(&session_dir)?;
129 let offset = stream_offset(&session_dir)?;
130 let meta = std::fs::metadata(&transcript).ok()?;
131 let modified = meta.modified().ok()?;
132 let recent = now
133 .duration_since(modified)
134 .map_or(true, |age| age <= MAX_AGE);
135 let pending = meta.len().checked_sub(offset)?;
136 (recent && pending > 0 && pending <= MAX_UNSENT_BYTES).then_some((
137 modified,
138 session_id,
139 session_dir,
140 transcript,
141 offset,
142 ))
143 })
144 .collect();
145 unsent.sort_by_key(|u| std::cmp::Reverse(u.0));
146 unsent
147 .into_iter()
148 .take(MAX_SCANNED)
149 .take_while(|_| Instant::now() < deadline)
150 .filter(|(_, _, _, transcript, offset)| unsent_has_cost_state(transcript, *offset))
151 .map(|(_, session_id, session_dir, transcript, _)| Candidate {
152 worktree_top: worktree_top(&session_dir, project_root),
153 session_id,
154 session_dir,
155 transcript,
156 })
157 .collect()
158}
159
160pub async fn sweep(
168 project_root: PathBuf,
169 worktree: String,
170 current_session: String,
171 deadline: Instant,
172) {
173 if env_sets_attribution(|name| std::env::var_os(name)) {
174 return;
175 }
176 let external = crate::session_state::anchored_session_dirs(
177 &crate::layout::sessions_dir(&project_root),
178 &worktree,
179 );
180 let mut sent_sessions = 0;
181 for c in candidates_with(
182 &project_root,
183 external,
184 ¤t_session,
185 SystemTime::now(),
186 deadline,
187 ) {
188 if sent_sessions >= MAX_SESSIONS || Instant::now() >= deadline {
189 break;
190 }
191 let event = tracevault_protocol::hooks::HookEvent {
192 session_id: c.session_id.clone(),
193 transcript_path: c.transcript.to_string_lossy().into_owned(),
194 cwd: c.worktree_top.clone(),
195 permission_mode: None,
196 hook_event_name: "SessionEnd".to_string(),
197 tool_name: None,
198 tool_input: None,
199 tool_response: None,
200 tool_use_id: None,
201 source: None,
202 transcript_records: None,
203 };
204 let target = SessionTarget {
205 project_root: project_root.clone(),
206 session_dir: c.session_dir,
207 worktree_top: c.worktree_top,
208 };
209 let sent = stream::stream_event(
210 event,
211 "session-end",
212 crate::agent::Agent::ClaudeCode,
213 &target,
214 deadline,
215 stream::Sender::CatchUp,
216 )
217 .await;
218 match sent {
219 Ok(stream::Sent::Accepted) => sent_sessions += 1,
220 Ok(stream::Sent::Skipped) => {}
221 Ok(stream::Sent::Queued) => break,
222 Err(e) => {
223 eprintln!("{TOP}: cannot send the end of an earlier session: {e}");
224 break;
225 }
226 }
227 }
228}
229
230fn transcript_path(session_dir: &Path) -> Option<PathBuf> {
232 let meta = std::fs::read_to_string(session_dir.join("metadata.json")).ok()?;
233 let meta: serde_json::Value = serde_json::from_str(&meta).ok()?;
234 let path = meta.get("transcript_path")?.as_str()?;
235 (!path.is_empty()).then(|| PathBuf::from(path))
236}
237
238fn stream_offset(session_dir: &Path) -> Option<u64> {
241 std::fs::read_to_string(session_dir.join(".stream_offset"))
242 .ok()?
243 .trim()
244 .parse()
245 .ok()
246}
247
248fn env_sets_attribution(var: impl Fn(&str) -> Option<std::ffi::OsString>) -> bool {
251 ["TRACEVAULT_PROJECT", "TRACEVAULT_PROJECT_ATTRIBUTION"]
252 .iter()
253 .any(|name| var(name).is_some_and(|v| !v.is_empty()))
254}
255
256fn unsent_has_cost_state(transcript: &Path, offset: u64) -> bool {
259 let mut unsent = Vec::new();
260 let read = std::fs::File::open(transcript).and_then(|mut f| {
261 f.seek(SeekFrom::Start(offset))?;
262 f.take(MAX_UNSENT_BYTES).read_to_end(&mut unsent)
263 });
264 read.is_ok()
265 && unsent
266 .split(|b| *b == b'\n')
267 .filter(|line| line.windows(MARKER.len()).any(|w| w == MARKER))
268 .filter_map(|line| serde_json::from_slice::<serde_json::Value>(line).ok())
269 .any(|l| l.get("type").and_then(|t| t.as_str()) == Some("cost-state"))
270}
271
272fn worktree_top(session_dir: &Path, project_root: &Path) -> String {
274 std::fs::read_to_string(session_dir.join("origin"))
275 .ok()
276 .map(|s| s.trim().to_string())
277 .filter(|s| !s.is_empty() && Path::new(s).is_dir())
278 .unwrap_or_else(|| project_root.to_string_lossy().into_owned())
279}
280
281#[cfg(test)]
282mod tests {
283 use super::*;
284 use std::fs;
285
286 const COST_STATE: &str = r#"{"type":"cost-state","totalCostUSD":0.12}"#;
287 const ASSISTANT: &str = r#"{"type":"assistant","message":{"id":"m1"}}"#;
288
289 struct Repo {
290 _tmp: tempfile::TempDir,
291 root: PathBuf,
292 transcripts: PathBuf,
293 }
294
295 fn repo() -> Repo {
296 let tmp = tempfile::tempdir().unwrap();
297 let root = tmp.path().join("repo");
298 let transcripts = tmp.path().join("claude-project");
299 fs::create_dir_all(root.join(".visdom/sessions")).unwrap();
300 fs::create_dir_all(&transcripts).unwrap();
301 Repo {
302 _tmp: tmp,
303 root,
304 transcripts,
305 }
306 }
307
308 impl Repo {
309 fn session(&self, id: &str, sent: &[&str], unsent: &[&str]) -> PathBuf {
312 let dir = self.root.join(".visdom/sessions").join(id);
313 fs::create_dir_all(&dir).unwrap();
314 let transcript = self.transcripts.join(format!("{id}.jsonl"));
315 let sent: String = sent.iter().map(|l| format!("{l}\n")).collect();
316 let unsent: String = unsent.iter().map(|l| format!("{l}\n")).collect();
317 fs::write(&transcript, format!("{sent}{unsent}")).unwrap();
318 fs::write(dir.join(".stream_offset"), sent.len().to_string()).unwrap();
319 fs::write(
320 dir.join("metadata.json"),
321 serde_json::json!({"transcript_path": transcript}).to_string(),
322 )
323 .unwrap();
324 transcript
325 }
326
327 fn ids(&self, current: &str, now: SystemTime) -> Vec<String> {
328 candidates(&self.root, current, now, later())
329 .into_iter()
330 .map(|c| c.session_id)
331 .collect()
332 }
333 }
334
335 fn later() -> Instant {
337 Instant::now() + Duration::from_secs(60)
338 }
339
340 fn touch(path: &Path, modified: SystemTime) {
341 fs::File::options()
342 .write(true)
343 .open(path)
344 .unwrap()
345 .set_modified(modified)
346 .unwrap();
347 }
348
349 #[test]
350 fn an_unsent_cost_state_makes_a_candidate() {
351 let r = repo();
352 let transcript = r.session("s1", &[ASSISTANT], &[COST_STATE]);
353 let found = candidates(&r.root, "other", SystemTime::now(), later());
354 assert_eq!(found.len(), 1);
355 assert_eq!(found[0].session_id, "s1");
356 assert_eq!(found[0].transcript, transcript);
357 assert_eq!(
358 found[0].worktree_top,
359 r.root.to_string_lossy(),
360 "no origin marker: the project root"
361 );
362 }
363
364 #[test]
365 fn lines_after_the_cost_state_do_not_hide_it() {
366 let r = repo();
367 r.session("s1", &[ASSISTANT], &[COST_STATE, ASSISTANT]);
368 assert_eq!(r.ids("other", SystemTime::now()), ["s1"]);
369 }
370
371 #[test]
372 fn unsent_lines_without_a_cost_state_are_left_to_the_session() {
373 let r = repo();
374 r.session("running", &[ASSISTANT], &[ASSISTANT]);
375 assert!(r.ids("other", SystemTime::now()).is_empty());
376 }
377
378 #[test]
379 fn a_cost_state_already_sent_is_not_sent_again() {
380 let r = repo();
381 r.session("done", &[ASSISTANT, COST_STATE], &[]);
382 r.session("resumed", &[COST_STATE], &[ASSISTANT]);
383 assert!(r.ids("other", SystemTime::now()).is_empty());
384 }
385
386 #[test]
387 fn the_current_session_is_left_to_its_own_hooks() {
388 let r = repo();
389 r.session("current", &[], &[COST_STATE]);
390 assert!(r.ids("current", SystemTime::now()).is_empty());
391 }
392
393 #[test]
394 fn subagent_files_are_never_read() {
395 let r = repo();
396 r.session("s1", &[ASSISTANT], &[ASSISTANT]);
397 let subagents = r.transcripts.join("s1").join("subagents");
398 fs::create_dir_all(&subagents).unwrap();
399 fs::write(subagents.join("agent-a.jsonl"), format!("{COST_STATE}\n")).unwrap();
400 assert!(r.ids("other", SystemTime::now()).is_empty());
401 }
402
403 #[test]
404 fn a_session_without_an_offset_or_transcript_is_skipped() {
405 let r = repo();
406 r.session("no-offset", &[], &[COST_STATE]);
407 fs::remove_file(r.root.join(".visdom/sessions/no-offset/.stream_offset")).unwrap();
408 let gone = r.session("gone", &[], &[COST_STATE]);
409 fs::remove_file(gone).unwrap();
410 r.session("bad-offset", &[], &[COST_STATE]);
411 fs::write(
412 r.root.join(".visdom/sessions/bad-offset/.stream_offset"),
413 "garbage",
414 )
415 .unwrap();
416 fs::create_dir_all(r.root.join(".visdom/sessions/no-metadata")).unwrap();
417 assert!(r.ids("other", SystemTime::now()).is_empty());
418 }
419
420 #[test]
421 fn sessions_older_than_the_cap_are_skipped() {
422 let r = repo();
423 let old = r.session("old", &[], &[COST_STATE]);
424 let now = SystemTime::now();
425 touch(&old, now - MAX_AGE - Duration::from_secs(60));
426 r.session("new", &[], &[COST_STATE]);
427 assert_eq!(r.ids("other", now), ["new"]);
428 }
429
430 #[test]
431 fn most_recent_first() {
432 let r = repo();
433 let now = SystemTime::now();
434 for i in 0..MAX_SESSIONS + 2 {
435 let t = r.session(&format!("s{i:02}"), &[], &[COST_STATE]);
436 touch(&t, now - Duration::from_secs(1000 - i as u64));
437 }
438 let ids = r.ids("other", now);
439 let expected: Vec<String> = (0..MAX_SESSIONS + 2)
440 .rev()
441 .map(|i| format!("s{i:02}"))
442 .collect();
443 assert_eq!(ids, expected);
445 }
446
447 #[test]
448 fn a_session_with_too_much_unsent_is_skipped() {
449 let r = repo();
450 let big = format!(
451 r#"{{"type":"assistant","pad":"{}"}}"#,
452 "x".repeat(MAX_UNSENT_BYTES as usize)
453 );
454 r.session("big", &[], &[&big, COST_STATE]);
455 assert!(r.ids("other", SystemTime::now()).is_empty());
456 }
457
458 #[test]
459 fn an_existing_origin_is_the_worktree_and_a_removed_one_is_not() {
460 let r = repo();
461 r.session("here", &[], &[COST_STATE]);
462 r.session("removed", &[], &[COST_STATE]);
463 let worktree = r.transcripts.parent().unwrap().join("wt");
464 fs::create_dir_all(&worktree).unwrap();
465 let sessions = r.root.join(".visdom/sessions");
466 fs::write(
467 sessions.join("here/origin"),
468 worktree.to_string_lossy().as_bytes(),
469 )
470 .unwrap();
471 fs::write(sessions.join("removed/origin"), "/nonexistent/worktree").unwrap();
472 let found = candidates(&r.root, "other", SystemTime::now(), later());
473 let top = |id: &str| {
474 found
475 .iter()
476 .find(|c| c.session_id == id)
477 .unwrap()
478 .worktree_top
479 .clone()
480 };
481 assert_eq!(top("here"), worktree.to_string_lossy());
482 assert_eq!(top("removed"), r.root.to_string_lossy());
483 }
484
485 #[test]
486 fn an_external_session_dir_is_a_candidate_too() {
487 let r = repo();
488 let umbrella = repo();
489 umbrella.session("anchored", &[ASSISTANT], &[COST_STATE]);
490 let external = umbrella.root.join(".visdom/sessions/anchored");
491 let found = candidates_with(
492 &r.root,
493 vec![external.clone()],
494 "other",
495 SystemTime::now(),
496 later(),
497 );
498 assert_eq!(found.len(), 1);
499 assert_eq!(found[0].session_id, "anchored");
500 assert_eq!(found[0].session_dir, external);
501 assert!(
502 candidates_with(
503 &r.root,
504 vec![external],
505 "anchored",
506 SystemTime::now(),
507 later()
508 )
509 .is_empty(),
510 "the current session is still left to its own hooks"
511 );
512 }
513
514 #[test]
515 fn no_sessions_dir_means_nothing_to_do() {
516 let tmp = tempfile::tempdir().unwrap();
517 assert!(candidates(tmp.path(), "x", SystemTime::now(), later()).is_empty());
518 }
519
520 #[test]
521 fn only_the_most_recent_unsent_sessions_are_read() {
522 let r = repo();
523 let now = SystemTime::now();
524 let reported = r.session("reported", &[], &[COST_STATE]);
527 touch(&reported, now - Duration::from_secs(10_000));
528 for i in 0..MAX_SCANNED {
529 let t = r.session(&format!("k{i:02}"), &[], &[ASSISTANT]);
530 touch(&t, now - Duration::from_secs(1000 - i as u64));
531 }
532 assert!(r.ids("other", now).is_empty());
533 }
534
535 #[test]
536 fn nothing_is_read_past_the_deadline() {
537 let r = repo();
538 r.session("s1", &[], &[COST_STATE]);
539 let found = candidates(&r.root, "other", SystemTime::now(), Instant::now());
540 assert!(found.is_empty());
541 }
542
543 #[test]
544 fn the_cost_state_type_must_be_the_line_type() {
545 let r = repo();
546 r.session(
548 "quoted",
549 &[],
550 &[r#"{"type":"user","message":{"content":"what is \"cost-state\"?"}}"#],
551 );
552 assert!(r.ids("other", SystemTime::now()).is_empty());
553 }
554
555 #[test]
556 fn the_sweep_stays_inside_the_session_start_timeout() {
557 let started = Instant::now();
558 assert_eq!(deadline(started, started), started + BUDGET);
560 let late = started + Duration::from_secs(8);
562 assert_eq!(deadline(started, late), started + HOOK_LATEST);
563 assert!(HOOK_LATEST + stream::IN_FLIGHT_GRACE < Duration::from_secs(10));
564 }
565
566 #[test]
567 fn a_process_scoped_project_stops_the_sweep() {
568 use std::ffi::OsString;
569 let env = |set: &'static str, value: &'static str| {
570 move |name: &str| (name == set).then(|| OsString::from(value))
571 };
572 assert!(env_sets_attribution(env("TRACEVAULT_PROJECT", "p")));
573 assert!(env_sets_attribution(env(
574 "TRACEVAULT_PROJECT_ATTRIBUTION",
575 "explicit"
576 )));
577 assert!(!env_sets_attribution(env("TRACEVAULT_PROJECT", "")));
578 assert!(!env_sets_attribution(|_: &str| None));
579 }
580
581 #[test]
582 fn a_session_an_earlier_release_started_is_still_caught_up() {
583 let r = repo();
584 r.session("old", &[ASSISTANT], &[COST_STATE]);
585 fs::create_dir_all(r.root.join(".tracevault/sessions")).unwrap();
587 fs::rename(
588 r.root.join(".visdom/sessions/old"),
589 r.root.join(".tracevault/sessions/old"),
590 )
591 .unwrap();
592 r.session("new", &[ASSISTANT], &[COST_STATE]);
593
594 let mut ids = r.ids("other", SystemTime::now());
595 ids.sort();
596 assert_eq!(ids, ["new", "old"]);
597 }
598}