use crate::program::TOP;
use std::io::{Read, Seek, SeekFrom};
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant, SystemTime};
use crate::commands::stream::{self, SessionTarget};
pub const MAX_AGE: Duration = Duration::from_secs(30 * 24 * 60 * 60);
pub const MAX_SESSIONS: usize = 10;
pub const MAX_SCANNED: usize = 50;
pub const MAX_UNSENT_BYTES: u64 = 8 * 1024 * 1024;
pub const BUDGET: Duration = Duration::from_secs(3);
const HOOK_LATEST: Duration = Duration::from_secs(10)
.saturating_sub(stream::IN_FLIGHT_GRACE)
.saturating_sub(Duration::from_secs(1));
pub fn deadline(hook_started: Instant, now: Instant) -> Instant {
(now + BUDGET).min(hook_started + HOOK_LATEST)
}
const MARKER: &[u8] = br#""cost-state""#;
#[derive(Debug, PartialEq, Eq)]
pub struct Candidate {
pub session_id: String,
pub session_dir: PathBuf,
pub transcript: PathBuf,
pub worktree_top: String,
}
#[cfg(test)]
pub fn candidates(
project_root: &Path,
current_session: &str,
now: SystemTime,
deadline: Instant,
) -> Vec<Candidate> {
candidates_with(project_root, vec![], current_session, now, deadline)
}
pub fn candidates_with(
project_root: &Path,
external: Vec<PathBuf>,
current_session: &str,
now: SystemTime,
deadline: Instant,
) -> Vec<Candidate> {
let local = crate::layout::existing_sessions_dirs(project_root)
.into_iter()
.filter_map(|dir| std::fs::read_dir(dir).ok())
.flatten();
let mut unsent: Vec<(SystemTime, String, PathBuf, PathBuf, u64)> = local
.take_while(|_| Instant::now() < deadline)
.flatten()
.map(|entry| entry.path())
.chain(external)
.filter_map(|session_dir| {
let session_id = session_dir.file_name()?.to_str()?.to_string();
if session_id == current_session
|| !crate::session_state::is_safe_session_id(&session_id)
{
return None;
}
let transcript = transcript_path(&session_dir)?;
let offset = stream_offset(&session_dir)?;
let meta = std::fs::metadata(&transcript).ok()?;
let modified = meta.modified().ok()?;
let recent = now
.duration_since(modified)
.map_or(true, |age| age <= MAX_AGE);
let pending = meta.len().checked_sub(offset)?;
(recent && pending > 0 && pending <= MAX_UNSENT_BYTES).then_some((
modified,
session_id,
session_dir,
transcript,
offset,
))
})
.collect();
unsent.sort_by_key(|u| std::cmp::Reverse(u.0));
unsent
.into_iter()
.take(MAX_SCANNED)
.take_while(|_| Instant::now() < deadline)
.filter(|(_, _, _, transcript, offset)| unsent_has_cost_state(transcript, *offset))
.map(|(_, session_id, session_dir, transcript, _)| Candidate {
worktree_top: worktree_top(&session_dir, project_root),
session_id,
session_dir,
transcript,
})
.collect()
}
pub async fn sweep(
project_root: PathBuf,
worktree: String,
current_session: String,
deadline: Instant,
) {
if env_sets_attribution(|name| std::env::var_os(name)) {
return;
}
let external = crate::session_state::anchored_session_dirs(
&crate::layout::sessions_dir(&project_root),
&worktree,
);
let mut sent_sessions = 0;
for c in candidates_with(
&project_root,
external,
¤t_session,
SystemTime::now(),
deadline,
) {
if sent_sessions >= MAX_SESSIONS || Instant::now() >= deadline {
break;
}
let event = session_end_event(&c.session_id, &c.transcript, &c.worktree_top);
let target = SessionTarget {
project_root: project_root.clone(),
session_dir: c.session_dir,
worktree_top: c.worktree_top,
};
let sent = stream::stream_event(
event,
"session-end",
crate::agent::Agent::ClaudeCode,
&target,
deadline,
stream::Sender::CatchUp,
)
.await;
match sent {
Ok(stream::Sent::Accepted) => sent_sessions += 1,
Ok(stream::Sent::Skipped) => {}
Ok(stream::Sent::Queued) => break,
Err(e) => {
eprintln!("{TOP}: cannot send the end of an earlier session: {e}");
break;
}
}
}
}
fn session_end_event(
session_id: &str,
transcript: &Path,
cwd: &str,
) -> tracevault_protocol::hooks::HookEvent {
tracevault_protocol::hooks::HookEvent {
session_id: session_id.to_string(),
transcript_path: transcript.to_string_lossy().into_owned(),
cwd: cwd.to_string(),
permission_mode: None,
hook_event_name: "SessionEnd".to_string(),
tool_name: None,
tool_input: None,
tool_response: None,
tool_use_id: None,
source: None,
transcript_records: None,
}
}
fn session_agent(session_dir: &Path, transcript: &Path) -> Option<crate::agent::Agent> {
use crate::agent::Agent;
use clap::ValueEnum;
let meta = stream::session_metadata(session_dir);
let agent = match meta.get("agent").and_then(|a| a.as_str()) {
Some(tool) => *Agent::value_variants()
.iter()
.find(|a| a.tool_name() == tool)?,
None => {
let under = |dir: &str| transcript.components().any(|c| c.as_os_str() == dir);
if under(".claude") {
Agent::ClaudeCode
} else if under(".codex") {
Agent::Codex
} else {
return None;
}
}
};
crate::pending_queue::lines_are_reread(Some(agent.tool_name())).then_some(agent)
}
fn has_unread(session_dir: &Path, transcript: &Path) -> bool {
let len = |p: &Path| std::fs::metadata(p).map(|m| m.len()).unwrap_or(0);
let offset = |p: &Path| -> u64 {
std::fs::read_to_string(p)
.ok()
.and_then(|s| s.trim().parse().ok())
.unwrap_or(0)
};
len(transcript) > offset(&session_dir.join(".stream_offset"))
|| crate::subagents::transcripts(transcript)
.iter()
.any(|f| len(f) > offset(&crate::subagents::offset_path(session_dir, f)))
}
pub(crate) async fn send_rest(
project_root: &Path,
session_dir: &Path,
deadline: Instant,
) -> Option<stream::Sent> {
if env_sets_attribution(|name| std::env::var_os(name)) {
return None;
}
let session_id = session_dir.file_name()?.to_str()?;
if !crate::session_state::is_safe_session_id(session_id) {
return None;
}
let transcript = transcript_path(session_dir)?;
if !transcript.is_file() || !has_unread(session_dir, &transcript) {
return None;
}
let agent = session_agent(session_dir, &transcript)?;
let worktree_top = worktree_top(session_dir, project_root);
let event = session_end_event(session_id, &transcript, &worktree_top);
let target = SessionTarget {
project_root: project_root.to_path_buf(),
session_dir: session_dir.to_path_buf(),
worktree_top,
};
match stream::stream_event(
event,
"session-end",
agent,
&target,
deadline,
stream::Sender::Flush,
)
.await
{
Ok(sent) => Some(sent),
Err(e) => {
eprintln!("{TOP}: cannot send the rest of a session: {e}");
Some(stream::Sent::Queued)
}
}
}
fn transcript_path(session_dir: &Path) -> Option<PathBuf> {
let meta = std::fs::read_to_string(session_dir.join("metadata.json")).ok()?;
let meta: serde_json::Value = serde_json::from_str(&meta).ok()?;
let path = meta.get("transcript_path")?.as_str()?;
(!path.is_empty()).then(|| PathBuf::from(path))
}
fn stream_offset(session_dir: &Path) -> Option<u64> {
std::fs::read_to_string(session_dir.join(".stream_offset"))
.ok()?
.trim()
.parse()
.ok()
}
fn env_sets_attribution(var: impl Fn(&str) -> Option<std::ffi::OsString>) -> bool {
["TRACEVAULT_PROJECT", "TRACEVAULT_PROJECT_ATTRIBUTION"]
.iter()
.any(|name| var(name).is_some_and(|v| !v.is_empty()))
}
fn unsent_has_cost_state(transcript: &Path, offset: u64) -> bool {
let mut unsent = Vec::new();
let read = std::fs::File::open(transcript).and_then(|mut f| {
f.seek(SeekFrom::Start(offset))?;
f.take(MAX_UNSENT_BYTES).read_to_end(&mut unsent)
});
read.is_ok()
&& unsent
.split(|b| *b == b'\n')
.filter(|line| line.windows(MARKER.len()).any(|w| w == MARKER))
.filter_map(|line| serde_json::from_slice::<serde_json::Value>(line).ok())
.any(|l| l.get("type").and_then(|t| t.as_str()) == Some("cost-state"))
}
fn worktree_top(session_dir: &Path, project_root: &Path) -> String {
std::fs::read_to_string(session_dir.join("origin"))
.ok()
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty() && Path::new(s).is_dir())
.unwrap_or_else(|| project_root.to_string_lossy().into_owned())
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
const COST_STATE: &str = r#"{"type":"cost-state","totalCostUSD":0.12}"#;
const ASSISTANT: &str = r#"{"type":"assistant","message":{"id":"m1"}}"#;
struct Repo {
_tmp: tempfile::TempDir,
root: PathBuf,
transcripts: PathBuf,
}
fn repo() -> Repo {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("repo");
let transcripts = tmp.path().join("claude-project");
fs::create_dir_all(root.join(".visdom/sessions")).unwrap();
fs::create_dir_all(&transcripts).unwrap();
Repo {
_tmp: tmp,
root,
transcripts,
}
}
impl Repo {
fn session(&self, id: &str, sent: &[&str], unsent: &[&str]) -> PathBuf {
let dir = self.root.join(".visdom/sessions").join(id);
fs::create_dir_all(&dir).unwrap();
let transcript = self.transcripts.join(format!("{id}.jsonl"));
let sent: String = sent.iter().map(|l| format!("{l}\n")).collect();
let unsent: String = unsent.iter().map(|l| format!("{l}\n")).collect();
fs::write(&transcript, format!("{sent}{unsent}")).unwrap();
fs::write(dir.join(".stream_offset"), sent.len().to_string()).unwrap();
fs::write(
dir.join("metadata.json"),
serde_json::json!({"transcript_path": transcript}).to_string(),
)
.unwrap();
transcript
}
fn ids(&self, current: &str, now: SystemTime) -> Vec<String> {
candidates(&self.root, current, now, later())
.into_iter()
.map(|c| c.session_id)
.collect()
}
}
fn later() -> Instant {
Instant::now() + Duration::from_secs(60)
}
fn touch(path: &Path, modified: SystemTime) {
fs::File::options()
.write(true)
.open(path)
.unwrap()
.set_modified(modified)
.unwrap();
}
#[test]
fn an_unsent_cost_state_makes_a_candidate() {
let r = repo();
let transcript = r.session("s1", &[ASSISTANT], &[COST_STATE]);
let found = candidates(&r.root, "other", SystemTime::now(), later());
assert_eq!(found.len(), 1);
assert_eq!(found[0].session_id, "s1");
assert_eq!(found[0].transcript, transcript);
assert_eq!(
found[0].worktree_top,
r.root.to_string_lossy(),
"no origin marker: the project root"
);
}
#[test]
fn lines_after_the_cost_state_do_not_hide_it() {
let r = repo();
r.session("s1", &[ASSISTANT], &[COST_STATE, ASSISTANT]);
assert_eq!(r.ids("other", SystemTime::now()), ["s1"]);
}
#[test]
fn unsent_lines_without_a_cost_state_are_left_to_the_session() {
let r = repo();
r.session("running", &[ASSISTANT], &[ASSISTANT]);
assert!(r.ids("other", SystemTime::now()).is_empty());
}
#[test]
fn a_cost_state_already_sent_is_not_sent_again() {
let r = repo();
r.session("done", &[ASSISTANT, COST_STATE], &[]);
r.session("resumed", &[COST_STATE], &[ASSISTANT]);
assert!(r.ids("other", SystemTime::now()).is_empty());
}
#[test]
fn the_current_session_is_left_to_its_own_hooks() {
let r = repo();
r.session("current", &[], &[COST_STATE]);
assert!(r.ids("current", SystemTime::now()).is_empty());
}
#[test]
fn subagent_files_are_never_read() {
let r = repo();
r.session("s1", &[ASSISTANT], &[ASSISTANT]);
let subagents = r.transcripts.join("s1").join("subagents");
fs::create_dir_all(&subagents).unwrap();
fs::write(subagents.join("agent-a.jsonl"), format!("{COST_STATE}\n")).unwrap();
assert!(r.ids("other", SystemTime::now()).is_empty());
}
#[test]
fn a_session_without_an_offset_or_transcript_is_skipped() {
let r = repo();
r.session("no-offset", &[], &[COST_STATE]);
fs::remove_file(r.root.join(".visdom/sessions/no-offset/.stream_offset")).unwrap();
let gone = r.session("gone", &[], &[COST_STATE]);
fs::remove_file(gone).unwrap();
r.session("bad-offset", &[], &[COST_STATE]);
fs::write(
r.root.join(".visdom/sessions/bad-offset/.stream_offset"),
"garbage",
)
.unwrap();
fs::create_dir_all(r.root.join(".visdom/sessions/no-metadata")).unwrap();
assert!(r.ids("other", SystemTime::now()).is_empty());
}
#[test]
fn sessions_older_than_the_cap_are_skipped() {
let r = repo();
let old = r.session("old", &[], &[COST_STATE]);
let now = SystemTime::now();
touch(&old, now - MAX_AGE - Duration::from_secs(60));
r.session("new", &[], &[COST_STATE]);
assert_eq!(r.ids("other", now), ["new"]);
}
#[test]
fn most_recent_first() {
let r = repo();
let now = SystemTime::now();
for i in 0..MAX_SESSIONS + 2 {
let t = r.session(&format!("s{i:02}"), &[], &[COST_STATE]);
touch(&t, now - Duration::from_secs(1000 - i as u64));
}
let ids = r.ids("other", now);
let expected: Vec<String> = (0..MAX_SESSIONS + 2)
.rev()
.map(|i| format!("s{i:02}"))
.collect();
assert_eq!(ids, expected);
}
#[test]
fn a_session_with_too_much_unsent_is_skipped() {
let r = repo();
let big = format!(
r#"{{"type":"assistant","pad":"{}"}}"#,
"x".repeat(MAX_UNSENT_BYTES as usize)
);
r.session("big", &[], &[&big, COST_STATE]);
assert!(r.ids("other", SystemTime::now()).is_empty());
}
#[test]
fn an_existing_origin_is_the_worktree_and_a_removed_one_is_not() {
let r = repo();
r.session("here", &[], &[COST_STATE]);
r.session("removed", &[], &[COST_STATE]);
let worktree = r.transcripts.parent().unwrap().join("wt");
fs::create_dir_all(&worktree).unwrap();
let sessions = r.root.join(".visdom/sessions");
fs::write(
sessions.join("here/origin"),
worktree.to_string_lossy().as_bytes(),
)
.unwrap();
fs::write(sessions.join("removed/origin"), "/nonexistent/worktree").unwrap();
let found = candidates(&r.root, "other", SystemTime::now(), later());
let top = |id: &str| {
found
.iter()
.find(|c| c.session_id == id)
.unwrap()
.worktree_top
.clone()
};
assert_eq!(top("here"), worktree.to_string_lossy());
assert_eq!(top("removed"), r.root.to_string_lossy());
}
#[test]
fn an_external_session_dir_is_a_candidate_too() {
let r = repo();
let umbrella = repo();
umbrella.session("anchored", &[ASSISTANT], &[COST_STATE]);
let external = umbrella.root.join(".visdom/sessions/anchored");
let found = candidates_with(
&r.root,
vec![external.clone()],
"other",
SystemTime::now(),
later(),
);
assert_eq!(found.len(), 1);
assert_eq!(found[0].session_id, "anchored");
assert_eq!(found[0].session_dir, external);
assert!(
candidates_with(
&r.root,
vec![external],
"anchored",
SystemTime::now(),
later()
)
.is_empty(),
"the current session is still left to its own hooks"
);
}
#[test]
fn no_sessions_dir_means_nothing_to_do() {
let tmp = tempfile::tempdir().unwrap();
assert!(candidates(tmp.path(), "x", SystemTime::now(), later()).is_empty());
}
#[test]
fn only_the_most_recent_unsent_sessions_are_read() {
let r = repo();
let now = SystemTime::now();
let reported = r.session("reported", &[], &[COST_STATE]);
touch(&reported, now - Duration::from_secs(10_000));
for i in 0..MAX_SCANNED {
let t = r.session(&format!("k{i:02}"), &[], &[ASSISTANT]);
touch(&t, now - Duration::from_secs(1000 - i as u64));
}
assert!(r.ids("other", now).is_empty());
}
#[test]
fn nothing_is_read_past_the_deadline() {
let r = repo();
r.session("s1", &[], &[COST_STATE]);
let found = candidates(&r.root, "other", SystemTime::now(), Instant::now());
assert!(found.is_empty());
}
#[test]
fn the_cost_state_type_must_be_the_line_type() {
let r = repo();
r.session(
"quoted",
&[],
&[r#"{"type":"user","message":{"content":"what is \"cost-state\"?"}}"#],
);
assert!(r.ids("other", SystemTime::now()).is_empty());
}
#[test]
fn the_sweep_stays_inside_the_session_start_timeout() {
let started = Instant::now();
assert_eq!(deadline(started, started), started + BUDGET);
let late = started + Duration::from_secs(8);
assert_eq!(deadline(started, late), started + HOOK_LATEST);
assert!(HOOK_LATEST + stream::IN_FLIGHT_GRACE < Duration::from_secs(10));
}
#[test]
fn a_process_scoped_project_stops_the_sweep() {
use std::ffi::OsString;
let env = |set: &'static str, value: &'static str| {
move |name: &str| (name == set).then(|| OsString::from(value))
};
assert!(env_sets_attribution(env("TRACEVAULT_PROJECT", "p")));
assert!(env_sets_attribution(env(
"TRACEVAULT_PROJECT_ATTRIBUTION",
"explicit"
)));
assert!(!env_sets_attribution(env("TRACEVAULT_PROJECT", "")));
assert!(!env_sets_attribution(|_: &str| None));
}
#[test]
fn a_session_an_earlier_release_started_is_still_caught_up() {
let r = repo();
r.session("old", &[ASSISTANT], &[COST_STATE]);
fs::create_dir_all(r.root.join(".tracevault/sessions")).unwrap();
fs::rename(
r.root.join(".visdom/sessions/old"),
r.root.join(".tracevault/sessions/old"),
)
.unwrap();
r.session("new", &[ASSISTANT], &[COST_STATE]);
let mut ids = r.ids("other", SystemTime::now());
ids.sort();
assert_eq!(ids, ["new", "old"]);
}
}