diff --git a/bt-daemon/src/collections/legacy.rs b/bt-daemon/src/collections/legacy.rs index 60853be3..43564bfd 100644 --- a/bt-daemon/src/collections/legacy.rs +++ b/bt-daemon/src/collections/legacy.rs @@ -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, @@ -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?; @@ -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?; } diff --git a/bt-daemon/src/collections/tests.rs b/bt-daemon/src/collections/tests.rs index e3de1129..1974cc99 100644 --- a/bt-daemon/src/collections/tests.rs +++ b/bt-daemon/src/collections/tests.rs @@ -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()); + } +} diff --git a/bt-daemon/src/transcript_import/claude.rs b/bt-daemon/src/transcript_import/claude.rs index c85ffaf4..6397c7f7 100644 --- a/bt-daemon/src/transcript_import/claude.rs +++ b/bt-daemon/src/transcript_import/claude.rs @@ -3,6 +3,7 @@ use super::{ string_at, timestamp_bounds, timestamp_ms, validate_session_id, IncrementalRecords, TailSession, TranscriptImport, TranscriptLayout, }; +use crate::translate::{cli_fork_history, CliForkHistory}; use crate::wire::Envelope; use anyhow::bail; use serde_json::{json, Value}; @@ -52,6 +53,9 @@ impl TailSession for Tail { len: u64, finalize: bool, ) -> anyhow::Result> { + if events.is_empty() { + return Ok(events); + } if events.len() < 2 { bail!("Claude import did not produce session boundary events"); } @@ -175,7 +179,16 @@ pub(super) fn envelopes( .find_map(|record| string_at(record, "/sessionId")) .unwrap_or_else(|| file_session_id(path)) }); - let inherited_prefix = own_start.unwrap_or(0); + let inherited_prefix = match own_start.filter(|&index| index > 0) { + Some(index) => index, + None => match cli_fork_history(records) { + CliForkHistory::Absent => 0, + // Wait to emit SessionStart until its offset includes the whole + // inherited prefix. Copied prompts must never advance turn indices. + CliForkHistory::AwaitingPrompt => return Ok(Vec::new()), + CliForkHistory::EndsAt(index) => index, + }, + }; let own_records = &records[inherited_prefix..]; let source_version = own_records .iter() diff --git a/bt-daemon/src/transcript_import/mod.rs b/bt-daemon/src/transcript_import/mod.rs index 117a1669..2b753bcd 100644 --- a/bt-daemon/src/transcript_import/mod.rs +++ b/bt-daemon/src/transcript_import/mod.rs @@ -1592,6 +1592,133 @@ mod tests { assert!(!tail.retry_envelopes); } + #[test] + fn claude_cli_fork_attach_waits_for_the_forks_own_prompt() { + use std::io::Write; + + let tmp = tempfile::tempdir().unwrap(); + let path = tmp.path().join("fork.jsonl"); + std::fs::write( + &path, + concat!( + "{\"type\":\"queue-operation\",\"sessionId\":\"fork\",\"operation\":\"enqueue\",\"timestamp\":\"2026-01-01T00:00:10Z\"}\n", + "{\"type\":\"user\",\"sessionId\":\"fork\",\"timestamp\":\"2026-01-01T00:00:01Z\",\"message\":{\"content\":\"old one\"}}\n", + "{\"type\":\"assistant\",\"sessionId\":\"fork\",\"timestamp\":\"2026-01-01T00:00:02Z\",\"message\":{\"content\":\"old answer one\"}}\n", + "{\"type\":\"user\",\"sessionId\":\"fork\",\"timestamp\":\"2026-01-01T00:00:03Z\",\"message\":{\"content\":\"old two\"}}\n", + "{\"type\":\"assistant\",\"sessionId\":\"fork\",\"timestamp\":\"2026-01-01T00:00:04Z\",\"message\":{\"content\":\"old answer two\"}}\n", + ), + ) + .unwrap(); + let append_line = |record: Value| { + let mut file = std::fs::OpenOptions::new() + .append(true) + .open(&path) + .unwrap(); + writeln!(file, "{record}").unwrap(); + }; + let mut tail = TranscriptTail::new(path.clone(), ImportSource::Claude); + let copied = tail.poll(false).unwrap(); + append_line( + json!({"type":"user","sessionId":"fork","timestamp":"2026-01-01T00:00:11Z","message":{"content":"new question"}}), + ); + let active = tail.poll(false).unwrap(); + append_line( + json!({"type":"assistant","sessionId":"fork","timestamp":"2026-01-01T00:00:12Z","message":{"content":"new answer"}}), + ); + let finalized = tail.poll(true).unwrap(); + assert_eq!( + finalized + .iter() + .map(|event| event.event.as_str()) + .collect::>(), + ["Stop", "SessionEnd"], + ); + assert!(copied.is_empty()); + assert_eq!( + active + .iter() + .map(|event| event.event.as_str()) + .collect::>(), + ["SessionStart", "UserPromptSubmit", "ImportCheckpoint"], + ); + } + + #[test] + fn claude_cli_fork_keeps_copied_work_as_context_in_import_and_live_translation() { + use crate::translate::{Registry, SessionCtx, SpanOp, SpanType}; + + let tmp = tempfile::tempdir().unwrap(); + let path = tmp.path().join("fork.jsonl"); + let records = [ + json!({"type":"queue-operation","sessionId":"fork","operation":"enqueue","timestamp":"2026-01-01T00:00:10Z"}), + json!({"type":"user","sessionId":"fork","timestamp":"2026-01-01T00:00:01Z","message":{"content":"old question"}}), + json!({"type":"assistant","sessionId":"fork","timestamp":"2026-01-01T00:00:02Z","message":{"id":"old","content":[{"type":"text","text":"old answer"}]}}), + json!({"type":"user","sessionId":"fork","timestamp":"2026-01-01T00:00:11Z","message":{"content":"new question"}}), + json!({"type":"assistant","sessionId":"fork","timestamp":"2026-01-01T00:00:12Z","message":{"id":"new","content":[{"type":"text","text":"new answer"}]}}), + ]; + std::fs::write( + &path, + records + .iter() + .map(|row| format!("{row}\n")) + .collect::(), + ) + .unwrap(); + let imported = transcript_envelopes(&path, ImportSource::Claude).unwrap(); + let live = vec![ + envelope( + "claude-code", + None, + "fork", + "UserPromptSubmit", + 1_767_225_611_000, + json!({"transcript_path":path,"prompt":"new question"}), + ), + envelope( + "claude-code", + None, + "fork", + "Stop", + 1_767_225_613_000, + json!({"transcript_path":path,"last_assistant_message":"new answer"}), + ), + ]; + let ctx = SessionCtx { + session_id: "fork".into(), + config: None, + }; + for events in [imported, live] { + let mut translator = Registry::default_agents().create("claude-code", "fork"); + let mut ops = Vec::new(); + for event in events { + ops.extend(translator.handle(&event, &ctx).unwrap()); + while let Some(more) = translator.drain_pending(&ctx).unwrap() { + ops.extend(more); + } + } + let calls = ops + .iter() + .filter_map(|op| match op { + SpanOp::Insert(row) if row.span_type == SpanType::Llm => Some(row), + _ => None, + }) + .collect::>(); + assert_eq!(calls.len(), 1); + assert!(calls[0] + .input + .as_ref() + .unwrap() + .to_string() + .contains("old answer")); + assert!(calls[0] + .output + .as_ref() + .unwrap() + .to_string() + .contains("new answer")); + } + } + #[test] fn claude_tail_closes_only_completed_turns() { let temp = tempfile::tempdir().unwrap(); diff --git a/bt-daemon/src/translate/claude.rs b/bt-daemon/src/translate/claude.rs index 66db8853..8254a875 100644 --- a/bt-daemon/src/translate/claude.rs +++ b/bt-daemon/src/translate/claude.rs @@ -27,6 +27,7 @@ use subagent_hook::SubagentHook; use timestamp_envelope::parse_rfc3339_timestamp; use timestamp_envelope::parse_timestamp_ms; use transcript_envelope::TranscriptEnvelope; +pub(crate) use transcript_envelope::{cli_fork_history, CliForkHistory}; use transcript_tool::TranscriptTool; use super::git::GitMetadataCache; @@ -308,11 +309,23 @@ impl ClaudeTranslator { return; }; let cursor = self.transcripts.entry(path.clone()).or_default(); - let rows = read_event_records(event, &path, &mut cursor.offset); + let Ok(fields) = TranscriptPayload::decode(&event.payload) else { + return; + }; + let rows = read_records_for_payload(event.ts_ms, &fields, &path, &mut cursor.offset); if self.claude_version.is_none() { self.claude_version = rows.iter().find_map(|row| string_field(row, "version")); } cursor.buffered.extend(rows); + if fields.import_through_offset.is_none() && self.last_turn_id.is_none() { + if let CliForkHistory::EndsAt(end) = cli_fork_history(&cursor.buffered) { + let remainder = cursor.buffered.split_off(end); + let history = std::mem::replace(&mut cursor.buffered, remainder); + self.main_history = std::mem::take(&mut self.main_history) + .parse_records(&history) + .history; + } + } } fn observe_session_details(&mut self, hook: &HookContext) { @@ -1812,6 +1825,15 @@ fn read_event_records(event: &Envelope, path: &str, offset: &mut u64) -> Vec Vec { let import_through_offset = fields.import_through_offset; if let Some(mirrors) = &fields.claude_mirrors { // This marker records even an absent/unreadable file. Never replace a @@ -1837,7 +1859,7 @@ fn read_event_records(event: &Envelope, path: &str, offset: &mut u64) -> Vec Vec { read_snapshot_bounded(contents, offset, None, through) } - (Some(contents), None) => read_snapshot_bounded(contents, offset, Some(event.ts_ms), None), + (Some(contents), None) => read_snapshot_bounded(contents, offset, Some(event_ts_ms), None), (None, through @ Some(_)) => read_file_bounded(path, offset, None, through), (None, None) if fields.replay == Some(true) => Vec::new(), - (None, None) => read_file_bounded(path, offset, Some(event.ts_ms), None), + (None, None) => read_file_bounded(path, offset, Some(event_ts_ms), None), } } diff --git a/bt-daemon/src/translate/claude/transcript_envelope.rs b/bt-daemon/src/translate/claude/transcript_envelope.rs index 1bbfa928..9c128cfc 100644 --- a/bt-daemon/src/translate/claude/transcript_envelope.rs +++ b/bt-daemon/src/translate/claude/transcript_envelope.rs @@ -1,4 +1,6 @@ +use super::parse_timestamp_ms; use serde::{Deserialize, Serialize}; +use serde_json::Value; /// Stable routing fields from one Claude transcript row. Message and tool /// blocks intentionally remain raw because they are preserved in span I/O. @@ -8,6 +10,66 @@ pub(super) struct TranscriptEnvelope { pub(super) kind: Option, #[serde(default)] pub(super) subtype: Option, + pub(super) operation: Option, #[serde(rename = "isCompactSummary", default)] pub(super) is_compact_summary: bool, } + +#[derive(Deserialize, Serialize)] +#[serde(rename_all = "snake_case")] +pub(super) enum QueueOperation { + Enqueue, + #[serde(other)] + Other, +} + +pub(crate) enum CliForkHistory { + Absent, + AwaitingPrompt, + EndsAt(usize), +} + +/// CLI forks stamp copied records with their own session ID. Claude queues the +/// new prompt before writing that copied history, retaining its old timestamps. +pub(crate) fn cli_fork_history(records: &[Value]) -> CliForkHistory { + let mut queued_at = None; + let mut copied_assistant = false; + for (index, record) in records.iter().enumerate() { + let Ok(row) = TranscriptEnvelope::deserialize(record) else { + continue; + }; + match row.kind.as_deref() { + Some("queue-operation") if matches!(row.operation, Some(QueueOperation::Enqueue)) => { + if queued_at.is_none() { + queued_at = parse_timestamp_ms(record); + } + } + Some("user") if matches!((queued_at, parse_timestamp_ms(record)), (Some(queue), Some(user)) if user >= queue) => + { + return if copied_assistant { + CliForkHistory::EndsAt(index) + } else { + CliForkHistory::Absent + }; + } + Some("user") if queued_at.is_none() || parse_timestamp_ms(record).is_none() => { + return CliForkHistory::Absent; + } + Some("assistant") => { + let (Some(queue), Some(assistant)) = (queued_at, parse_timestamp_ms(record)) else { + return CliForkHistory::Absent; + }; + if assistant >= queue { + return CliForkHistory::Absent; + } + copied_assistant = true; + } + _ => {} + } + } + if queued_at.is_some() { + CliForkHistory::AwaitingPrompt + } else { + CliForkHistory::Absent + } +} diff --git a/bt-daemon/src/translate/mod.rs b/bt-daemon/src/translate/mod.rs index 87e8d6c9..e8000083 100644 --- a/bt-daemon/src/translate/mod.rs +++ b/bt-daemon/src/translate/mod.rs @@ -22,7 +22,7 @@ mod muse; mod opencode; mod opencode_v2; mod pi; -pub(crate) use claude::successful_subagent_handback_message; +pub(crate) use claude::{cli_fork_history, successful_subagent_handback_message, CliForkHistory}; pub(crate) use pi::request_config as pi_request_config; mod origins; pub(crate) mod recent;