use std::{
fs::{self, OpenOptions},
io::{BufRead, BufReader, Write},
path::{Path, PathBuf},
time::{SystemTime, UNIX_EPOCH},
};
#[cfg(unix)]
use std::os::unix::fs::OpenOptionsExt;
use serde::{Deserialize, Serialize};
#[cfg(test)]
use rho_providers::model::ModelIdentity;
use rho_providers::model::{ContentBlock, Message, ToolResult};
#[cfg(test)]
use rho_sdk::SessionId;
use rho_sdk::{CompactionState, Revision, SessionSnapshot};
use super::agent_identity::{SavedAgent, SessionAgentRole};
use super::append_cursor::AppendCursor;
use super::tree::{NodeId, ProjectedMessage, SessionNode};
use super::{
index, Session, SessionIndexRecord, SessionOrigin, SessionProvenance, SessionSummary,
SessionTarget,
};
pub(crate) use super::id_match::NoSessionFound;
use super::id_match::{matching_session_files, session_id, single_match, single_workspace};
pub(super) use super::layout::{
ensure_session_dir, parse_timestamp, resolve_transcript_path, session_dir_in_root,
session_id_from_path, session_root, set_private_dir_permissions, set_private_file_permissions,
timestamp, unix_timestamp_secs, workspace_key, SessionUnit, SESSION_TRANSCRIPT_FILE_NAME,
};
pub(super) const MIN_SESSION_VERSION: u32 = 4;
pub(super) const SESSION_VERSION: u32 = 5;
pub(super) const SUPPORTED_SESSION_VERSIONS: std::ops::RangeInclusive<u64> =
MIN_SESSION_VERSION as u64..=SESSION_VERSION as u64;
#[derive(Clone, Debug)]
pub(super) struct ResolvedSession {
pub(super) id: String,
pub(super) path: PathBuf,
pub(super) cwd: PathBuf,
}
#[derive(Clone, Debug)]
pub(super) struct SessionStore {
root: PathBuf,
cwd: PathBuf,
}
impl SessionStore {
pub(super) fn new(root: &Path, cwd: &Path) -> Self {
Self {
root: root.to_path_buf(),
cwd: cwd.to_path_buf(),
}
}
fn ensure_dir(&self) -> anyhow::Result<PathBuf> {
ensure_session_dir(&self.root, &self.cwd)
}
pub(super) fn resolve(&self, id_prefix: &str) -> anyhow::Result<ResolvedSession> {
if let Some(local) = self.resolve_local(id_prefix)? {
return Ok(local);
}
index::reconcile_all_workspaces(&self.root)?;
let global = index::matching_sessions_any_workspace(&self.root, id_prefix)?;
let Some((path, cwd)) = single_match(&global, id_prefix)? else {
return Err(NoSessionFound {
id_prefix: id_prefix.to_owned(),
}
.into());
};
Ok(ResolvedSession {
id: session_id(path)?,
path: path.clone(),
cwd: cwd.clone(),
})
}
pub(super) fn resolve_in_workspace(&self, id_prefix: &str) -> anyhow::Result<ResolvedSession> {
self.resolve_local(id_prefix)?.ok_or_else(|| {
anyhow::anyhow!(
"no session found matching '{id_prefix}' in {}",
self.cwd.display()
)
})
}
pub(super) fn resolve_local(&self, id_prefix: &str) -> anyhow::Result<Option<ResolvedSession>> {
self.resolve_local_where(id_prefix, |_| true)
}
pub(super) fn workspace_of(root: &Path, id: &str) -> anyhow::Result<Option<PathBuf>> {
if let Some(cwd) = indexed_workspace(root, id)? {
return Ok(Some(cwd));
}
index::reconcile_all_workspaces(root)?;
indexed_workspace(root, id)
}
pub(super) fn workspaces_of(
root: &Path,
ids: &[String],
) -> Vec<anyhow::Result<Option<PathBuf>>> {
let mut found: Vec<_> = ids.iter().map(|id| indexed_workspace(root, id)).collect();
let missing = |found: &anyhow::Result<Option<PathBuf>>| matches!(found, Ok(None));
if !found.iter().any(missing) {
return found;
}
let reconciled =
index::reconcile_all_workspaces(root).map_err(|error| format!("{error:#}"));
for (id, found) in ids.iter().zip(&mut found) {
if !missing(found) {
continue;
}
*found = match &reconciled {
Ok(()) => indexed_workspace(root, id),
Err(why) => Err(anyhow::anyhow!(
"could not reconcile the session index: {why}"
)),
};
}
found
}
pub(super) fn resolve_exact_local(&self, id: &str) -> anyhow::Result<Option<ResolvedSession>> {
self.resolve_local_where(id, |path| session_id_from_path(path).as_deref() == Some(id))
}
fn resolve_local_where(
&self,
id_prefix: &str,
keep: impl Fn(&Path) -> bool,
) -> anyhow::Result<Option<ResolvedSession>> {
let dir = self.ensure_dir()?;
let local = matching_session_files(&dir, id_prefix)?
.into_iter()
.filter(|path| keep(path.as_path()))
.filter_map(|path| {
let cwd = read_session_cwd(&path).ok()?;
(workspace_key(&cwd) == workspace_key(&self.cwd)).then_some((path, cwd))
})
.collect::<Vec<_>>();
for (path, _) in &local {
let _ = index::sync_session_file(&self.root, &self.cwd, path);
}
let Some((path, cwd)) = single_match(&local, id_prefix)? else {
return Ok(None);
};
Ok(Some(ResolvedSession {
id: session_id(path)?,
path: path.clone(),
cwd: cwd.clone(),
}))
}
pub(super) fn create_path(&self, id: &str, created_at: u64) -> anyhow::Result<PathBuf> {
let session_dir = self.ensure_dir()?.join(format!("{created_at}_{id}"));
fs::create_dir_all(&session_dir)?;
set_private_dir_permissions(&session_dir)?;
Ok(session_dir.join(SESSION_TRANSCRIPT_FILE_NAME))
}
pub(super) fn list(&self) -> anyhow::Result<Vec<SessionSummary>> {
self.ensure_dir()?;
match index::list_workspace_sessions(&self.root, &self.cwd) {
Ok(summaries) => Ok(summaries),
Err(_) => self.list_by_scan(),
}
}
pub(super) fn set_title(&self, id_prefix: &str, title: &str) -> anyhow::Result<()> {
for path in matching_session_files(&self.ensure_dir()?, id_prefix)? {
index::sync_session_file(&self.root, &self.cwd, &path)?;
}
index::set_title(&self.root, &self.cwd, id_prefix, title)
}
pub(super) fn title(&self, id: &str) -> anyhow::Result<Option<String>> {
index::title(&self.root, &self.cwd, id)
}
pub(super) fn set_title_if_absent(&self, id: &str, title: &str) -> anyhow::Result<bool> {
index::set_title_if_absent(&self.root, &self.cwd, id, title)
}
fn list_by_scan(&self) -> anyhow::Result<Vec<SessionSummary>> {
list_session_summaries_by_scan(&self.ensure_dir()?, &self.cwd)
}
}
impl ResolvedSession {
pub(super) fn tree(&self) -> anyhow::Result<super::tree::SessionTree> {
super::tree::SessionTree::load(&self.path)
}
pub(super) fn summary_with_tree(
&self,
cwd: &Path,
) -> anyhow::Result<(SessionIndexRecord, super::tree::SessionTree)> {
summarize_session_file_with_tree(&self.path, cwd)
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub(crate) struct StoredDisplayMessage {
pub(crate) timestamp: String,
pub(crate) message: Message,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub(super) enum SessionEntry {
Session {
version: u32,
id: String,
timestamp: String,
cwd: PathBuf,
#[serde(default, skip_serializing_if = "Option::is_none")]
agent_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
agent_fingerprint: Option<String>,
#[serde(default, skip_serializing_if = "SessionAgentRole::is_root")]
agent_role: SessionAgentRole,
#[serde(default, skip_serializing_if = "Option::is_none")]
launch_agent: Option<SavedAgent>,
#[serde(default, skip_serializing_if = "Option::is_none")]
origin: Option<SessionOrigin>,
#[serde(default, skip_serializing_if = "Option::is_none")]
parent_session: Option<SessionTarget>,
},
Node {
#[serde(flatten)]
node: SessionNode,
},
SetLeaf {
timestamp: String,
target_id: NodeId,
},
}
impl SessionEntry {
pub(crate) fn event_timestamp(&self) -> &str {
match self {
SessionEntry::Session { timestamp, .. } | SessionEntry::SetLeaf { timestamp, .. } => {
timestamp
}
SessionEntry::Node { node } => node.timestamp.as_str(),
}
}
}
impl Session {
fn append_entry(&self, entry: &SessionEntry) -> anyhow::Result<()> {
let mut cursor = self
.write_lock
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
cursor.invalidate_tree();
self.append_entry_unlocked(&mut cursor, entry)
}
pub(super) fn append_tree_entry(
&self,
cursor: &mut AppendCursor,
tree: &mut super::tree::SessionTree,
entry: SessionEntry,
) -> anyhow::Result<()> {
match &entry {
SessionEntry::Node { node } => tree.apply_explicit_node(node.clone())?,
SessionEntry::SetLeaf {
timestamp,
target_id,
} => {
tree.apply_set_leaf(target_id.clone(), timestamp)?;
tree.ensure_active_state()?;
}
SessionEntry::Session { .. } => {
anyhow::bail!("append_tree_entry only accepts Node or SetLeaf entries");
}
}
self.write_jsonl_entry(cursor, &entry)
}
pub(super) fn append_entry_unlocked(
&self,
cursor: &mut AppendCursor,
entry: &SessionEntry,
) -> anyhow::Result<()> {
if matches!(
entry,
SessionEntry::Node { .. } | SessionEntry::SetLeaf { .. }
) {
anyhow::bail!("tree-mutating entries must use append_tree_entry");
}
self.write_jsonl_entry(cursor, entry)
}
fn write_jsonl_entry(
&self,
cursor: &mut AppendCursor,
entry: &SessionEntry,
) -> anyhow::Result<()> {
let mut serialized = serde_json::to_vec(entry)?;
serialized.push(b'\n');
let mut options = OpenOptions::new();
options.create(true).read(true).append(true);
#[cfg(unix)]
options.mode(0o600);
let original_len = fs::metadata(&self.path)
.map(|metadata| metadata.len())
.unwrap_or(0);
let (previous_len, needs_separator) = match cursor.valid_len {
Some(valid_len) if valid_len == original_len => (valid_len, false),
_ => {
let (previous_len, needs_separator) = recoverable_jsonl_end(&self.path)?;
if previous_len != original_len {
restore_file_len(&self.path, previous_len)?;
}
(previous_len, needs_separator)
}
};
cursor.valid_len = None;
let mut file = options.open(&self.path)?;
set_private_file_permissions(&file)?;
if needs_separator {
serialized.insert(0, b'\n');
}
if let Err(write_error) = file.write_all(&serialized).and_then(|()| file.sync_data()) {
drop(file);
return match restore_file_len(&self.path, previous_len) {
Ok(()) => Err(write_error.into()),
Err(rollback_error) => Err(anyhow::anyhow!(
"session append failed: {write_error}; could not roll back file length: {rollback_error}"
)),
};
}
cursor.valid_len = Some(previous_len + serialized.len() as u64);
Ok(())
}
pub(super) fn append_session_metadata(
&self,
id: String,
created_at: u64,
agent: Option<(&str, &str)>,
provenance: SessionProvenance,
) -> anyhow::Result<()> {
self.append_entry(&SessionEntry::Session {
version: SESSION_VERSION,
id,
timestamp: created_at.to_string(),
cwd: self.cwd.clone(),
agent_id: agent.map(|(id, _)| id.to_string()),
agent_fingerprint: agent.map(|(_, fingerprint)| fingerprint.to_string()),
agent_role: SessionAgentRole::Root,
launch_agent: None,
origin: Some(provenance.origin),
parent_session: provenance.parent.clone(),
})?;
let _ = index::record_created(self, created_at, provenance);
Ok(())
}
#[cfg(test)]
pub(super) fn append_stored_message(
&self,
message: &Message,
display_message: Option<&Message>,
) -> anyhow::Result<()> {
let state = super::tree::SessionTree::load(&self.path)?
.active_state()
.cloned()
.unwrap_or_default();
let revision = next_revision(state.revision)?;
let mut history = state.model;
history.push(message.clone());
let provider = state.snapshot.as_ref().map_or_else(
|| ModelIdentity::new("test", "test", "test"),
|snapshot| snapshot.provider().clone(),
);
let snapshot = SessionSnapshot::new(
SessionId::from_string(self.id.clone())?,
revision,
history,
provider,
state.compaction,
);
self.save_snapshot(&snapshot, &[display_message.unwrap_or(message).clone()])
}
#[cfg(test)]
pub(super) fn append_replaced_history(&self, messages: &[Message]) -> anyhow::Result<()> {
let mut state = super::tree::SessionTree::load(&self.path)?
.active_state()
.cloned()
.unwrap_or_default();
apply_history_replacement(&mut state, messages.to_vec())?;
let provider = state.snapshot.as_ref().map_or_else(
|| ModelIdentity::new("test", "test", "test"),
|snapshot| snapshot.provider().clone(),
);
let snapshot = SessionSnapshot::new(
SessionId::from_string(self.id.clone())?,
state.revision,
state.model,
provider,
state.compaction,
);
self.save_snapshot(&snapshot, &[])
}
}
fn indexed_workspace(root: &Path, id: &str) -> anyhow::Result<Option<PathBuf>> {
let exact: Vec<_> = index::matching_sessions_any_workspace(root, id)?
.into_iter()
.filter(|(path, _)| session_id_from_path(path).as_deref() == Some(id))
.collect();
Ok(single_workspace(&exact, id)?.map(|(_, cwd)| cwd.clone()))
}
pub(super) fn read_session_cwd(path: &Path) -> anyhow::Result<PathBuf> {
let file = fs::File::open(path)?;
let line = BufReader::new(file)
.lines()
.next()
.transpose()?
.ok_or_else(|| anyhow::anyhow!("session file is empty"))?;
match serde_json::from_str::<SessionEntry>(&line)? {
SessionEntry::Session { cwd, .. } => Ok(cwd),
_ => anyhow::bail!("session file does not start with session metadata"),
}
}
#[derive(Clone, Debug, Default)]
pub(crate) struct PersistedSessionState {
pub(crate) model: Vec<Message>,
pub(crate) display: Vec<StoredDisplayMessage>,
pub(crate) snapshot: Option<SessionSnapshot>,
pub(crate) revision: Revision,
pub(crate) compaction: CompactionState,
}
fn restore_file_len(path: &Path, len: u64) -> std::io::Result<()> {
let file = OpenOptions::new().write(true).open(path)?;
file.set_len(len)?;
file.sync_data()
}
fn recoverable_jsonl_end(path: &Path) -> anyhow::Result<(u64, bool)> {
let Ok(contents) = fs::read(path) else {
return Ok((0, false));
};
if contents.is_empty() || contents.ends_with(b"\n") {
return Ok((contents.len() as u64, false));
}
let tail_start = contents
.iter()
.rposition(|byte| *byte == b'\n')
.map_or(0, |position| position + 1);
match serde_json::from_slice::<SessionEntry>(&contents[tail_start..]) {
Ok(_) => Ok((contents.len() as u64, true)),
Err(error) if error.is_eof() => Ok((tail_start as u64, false)),
Err(error) => Err(error.into()),
}
}
pub(super) fn history_from_tree(tree: &super::tree::SessionTree) -> anyhow::Result<Vec<Message>> {
if tree.active_leaf_id().is_none() {
return Ok(Vec::new());
}
let state = tree.active_state().expect("active leaf has restored state");
Ok(insert_interrupted_tool_placeholders(state.model.clone()))
}
pub(super) fn active_display_from_tree(
tree: &super::tree::SessionTree,
) -> anyhow::Result<Vec<ProjectedMessage>> {
let Some(leaf) = tree.active_leaf_id() else {
return Ok(Vec::new());
};
let mut messages = tree
.projected_display_rows(leaf)?
.into_iter()
.map(|(origin, row)| ProjectedMessage {
origin: Some(origin),
message: row.message,
})
.collect();
normalize_loaded_history_by(
&mut messages,
|projected| &mut projected.message,
|_source, result| ProjectedMessage {
origin: None,
message: Message::ToolResult(result.into()),
},
);
Ok(messages)
}
#[cfg(test)]
fn apply_history_replacement(
state: &mut PersistedSessionState,
messages: Vec<Message>,
) -> anyhow::Result<()> {
let previous_messages = state.model.len();
let previous_tokens = rho_sdk::model::context::estimate_messages_tokens(&state.model);
let current_tokens = rho_sdk::model::context::estimate_messages_tokens(&messages);
state.model = messages;
state.revision = next_revision(state.revision)?;
state.compaction = CompactionState::from_parts(
state.compaction.completed_compactions().saturating_add(1),
state
.compaction
.removed_messages()
.saturating_add(previous_messages.saturating_sub(state.model.len()) as u64),
Some(state.revision),
)
.with_removed_tokens(
state
.compaction
.removed_tokens()
.saturating_add(previous_tokens.saturating_sub(current_tokens)),
)
.with_removed_cost_usd_micros(state.compaction.removed_cost_usd_micros())
.with_last_compaction_tokens(previous_tokens, current_tokens);
Ok(())
}
#[cfg(test)]
fn next_revision(revision: Revision) -> anyhow::Result<Revision> {
revision
.checked_next()
.ok_or_else(|| anyhow::anyhow!("session revision is exhausted"))
}
#[cfg(test)]
fn visit_entries(
path: &Path,
mut visit: impl FnMut(SessionEntry) -> anyhow::Result<()>,
) -> anyhow::Result<()> {
let file = fs::File::open(path)?;
let mut reader = BufReader::new(file);
let mut line = String::new();
loop {
line.clear();
if reader.read_line(&mut line)? == 0 {
return Ok(());
}
if line.trim().is_empty() {
continue;
}
let terminated = line.ends_with('\n');
match serde_json::from_str::<SessionEntry>(&line) {
Ok(entry) => {
if let SessionEntry::Session { version, .. } = &entry {
validate_session_version(*version, path)?;
}
visit(entry)?;
}
Err(err) if !terminated && err.is_eof() => return Ok(()),
Err(err) => return Err(err.into()),
}
}
}
#[derive(Debug, thiserror::Error)]
#[error(
"this session was created by rho before 1.11 (session format v{version}) and can't be opened in rho 3; open it with rho 2.x"
)]
pub(crate) struct PreTreeSession {
pub(crate) version: u32,
}
pub(super) fn validate_session_version(version: u32, path: &Path) -> anyhow::Result<()> {
match version {
MIN_SESSION_VERSION..=SESSION_VERSION => Ok(()),
1..MIN_SESSION_VERSION => Err(PreTreeSession { version }.into()),
_ => {
eprintln!(
"warning: skipping session {} with unsupported version {version} (maximum supported: {SESSION_VERSION})",
path.display()
);
anyhow::bail!("unsupported session version {version}")
}
}
}
#[cfg(test)]
pub(super) fn test_transcript(cwd: &Path, id: &str, created_at: u64, prompts: &[&str]) -> String {
use super::display_rows::StoredDisplayRow;
use super::tree::{SessionNodeKind, StoredStateTransition};
let header = SessionEntry::Session {
version: SESSION_VERSION,
id: id.into(),
timestamp: created_at.to_string(),
cwd: cwd.to_path_buf(),
agent_id: None,
agent_fingerprint: None,
agent_role: SessionAgentRole::Root,
launch_agent: None,
origin: None,
parent_session: None,
};
let mut entries = vec![header];
if !prompts.is_empty() {
let history = prompts
.iter()
.map(|prompt| Message::user_text(*prompt))
.collect::<Vec<_>>();
let snapshot = SessionSnapshot::new(
SessionId::from_string(id.to_owned()).expect("test session id"),
Revision::from_u64(1),
history,
ModelIdentity::new("test", "test", "test"),
CompactionState::default(),
);
entries.push(SessionEntry::Node {
node: SessionNode {
id: NodeId::new(),
parent_id: None,
timestamp: created_at.to_string(),
kind: SessionNodeKind::Commit,
compaction_facts: None,
display_messages: (0..prompts.len()).map(StoredDisplayRow::Model).collect(),
transition: StoredStateTransition::Snapshot {
snapshot: Box::new(snapshot),
},
},
});
}
entries
.iter()
.map(|entry| serde_json::to_string(entry).expect("serialize test entry") + "\n")
.collect()
}
#[cfg(test)]
pub(super) fn read_entries(path: &Path) -> anyhow::Result<Vec<SessionEntry>> {
let mut entries = Vec::new();
visit_entries(path, |entry| {
entries.push(entry);
Ok(())
})?;
Ok(entries)
}
pub(super) fn summarize_session_file(
path: &Path,
fallback_cwd: &Path,
) -> anyhow::Result<SessionIndexRecord> {
match summarize_session_file_with_tree(path, fallback_cwd) {
Ok((record, _)) => Ok(record),
Err(error) if error.is::<PreTreeSession>() => {
super::tree::SessionTree::pre_tree_summary_record(path, fallback_cwd)
}
Err(error) => Err(error),
}
}
fn summarize_session_file_with_tree(
path: &Path,
fallback_cwd: &Path,
) -> anyhow::Result<(SessionIndexRecord, super::tree::SessionTree)> {
let tree = super::tree::SessionTree::load(path)?;
let record = tree.summary_record(path, fallback_cwd)?;
Ok((record, tree))
}
const INTERRUPTED_TOOL_RESULT_CONTENT: &str = "tool call interrupted before completion";
fn completed_tool_call_ids(message: &Message) -> Vec<&str> {
let Some(blocks) = message.completed_assistant_content() else {
return Vec::new();
};
blocks
.iter()
.filter_map(|block| match block {
ContentBlock::ToolCall(call) => Some(call.id.as_str()),
ContentBlock::Text(_) | ContentBlock::Image(_) => None,
})
.collect()
}
pub(crate) fn insert_interrupted_tool_placeholders(mut messages: Vec<Message>) -> Vec<Message> {
normalize_loaded_history_by(
&mut messages,
|message| message,
|_source, result| Message::ToolResult(result.into()),
);
messages
}
pub(crate) fn insert_interrupted_display_placeholders(
mut messages: Vec<StoredDisplayMessage>,
) -> Vec<StoredDisplayMessage> {
normalize_loaded_history_by(
&mut messages,
|stored| &mut stored.message,
|source, result| StoredDisplayMessage {
timestamp: source.timestamp.clone(),
message: Message::ToolResult(result.into()),
},
);
messages
}
fn normalize_loaded_history_by<T>(
messages: &mut Vec<T>,
message: impl Fn(&mut T) -> &mut Message,
make_placeholder: impl Fn(&T, ToolResult) -> T,
) {
rho_sdk::model::attach_legacy_tool_images(messages, &message);
let mut index = 0usize;
while index < messages.len() {
let mut remaining: std::collections::BTreeSet<String> =
completed_tool_call_ids(message(&mut messages[index]))
.into_iter()
.map(str::to_owned)
.collect();
if remaining.is_empty() {
index += 1;
continue;
}
for item in &mut messages[index + 1..] {
let Message::ToolResult(result) = message(item) else {
continue;
};
remaining.remove(&result.id);
if remaining.is_empty() {
break;
}
}
if remaining.is_empty() {
index += 1;
continue;
}
let placeholders = remaining
.into_iter()
.map(|id| {
make_placeholder(
&messages[index],
ToolResult::failed(id, INTERRUPTED_TOOL_RESULT_CONTENT),
)
})
.collect::<Vec<_>>();
let insert_at = index + 1;
let added = placeholders.len();
for (offset, placeholder) in placeholders.into_iter().enumerate() {
messages.insert(insert_at + offset, placeholder);
}
index = insert_at + added;
}
}
fn list_session_summaries_by_scan(dir: &Path, cwd: &Path) -> anyhow::Result<Vec<SessionSummary>> {
let mut summaries = fs::read_dir(dir)?
.filter_map(Result::ok)
.filter_map(|entry| {
let unit = SessionUnit::from_path(&entry.path())?;
summarize_session_file(&unit.transcript_path(), cwd)
.ok()
.filter(|record| record.summary.cwd == cwd)
})
.map(|record| record.summary)
.collect::<Vec<_>>();
summaries.sort_by(|left, right| {
right
.updated_at
.cmp(&left.updated_at)
.then_with(|| right.created_at.cmp(&left.created_at))
.then_with(|| left.id.cmp(&right.id))
});
Ok(summaries)
}
pub(super) fn session_file_stats(path: &Path) -> (Option<i64>, Option<i64>) {
let stats_path = resolve_transcript_path(path).unwrap_or_else(|| path.to_path_buf());
let Ok(metadata) = fs::metadata(stats_path) else {
return (None, None);
};
let file_size = Some(clamp_u64_to_i64(metadata.len()));
let file_mtime = metadata.modified().ok().map(system_time_secs);
(file_size, file_mtime)
}
pub(super) fn user_message_text(message: &Message) -> Option<String> {
let rho_sdk::model::SemanticMessage::User(blocks) = message.semantic() else {
return None;
};
let text = blocks
.iter()
.filter_map(|block| match block {
ContentBlock::Text(text) => Some(text.trim()),
ContentBlock::Image(_) | ContentBlock::ToolCall(_) => None,
})
.filter(|text| !text.is_empty())
.collect::<Vec<_>>()
.join("\n");
(!text.is_empty()).then_some(text)
}
pub(super) fn clamp_u64_to_i64(value: u64) -> i64 {
value.min(i64::MAX as u64) as i64
}
pub(super) fn timestamp_from_filename(path: &Path) -> Option<u64> {
SessionUnit::from_path(path)?.created_at_from_name()
}
fn system_time_secs(time: SystemTime) -> i64 {
time.duration_since(UNIX_EPOCH)
.map(|duration| clamp_u64_to_i64(duration.as_secs()))
.unwrap_or_default()
}
#[cfg(test)]
#[path = "persistence_complete_turn_tests.rs"]
mod complete_turn_tests;