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