Skip to content
Open
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());
}
}
15 changes: 14 additions & 1 deletion bt-daemon/src/transcript_import/claude.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -52,6 +53,9 @@ impl TailSession for Tail {
len: u64,
finalize: bool,
) -> anyhow::Result<Vec<Envelope>> {
if events.is_empty() {
return Ok(events);
}
if events.len() < 2 {
bail!("Claude import did not produce session boundary events");
}
Expand Down Expand Up @@ -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()
Expand Down
127 changes: 127 additions & 0 deletions bt-daemon/src/transcript_import/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::<Vec<_>>(),
["Stop", "SessionEnd"],
);
assert!(copied.is_empty());
assert_eq!(
active
.iter()
.map(|event| event.event.as_str())
.collect::<Vec<_>>(),
["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::<String>(),
)
.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::<Vec<_>>();
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();
Expand Down
30 changes: 26 additions & 4 deletions bt-daemon/src/translate/claude.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -1812,6 +1825,15 @@ fn read_event_records(event: &Envelope, path: &str, offset: &mut u64) -> Vec<Val
let Ok(fields) = TranscriptPayload::decode(&event.payload) else {
return Vec::new();
};
read_records_for_payload(event.ts_ms, &fields, path, offset)
}

fn read_records_for_payload(
event_ts_ms: i64,
fields: &TranscriptPayload,
path: &str,
offset: &mut u64,
) -> Vec<Value> {
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
Expand All @@ -1837,7 +1859,7 @@ fn read_event_records(event: &Envelope, path: &str, offset: &mut u64) -> Vec<Val
// are interchangeable between them. An import offset is the
// tighter bound when present.
let through = import_through_offset.unwrap_or(through);
let cutoff = import_through_offset.is_none().then_some(event.ts_ms);
let cutoff = import_through_offset.is_none().then_some(event_ts_ms);
if std::fs::metadata(mirror_path).is_ok() {
return read_file_bounded(mirror_path, offset, cutoff, Some(through));
}
Expand All @@ -1850,10 +1872,10 @@ fn read_event_records(event: &Envelope, path: &str, offset: &mut u64) -> Vec<Val
(Some(contents), through @ Some(_)) => {
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),
}
}

Expand Down
Loading
Loading