Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 25 additions & 9 deletions bt-daemon/src/collections/legacy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@ const IMPORT_RECORDS: usize = 1024;
const IMPORT_BYTES: usize = 8 * 1024 * 1024;
const PI_MESSAGES_DELTA: &str = "_bt_messages_delta";

// Recovery and live capture can both discover a legacy journal. Serialize
// reading, committing and removing those files. Modern sessions bypass this.
static IMPORT_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());

/// Import any legacy journals that hold records for this source session.
pub(super) async fn import_session(
data_dir: &Path,
Expand All @@ -30,14 +34,19 @@ pub(super) async fn import_session(
events: &SessionStorage,
) -> anyhow::Result<()> {
let unqualified = journal_path(data_dir, session_id);
if unqualified
let unqualified_supported = unqualified
.file_name()
.is_some_and(|name| name.len() <= crate::journal::MAX_FILE_NAME_BYTES)
&& tokio::fs::try_exists(&unqualified).await?
.is_some_and(|name| name.len() <= crate::journal::MAX_FILE_NAME_BYTES);
let qualified = source_journal_path(data_dir, source, session_id);
if !(unqualified_supported && tokio::fs::try_exists(&unqualified).await?)
&& !tokio::fs::try_exists(&qualified).await?
{
return Ok(());
}
let _guard = IMPORT_LOCK.lock().await;
if unqualified_supported && tokio::fs::try_exists(&unqualified).await? {
import_unqualified(data_dir, &unqualified).await?;
}
let qualified = source_journal_path(data_dir, source, session_id);
if tokio::fs::try_exists(&qualified).await? {
import_file(&qualified, source, events, None).await?;
tokio::fs::remove_file(&qualified).await?;
Expand All @@ -57,11 +66,18 @@ pub(crate) async fn import_all(data_dir: &Path) {
continue;
}
let result = async {
let owners = sessions(&path).await?;
if owners.is_empty() {
// Nothing was ever acknowledged from a file without events.
tokio::fs::remove_file(&path).await?;
}
let owners = {
let _guard = IMPORT_LOCK.lock().await;
if !tokio::fs::try_exists(&path).await? {
return Ok(());
}
let owners = sessions(&path).await?;
if owners.is_empty() {
// Nothing was ever acknowledged from a file without events.
tokio::fs::remove_file(&path).await?;
}
owners
};
for (source, session_id) in owners {
SessionStorage::open(data_dir, &source, &session_id).await?;
}
Expand Down
27 changes: 27 additions & 0 deletions bt-daemon/src/collections/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -434,3 +434,30 @@ async fn compaction_returns_deleted_space_to_the_file_system() {
assert_eq!(pragma("freelist_count"), 0);
assert!(size() < bloated / 4, "{} of {bloated} bytes remain", size());
}

#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn simultaneous_legacy_open_preserves_capture() {
for qualified in [true, false] {
let temp = tempfile::tempdir().unwrap();
let path = if qualified {
source_journal_path(temp.path(), "debug", "session")
} else {
journal_path(temp.path(), "session")
};
let record = line(
&json!({"source":"debug","session_id":"session","event":"e","ts_ms":1,"payload":{}}),
);
write_legacy(&path, &record).await;
let outcomes = futures::future::join_all(
(0..16).map(|_| SessionStorage::open(temp.path(), "debug", "session")),
)
.await;
for storage in outcomes {
assert_eq!(
storage.unwrap().status().await.unwrap().event_tail,
record.len() as u64
);
}
assert!(!path.exists());
}
}
149 changes: 71 additions & 78 deletions bt-daemon/src/translate/claude.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,11 @@ mod native_field;
mod parsed_transcript;
mod subagent_hook;
mod timestamp_envelope;
mod transcript_content;
mod transcript_envelope;
mod transcript_tool;
mod transcript_tool_outcome;
mod user_prompt_hook;

use hook_context::HookContext;
use llm_call::LlmCall;
Expand All @@ -26,8 +28,10 @@ use subagent_hook::SubagentHook;
#[cfg(test)]
use timestamp_envelope::parse_rfc3339_timestamp;
use timestamp_envelope::parse_timestamp_ms;
use transcript_content::TranscriptContent;
use transcript_envelope::TranscriptEnvelope;
use transcript_tool::TranscriptTool;
use user_prompt_hook::UserPromptHook;

use super::git::GitMetadataCache;
use super::recent::{RecentMap, RecentSet, RECENT_ID_CAPACITY};
Expand Down Expand Up @@ -72,7 +76,7 @@ struct Turn {
#[derive(Serialize, Deserialize)]
struct PendingPrompt {
turn_id: Arc<String>,
content: Value,
content: TranscriptContent,
}

#[derive(Default, Serialize, Deserialize)]
Expand Down Expand Up @@ -350,7 +354,7 @@ impl ClaudeTranslator {
)
}

fn open_turn(&mut self, event: &Envelope, ops: &mut Vec<SpanOp>) {
fn open_turn(&mut self, event: &Envelope, prompt: UserPromptHook, ops: &mut Vec<SpanOp>) {
self.session_status = Some("running".into());
if let Some(old) = self.turn.take() {
self.close_pending_tools(
Expand All @@ -369,7 +373,8 @@ impl ClaudeTranslator {
..Default::default()
}));
}
let continuation = continuation_origin(&event.payload);
let text = prompt.prompt.as_ref().and_then(TranscriptContent::as_text);
let continuation = continuation_origin(&event.payload, text);
let (id, parent_id, user_turn_id, name) = if let Some((_, task_id)) = continuation {
self.continuation_count += 1;
let owner = self
Expand Down Expand Up @@ -402,7 +407,7 @@ impl ClaudeTranslator {
// as directly as a `/x` slash command. Continuations are runtime
// notifications, not user requests.
if continuation.is_none() {
if let Some(prompt) = event.payload.get("prompt").and_then(Value::as_str) {
if let Some(prompt) = text {
for name in prompt_skill_names(prompt) {
push_unique(&mut self.requested_skills, name);
}
Expand Down Expand Up @@ -433,7 +438,7 @@ impl ClaudeTranslator {
span_type: SpanType::Task,
is_turn: true,
start_ms: Some(event.ts_ms),
input: event.payload.get("prompt").cloned(),
input: (!prompt.prompt.is_missing()).then(|| json!(prompt.prompt)),
metadata: (!metadata.is_empty()).then_some(Value::Object(metadata)),
turn_span_id: Some(owner.clone()),
..Default::default()
Expand All @@ -446,14 +451,12 @@ impl ClaudeTranslator {
self.prompt_turns
.insert(prompt_id.to_owned(), turn_id.clone());
}
if let Some(content) = event.payload.get("prompt").filter(|value| !value.is_null()) {
if let crate::json::Field::Value(content) = prompt.prompt {
if self.pending_prompts.len() == RECENT_ID_CAPACITY {
self.pending_prompts.pop_front();
}
self.pending_prompts.push_back(PendingPrompt {
turn_id,
content: content.clone(),
});
self.pending_prompts
.push_back(PendingPrompt { turn_id, content });
}
self.turn = Some(Turn {
id,
Expand Down Expand Up @@ -992,7 +995,11 @@ impl ClaudeTranslator {
// Hooks carry prompt_id only after the first user input, and older Claude
// versions omit it. Without it, match prompts in submission order, then
// retain transcript identities so repeats cannot consume another turn.
fn user_record_turn(&mut self, record: &Value) -> Option<Arc<String>> {
fn user_record_turn(
&mut self,
record: &Value,
row: &TranscriptEnvelope,
) -> Option<Arc<String>> {
let prompt_id = record.get("promptId").and_then(Value::as_str);
let mut owner = prompt_id
.and_then(|id| self.prompt_turns.get(id))
Expand All @@ -1007,9 +1014,8 @@ impl ClaudeTranslator {
if let Some(owner) = &owner {
&pending.turn_id == owner
} else {
record
.pointer("/message/content")
.is_some_and(|content| prompt_matches(&pending.content, content))
row.content()
.is_some_and(|content| content.matches_prompt(&pending.content))
}
}) {
owner = self
Expand All @@ -1028,12 +1034,13 @@ impl ClaudeTranslator {
// each user record before propagating its owner through record ancestry.
fn observe_record_turns(&mut self, records: &[Value], ops: &mut Vec<SpanOp>) {
for record in records {
let user_prompt = is_real_user_record(record)
&& record.get("queueTranscriptOnly").and_then(Value::as_bool) != Some(true);
if user_prompt {
self.main_record_turn = self.user_record_turn(record);
let user_prompt = TranscriptEnvelope::deserialize(record)
.ok()
.filter(|row| row.is_user_prompt() && !row.queue_transcript_only);
if let Some(row) = &user_prompt {
self.main_record_turn = self.user_record_turn(record, row);
}
let owner = if user_prompt {
let owner = if user_prompt.is_some() {
self.main_record_turn.clone()
} else {
record
Expand All @@ -1044,10 +1051,11 @@ impl ClaudeTranslator {
.or_else(|| self.main_record_turn.clone())
};
let Some(owner) = owner else { continue };
if user_prompt {
if let Some(content) = record
.pointer("/message/content")
.filter(|content| crate::attachments::contains(content))
if let Some(row) = user_prompt {
if let Some(content) = row
.content()
.map(|content| json!(content))
.filter(crate::attachments::contains)
{
let identity =
self.turn_identities
Expand All @@ -1064,7 +1072,7 @@ impl ClaudeTranslator {
span_id: owner.to_string(),
root_span_id,
parent_span_ids: vec![parent_id],
input: Some(content.clone()),
input: Some(content),
turn_span_id: self.owner_of(owner.as_str()),
..Default::default()
}));
Expand Down Expand Up @@ -1155,27 +1163,47 @@ impl ClaudeTranslator {
}
}

fn flush_previous_turn_rows(&mut self, ops: &mut Vec<SpanOp>) {
let (Some(path), Some(parent)) = (self.main_transcript.clone(), self.last_turn_id.clone())
else {
fn flush_previous_turn_rows(&mut self, prompt: &UserPromptHook, ops: &mut Vec<SpanOp>) {
let previous = self.turn.as_ref().map_or_else(
|| {
self.last_turn_id
.clone()
.map(|id| (id, self.last_turn_cwd.clone()))
},
|turn| Some((turn.id.clone(), turn.cwd.clone())),
);
let (Some(path), Some((parent, cwd))) = (self.main_transcript.clone(), previous) else {
return;
};
let Some(cursor) = self.transcripts.get_mut(&path) else {
return;
};
let split = cursor
.buffered
.iter()
.rposition(is_real_user_record)
.unwrap_or(cursor.buffered.len());
let split = if self.turn.is_some() {
// The replacement hook can run before its prompt is written. In
// that case all bytes observed by this hook belong to the old turn.
prompt.prompt.as_ref().and_then(|prompt| {
cursor.buffered.iter().rposition(|record| {
TranscriptEnvelope::deserialize(record).is_ok_and(|row| {
row.is_user_prompt()
&& !row.queue_transcript_only
&& row
.content()
.is_some_and(|content| content.matches_prompt(prompt))
})
})
})
} else {
cursor.buffered.iter().rposition(is_real_user_record)
}
.unwrap_or(cursor.buffered.len());
let current_turn_rows = cursor.buffered.split_off(split);
let previous_rows = std::mem::replace(&mut cursor.buffered, current_turn_rows);
self.queue_transcript(
previous_rows,
PendingHistory::Main,
"main".into(),
parent,
self.last_turn_cwd.clone(),
cwd,
ops,
);
}
Expand Down Expand Up @@ -1411,9 +1439,10 @@ impl AgentTranslator for ClaudeTranslator {
}
}
"UserPromptSubmit" => {
self.flush_previous_turn_rows(&mut ops);
let prompt = UserPromptHook::deserialize(&event.payload).unwrap_or_default();
self.flush_previous_turn_rows(&prompt, &mut ops);
event_op_start = ops.len();
self.open_turn(event, &mut ops);
self.open_turn(event, prompt, &mut ops);
}
"UserPromptExpansion" => self.record_skill(event, &mut ops),
"PreToolUse" => self.pre_tool(event, &mut ops),
Expand Down Expand Up @@ -1632,7 +1661,10 @@ pub(crate) fn successful_subagent_handback_message(records: &[Value]) -> Option<
.and_then(|tool| tool.handback_message())
}

fn continuation_origin(payload: &Value) -> Option<(&'static str, &str)> {
fn continuation_origin<'a>(
payload: &'a Value,
prompt: Option<&'a str>,
) -> Option<(&'static str, &'a str)> {
if let Some(origin) = payload.get("origin") {
if origin.get("kind").and_then(Value::as_str) == Some("peer")
&& origin.get("handback").and_then(Value::as_bool) == Some(true)
Expand All @@ -1644,7 +1676,7 @@ fn continuation_origin(payload: &Value) -> Option<(&'static str, &str)> {
return (!id.is_empty()).then_some(("agent_message", id));
}
}
let prompt = payload.get("prompt")?.as_str()?.trim();
let prompt = prompt?.trim();
if let Some(id) = task_notification_id(prompt) {
return Some(("task_notification", id));
}
Expand All @@ -1667,49 +1699,10 @@ fn task_notification_id(prompt: &str) -> Option<&str> {
(!id.is_empty()).then_some(id)
}

fn prompt_matches(prompt: &Value, content: &Value) -> bool {
if prompt == content {
return true;
}
let (Some(mut remaining), Some(blocks)) = (prompt.as_str(), content.as_array()) else {
return false;
};
// Native hooks use a string, while transcripts may wrap the same prompt
// in text blocks alongside images. Compare without allocating a joined copy.
let mut has_text = false;
for text in blocks.iter().filter_map(|block| {
(block.get("type").and_then(Value::as_str) == Some("text"))
.then(|| block.get("text").and_then(Value::as_str))
.flatten()
}) {
has_text = true;
let Some(rest) = remaining.strip_prefix(text) else {
return false;
};
remaining = rest;
}
remaining.is_empty() && (has_text || crate::attachments::contains(content))
}

fn is_real_user_record(record: &Value) -> bool {
let Some(envelope) = decode::<TranscriptEnvelope>(record) else {
return false;
};
if envelope.kind.as_deref() != Some("user") {
return false;
}
if envelope.is_compact_summary {
return false;
}
!record
.pointer("/message/content")
.and_then(Value::as_array)
.is_some_and(|blocks| {
blocks
.iter()
.any(|block| block.get("type").and_then(Value::as_str) == Some("tool_result"))
})
TranscriptEnvelope::deserialize(record).is_ok_and(|row| row.is_user_prompt())
}

/// Read newline-delimited records forward from `offset`, advancing it past
/// everything consumed.
///
Expand Down
Loading
Loading