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 = session_end_event(&c.session_id, &c.transcript, &c.worktree_top);
192 let target = SessionTarget {
193 project_root: project_root.clone(),
194 session_dir: c.session_dir,
195 worktree_top: c.worktree_top,
196 };
197 let sent = stream::stream_event(
198 event,
199 "session-end",
200 crate::agent::Agent::ClaudeCode,
201 &target,
202 deadline,
203 stream::Sender::CatchUp,
204 )
205 .await;
206 match sent {
207 Ok(stream::Sent::Accepted) => sent_sessions += 1,
208 Ok(stream::Sent::Skipped) => {}
209 Ok(stream::Sent::Queued) => break,
210 Err(e) => {
211 eprintln!("{TOP}: cannot send the end of an earlier session: {e}");
212 break;
213 }
214 }
215 }
216}
217
218fn session_end_event(
220 session_id: &str,
221 transcript: &Path,
222 cwd: &str,
223) -> tracevault_protocol::hooks::HookEvent {
224 tracevault_protocol::hooks::HookEvent {
225 session_id: session_id.to_string(),
226 transcript_path: transcript.to_string_lossy().into_owned(),
227 cwd: cwd.to_string(),
228 permission_mode: None,
229 hook_event_name: "SessionEnd".to_string(),
230 tool_name: None,
231 tool_input: None,
232 tool_response: None,
233 tool_use_id: None,
234 source: None,
235 transcript_records: None,
236 }
237}
238
239fn session_agent(session_dir: &Path, transcript: &Path) -> Option<crate::agent::Agent> {
245 use crate::agent::Agent;
246 use clap::ValueEnum;
247 let meta = stream::session_metadata(session_dir);
248 let agent = match meta.get("agent").and_then(|a| a.as_str()) {
249 Some(tool) => *Agent::value_variants()
250 .iter()
251 .find(|a| a.tool_name() == tool)?,
252 None => {
253 let under = |dir: &str| transcript.components().any(|c| c.as_os_str() == dir);
254 if under(".claude") {
255 Agent::ClaudeCode
256 } else if under(".codex") {
257 Agent::Codex
258 } else {
259 return None;
260 }
261 }
262 };
263 crate::pending_queue::lines_are_reread(Some(agent.tool_name())).then_some(agent)
264}
265
266fn has_unread(session_dir: &Path, transcript: &Path) -> bool {
268 let len = |p: &Path| std::fs::metadata(p).map(|m| m.len()).unwrap_or(0);
269 let offset = |p: &Path| -> u64 {
270 std::fs::read_to_string(p)
271 .ok()
272 .and_then(|s| s.trim().parse().ok())
273 .unwrap_or(0)
274 };
275 len(transcript) > offset(&session_dir.join(".stream_offset"))
276 || crate::subagents::transcripts(transcript)
277 .iter()
278 .any(|f| len(f) > offset(&crate::subagents::offset_path(session_dir, f)))
279}
280
281pub(crate) async fn send_rest(
293 project_root: &Path,
294 session_dir: &Path,
295 deadline: Instant,
296) -> Option<stream::Sent> {
297 if env_sets_attribution(|name| std::env::var_os(name)) {
298 return None;
299 }
300 let session_id = session_dir.file_name()?.to_str()?;
301 if !crate::session_state::is_safe_session_id(session_id) {
302 return None;
303 }
304 let transcript = transcript_path(session_dir)?;
305 if !transcript.is_file() || !has_unread(session_dir, &transcript) {
306 return None;
307 }
308 let agent = session_agent(session_dir, &transcript)?;
309 let worktree_top = worktree_top(session_dir, project_root);
310 let event = session_end_event(session_id, &transcript, &worktree_top);
311 let target = SessionTarget {
312 project_root: project_root.to_path_buf(),
313 session_dir: session_dir.to_path_buf(),
314 worktree_top,
315 };
316 match stream::stream_event(
317 event,
318 "session-end",
319 agent,
320 &target,
321 deadline,
322 stream::Sender::Flush,
323 )
324 .await
325 {
326 Ok(sent) => Some(sent),
327 Err(e) => {
328 eprintln!("{TOP}: cannot send the rest of a session: {e}");
329 Some(stream::Sent::Queued)
330 }
331 }
332}
333
334fn transcript_path(session_dir: &Path) -> Option<PathBuf> {
336 let meta = std::fs::read_to_string(session_dir.join("metadata.json")).ok()?;
337 let meta: serde_json::Value = serde_json::from_str(&meta).ok()?;
338 let path = meta.get("transcript_path")?.as_str()?;
339 (!path.is_empty()).then(|| PathBuf::from(path))
340}
341
342fn stream_offset(session_dir: &Path) -> Option<u64> {
345 std::fs::read_to_string(session_dir.join(".stream_offset"))
346 .ok()?
347 .trim()
348 .parse()
349 .ok()
350}
351
352fn env_sets_attribution(var: impl Fn(&str) -> Option<std::ffi::OsString>) -> bool {
355 ["TRACEVAULT_PROJECT", "TRACEVAULT_PROJECT_ATTRIBUTION"]
356 .iter()
357 .any(|name| var(name).is_some_and(|v| !v.is_empty()))
358}
359
360fn unsent_has_cost_state(transcript: &Path, offset: u64) -> bool {
363 let mut unsent = Vec::new();
364 let read = std::fs::File::open(transcript).and_then(|mut f| {
365 f.seek(SeekFrom::Start(offset))?;
366 f.take(MAX_UNSENT_BYTES).read_to_end(&mut unsent)
367 });
368 read.is_ok()
369 && unsent
370 .split(|b| *b == b'\n')
371 .filter(|line| line.windows(MARKER.len()).any(|w| w == MARKER))
372 .filter_map(|line| serde_json::from_slice::<serde_json::Value>(line).ok())
373 .any(|l| l.get("type").and_then(|t| t.as_str()) == Some("cost-state"))
374}
375
376fn worktree_top(session_dir: &Path, project_root: &Path) -> String {
378 std::fs::read_to_string(session_dir.join("origin"))
379 .ok()
380 .map(|s| s.trim().to_string())
381 .filter(|s| !s.is_empty() && Path::new(s).is_dir())
382 .unwrap_or_else(|| project_root.to_string_lossy().into_owned())
383}
384
385#[cfg(test)]
386mod tests {
387 use super::*;
388 use std::fs;
389
390 const COST_STATE: &str = r#"{"type":"cost-state","totalCostUSD":0.12}"#;
391 const ASSISTANT: &str = r#"{"type":"assistant","message":{"id":"m1"}}"#;
392
393 struct Repo {
394 _tmp: tempfile::TempDir,
395 root: PathBuf,
396 transcripts: PathBuf,
397 }
398
399 fn repo() -> Repo {
400 let tmp = tempfile::tempdir().unwrap();
401 let root = tmp.path().join("repo");
402 let transcripts = tmp.path().join("claude-project");
403 fs::create_dir_all(root.join(".visdom/sessions")).unwrap();
404 fs::create_dir_all(&transcripts).unwrap();
405 Repo {
406 _tmp: tmp,
407 root,
408 transcripts,
409 }
410 }
411
412 impl Repo {
413 fn session(&self, id: &str, sent: &[&str], unsent: &[&str]) -> PathBuf {
416 let dir = self.root.join(".visdom/sessions").join(id);
417 fs::create_dir_all(&dir).unwrap();
418 let transcript = self.transcripts.join(format!("{id}.jsonl"));
419 let sent: String = sent.iter().map(|l| format!("{l}\n")).collect();
420 let unsent: String = unsent.iter().map(|l| format!("{l}\n")).collect();
421 fs::write(&transcript, format!("{sent}{unsent}")).unwrap();
422 fs::write(dir.join(".stream_offset"), sent.len().to_string()).unwrap();
423 fs::write(
424 dir.join("metadata.json"),
425 serde_json::json!({"transcript_path": transcript}).to_string(),
426 )
427 .unwrap();
428 transcript
429 }
430
431 fn ids(&self, current: &str, now: SystemTime) -> Vec<String> {
432 candidates(&self.root, current, now, later())
433 .into_iter()
434 .map(|c| c.session_id)
435 .collect()
436 }
437 }
438
439 fn later() -> Instant {
441 Instant::now() + Duration::from_secs(60)
442 }
443
444 fn touch(path: &Path, modified: SystemTime) {
445 fs::File::options()
446 .write(true)
447 .open(path)
448 .unwrap()
449 .set_modified(modified)
450 .unwrap();
451 }
452
453 #[test]
454 fn an_unsent_cost_state_makes_a_candidate() {
455 let r = repo();
456 let transcript = r.session("s1", &[ASSISTANT], &[COST_STATE]);
457 let found = candidates(&r.root, "other", SystemTime::now(), later());
458 assert_eq!(found.len(), 1);
459 assert_eq!(found[0].session_id, "s1");
460 assert_eq!(found[0].transcript, transcript);
461 assert_eq!(
462 found[0].worktree_top,
463 r.root.to_string_lossy(),
464 "no origin marker: the project root"
465 );
466 }
467
468 #[test]
469 fn lines_after_the_cost_state_do_not_hide_it() {
470 let r = repo();
471 r.session("s1", &[ASSISTANT], &[COST_STATE, ASSISTANT]);
472 assert_eq!(r.ids("other", SystemTime::now()), ["s1"]);
473 }
474
475 #[test]
476 fn unsent_lines_without_a_cost_state_are_left_to_the_session() {
477 let r = repo();
478 r.session("running", &[ASSISTANT], &[ASSISTANT]);
479 assert!(r.ids("other", SystemTime::now()).is_empty());
480 }
481
482 #[test]
483 fn a_cost_state_already_sent_is_not_sent_again() {
484 let r = repo();
485 r.session("done", &[ASSISTANT, COST_STATE], &[]);
486 r.session("resumed", &[COST_STATE], &[ASSISTANT]);
487 assert!(r.ids("other", SystemTime::now()).is_empty());
488 }
489
490 #[test]
491 fn the_current_session_is_left_to_its_own_hooks() {
492 let r = repo();
493 r.session("current", &[], &[COST_STATE]);
494 assert!(r.ids("current", SystemTime::now()).is_empty());
495 }
496
497 #[test]
498 fn subagent_files_are_never_read() {
499 let r = repo();
500 r.session("s1", &[ASSISTANT], &[ASSISTANT]);
501 let subagents = r.transcripts.join("s1").join("subagents");
502 fs::create_dir_all(&subagents).unwrap();
503 fs::write(subagents.join("agent-a.jsonl"), format!("{COST_STATE}\n")).unwrap();
504 assert!(r.ids("other", SystemTime::now()).is_empty());
505 }
506
507 #[test]
508 fn a_session_without_an_offset_or_transcript_is_skipped() {
509 let r = repo();
510 r.session("no-offset", &[], &[COST_STATE]);
511 fs::remove_file(r.root.join(".visdom/sessions/no-offset/.stream_offset")).unwrap();
512 let gone = r.session("gone", &[], &[COST_STATE]);
513 fs::remove_file(gone).unwrap();
514 r.session("bad-offset", &[], &[COST_STATE]);
515 fs::write(
516 r.root.join(".visdom/sessions/bad-offset/.stream_offset"),
517 "garbage",
518 )
519 .unwrap();
520 fs::create_dir_all(r.root.join(".visdom/sessions/no-metadata")).unwrap();
521 assert!(r.ids("other", SystemTime::now()).is_empty());
522 }
523
524 #[test]
525 fn sessions_older_than_the_cap_are_skipped() {
526 let r = repo();
527 let old = r.session("old", &[], &[COST_STATE]);
528 let now = SystemTime::now();
529 touch(&old, now - MAX_AGE - Duration::from_secs(60));
530 r.session("new", &[], &[COST_STATE]);
531 assert_eq!(r.ids("other", now), ["new"]);
532 }
533
534 #[test]
535 fn most_recent_first() {
536 let r = repo();
537 let now = SystemTime::now();
538 for i in 0..MAX_SESSIONS + 2 {
539 let t = r.session(&format!("s{i:02}"), &[], &[COST_STATE]);
540 touch(&t, now - Duration::from_secs(1000 - i as u64));
541 }
542 let ids = r.ids("other", now);
543 let expected: Vec<String> = (0..MAX_SESSIONS + 2)
544 .rev()
545 .map(|i| format!("s{i:02}"))
546 .collect();
547 assert_eq!(ids, expected);
549 }
550
551 #[test]
552 fn a_session_with_too_much_unsent_is_skipped() {
553 let r = repo();
554 let big = format!(
555 r#"{{"type":"assistant","pad":"{}"}}"#,
556 "x".repeat(MAX_UNSENT_BYTES as usize)
557 );
558 r.session("big", &[], &[&big, COST_STATE]);
559 assert!(r.ids("other", SystemTime::now()).is_empty());
560 }
561
562 #[test]
563 fn an_existing_origin_is_the_worktree_and_a_removed_one_is_not() {
564 let r = repo();
565 r.session("here", &[], &[COST_STATE]);
566 r.session("removed", &[], &[COST_STATE]);
567 let worktree = r.transcripts.parent().unwrap().join("wt");
568 fs::create_dir_all(&worktree).unwrap();
569 let sessions = r.root.join(".visdom/sessions");
570 fs::write(
571 sessions.join("here/origin"),
572 worktree.to_string_lossy().as_bytes(),
573 )
574 .unwrap();
575 fs::write(sessions.join("removed/origin"), "/nonexistent/worktree").unwrap();
576 let found = candidates(&r.root, "other", SystemTime::now(), later());
577 let top = |id: &str| {
578 found
579 .iter()
580 .find(|c| c.session_id == id)
581 .unwrap()
582 .worktree_top
583 .clone()
584 };
585 assert_eq!(top("here"), worktree.to_string_lossy());
586 assert_eq!(top("removed"), r.root.to_string_lossy());
587 }
588
589 #[test]
590 fn an_external_session_dir_is_a_candidate_too() {
591 let r = repo();
592 let umbrella = repo();
593 umbrella.session("anchored", &[ASSISTANT], &[COST_STATE]);
594 let external = umbrella.root.join(".visdom/sessions/anchored");
595 let found = candidates_with(
596 &r.root,
597 vec![external.clone()],
598 "other",
599 SystemTime::now(),
600 later(),
601 );
602 assert_eq!(found.len(), 1);
603 assert_eq!(found[0].session_id, "anchored");
604 assert_eq!(found[0].session_dir, external);
605 assert!(
606 candidates_with(
607 &r.root,
608 vec![external],
609 "anchored",
610 SystemTime::now(),
611 later()
612 )
613 .is_empty(),
614 "the current session is still left to its own hooks"
615 );
616 }
617
618 #[test]
619 fn no_sessions_dir_means_nothing_to_do() {
620 let tmp = tempfile::tempdir().unwrap();
621 assert!(candidates(tmp.path(), "x", SystemTime::now(), later()).is_empty());
622 }
623
624 #[test]
625 fn only_the_most_recent_unsent_sessions_are_read() {
626 let r = repo();
627 let now = SystemTime::now();
628 let reported = r.session("reported", &[], &[COST_STATE]);
631 touch(&reported, now - Duration::from_secs(10_000));
632 for i in 0..MAX_SCANNED {
633 let t = r.session(&format!("k{i:02}"), &[], &[ASSISTANT]);
634 touch(&t, now - Duration::from_secs(1000 - i as u64));
635 }
636 assert!(r.ids("other", now).is_empty());
637 }
638
639 #[test]
640 fn nothing_is_read_past_the_deadline() {
641 let r = repo();
642 r.session("s1", &[], &[COST_STATE]);
643 let found = candidates(&r.root, "other", SystemTime::now(), Instant::now());
644 assert!(found.is_empty());
645 }
646
647 #[test]
648 fn the_cost_state_type_must_be_the_line_type() {
649 let r = repo();
650 r.session(
652 "quoted",
653 &[],
654 &[r#"{"type":"user","message":{"content":"what is \"cost-state\"?"}}"#],
655 );
656 assert!(r.ids("other", SystemTime::now()).is_empty());
657 }
658
659 #[test]
660 fn the_sweep_stays_inside_the_session_start_timeout() {
661 let started = Instant::now();
662 assert_eq!(deadline(started, started), started + BUDGET);
664 let late = started + Duration::from_secs(8);
666 assert_eq!(deadline(started, late), started + HOOK_LATEST);
667 assert!(HOOK_LATEST + stream::IN_FLIGHT_GRACE < Duration::from_secs(10));
668 }
669
670 #[test]
671 fn a_process_scoped_project_stops_the_sweep() {
672 use std::ffi::OsString;
673 let env = |set: &'static str, value: &'static str| {
674 move |name: &str| (name == set).then(|| OsString::from(value))
675 };
676 assert!(env_sets_attribution(env("TRACEVAULT_PROJECT", "p")));
677 assert!(env_sets_attribution(env(
678 "TRACEVAULT_PROJECT_ATTRIBUTION",
679 "explicit"
680 )));
681 assert!(!env_sets_attribution(env("TRACEVAULT_PROJECT", "")));
682 assert!(!env_sets_attribution(|_: &str| None));
683 }
684
685 #[test]
686 fn a_session_an_earlier_release_started_is_still_caught_up() {
687 let r = repo();
688 r.session("old", &[ASSISTANT], &[COST_STATE]);
689 fs::create_dir_all(r.root.join(".tracevault/sessions")).unwrap();
691 fs::rename(
692 r.root.join(".visdom/sessions/old"),
693 r.root.join(".tracevault/sessions/old"),
694 )
695 .unwrap();
696 r.session("new", &[ASSISTANT], &[COST_STATE]);
697
698 let mut ids = r.ids("other", SystemTime::now());
699 ids.sort();
700 assert_eq!(ids, ["new", "old"]);
701 }
702}