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