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());
}
}
32 changes: 17 additions & 15 deletions bt-daemon/src/transcript_import/claude.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@ use super::{
string_at, timestamp_bounds, timestamp_ms, validate_session_id, IncrementalRecords,
TailSession, TranscriptImport, TranscriptLayout,
};
use crate::translate::ClaudeTranscriptEnvelope;
use crate::wire::Envelope;
use anyhow::bail;
use serde::Deserialize;
use serde_json::{json, Value};
use std::collections::{HashMap, HashSet};
use std::io::BufRead;
Expand Down Expand Up @@ -307,7 +309,16 @@ pub(super) fn envelopes(
record_end_offsets[record_index],
));
}
let error = last_assistant_error(segment);
let error = if segment
.iter()
.rev()
.take_while(|record| record.get("type").and_then(Value::as_str) != Some("assistant"))
.any(is_interrupt_record)
{
Some("Request interrupted by user".to_owned())
} else {
last_assistant_error(segment)
};
let stop_event = if error.is_some() {
"StopFailure"
} else {
Expand Down Expand Up @@ -675,21 +686,12 @@ fn import_envelope(
)
}

fn is_interrupt_record(record: &Value) -> bool {
ClaudeTranscriptEnvelope::deserialize(record).is_ok_and(|row| row.is_interrupt())
}

fn is_real_user(record: &Value) -> bool {
if record.get("type").and_then(Value::as_str) != Some("user") {
return false;
}
if record.get("isCompactSummary").and_then(Value::as_bool) == Some(true) {
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"))
})
ClaudeTranscriptEnvelope::deserialize(record).is_ok_and(|row| row.is_import_turn_start())
}

fn last_assistant_text(records: &[Value]) -> Option<Value> {
Expand Down
38 changes: 38 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,44 @@ mod tests {
assert!(!tail.retry_envelopes);
}

#[test]
fn claude_import_distinguishes_prompts_from_native_bookkeeping() {
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("session.jsonl");
let records = [
json!({"type":"user","sessionId":"session","message":{"content":"read the skill"}}),
json!({"type":"user","isMeta":true,"message":{"content":"injected skill body"}}),
json!({"type":"user","isMeta":true,"message":{"content":"[Image: source: image.png]"}}),
json!({"type":"assistant","message":{"content":"working"}}),
json!({"type":"user","message":{"content":[{"type":"text","text":"[Request interrupted by user]"}]}}),
json!({"type":"user","message":{"content":"<local-command-caveat>local only</local-command-caveat>"}}),
json!({"type":"user","message":{"content":"<command-name>/context</command-name>"}}),
json!({"type":"user","message":{"content":"<local-command-stdout>result</local-command-stdout>"}}),
json!({"type":"user","message":{"content":"next question"}}),
json!({"type":"assistant","message":{"content":"answer"}}),
];
std::fs::write(
&path,
records
.iter()
.map(|row| format!("{row}\n"))
.collect::<String>(),
)
.unwrap();
let events = transcript_envelopes(&path, ImportSource::Claude).unwrap();
let prompts = events
.iter()
.filter(|event| event.event == "UserPromptSubmit")
.map(|event| event.payload["prompt"].as_str().unwrap())
.collect::<Vec<_>>();
assert_eq!(prompts, ["read the skill", "next question"]);
let failure = events
.iter()
.find(|event| event.event == "StopFailure")
.unwrap();
assert_eq!(failure.payload["error"], "Request interrupted by user");
}

#[test]
fn claude_tail_closes_only_completed_turns() {
let temp = tempfile::tempdir().unwrap();
Expand Down
20 changes: 2 additions & 18 deletions bt-daemon/src/translate/claude.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ use subagent_hook::SubagentHook;
#[cfg(test)]
use timestamp_envelope::parse_rfc3339_timestamp;
use timestamp_envelope::parse_timestamp_ms;
use transcript_envelope::TranscriptEnvelope;
pub(crate) use transcript_envelope::TranscriptEnvelope;
use transcript_tool::TranscriptTool;

use super::git::GitMetadataCache;
Expand Down Expand Up @@ -1692,23 +1692,7 @@ fn prompt_matches(prompt: &Value, content: &Value) -> bool {
}

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"))
})
decode::<TranscriptEnvelope>(record).is_some_and(|row| row.is_user_prompt())
}
/// Read newline-delimited records forward from `offset`, advancing it past
/// everything consumed.
Expand Down
88 changes: 83 additions & 5 deletions bt-daemon/src/translate/claude/transcript_envelope.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,91 @@
use serde::{Deserialize, Serialize};
use serde::Deserialize;

/// Stable routing fields from one Claude transcript row. Message and tool
/// blocks intentionally remain raw because they are preserved in span I/O.
#[derive(Deserialize, Serialize)]
pub(super) struct TranscriptEnvelope {
/// Stable routing fields from one Claude transcript row.
#[derive(Deserialize)]
pub(crate) struct TranscriptEnvelope {
#[serde(rename = "type", default)]
pub(super) kind: Option<String>,
#[serde(default)]
pub(super) subtype: Option<String>,
#[serde(rename = "isCompactSummary", default)]
pub(super) is_compact_summary: bool,
#[serde(rename = "isMeta", default)]
is_meta: bool,
#[serde(rename = "queueTranscriptOnly", default)]
queue_transcript_only: bool,
message: Option<TranscriptMessage>,
}

#[derive(Deserialize)]
struct TranscriptMessage {
content: Option<TranscriptContent>,
}

#[derive(Deserialize)]
#[serde(untagged)]
enum TranscriptContent {
Text(String),
Blocks(Vec<TranscriptBlock>),
Other(serde::de::IgnoredAny),
}

#[derive(Deserialize)]
struct TranscriptBlock {
#[serde(rename = "type")]
kind: Option<String>,
text: Option<String>,
}

impl TranscriptEnvelope {
pub(super) fn is_user_prompt(&self) -> bool {
self.kind.as_deref() == Some("user")
&& !self.is_compact_summary
&& !matches!(
self.content(),
Some(TranscriptContent::Blocks(blocks))
if blocks.iter().any(|block| block.kind.as_deref() == Some("tool_result"))
)
}

pub(crate) fn is_import_turn_start(&self) -> bool {
self.is_user_prompt()
&& !self.is_meta
&& !self.queue_transcript_only
&& !self.is_interrupt()
&& !self.user_text().is_some_and(|text| {
[
"<local-command-caveat>",
"<command-name>",
"<local-command-stdout>",
"<local-command-stderr>",
]
.iter()
.any(|tag| text.trim_start().starts_with(tag))
})
}

pub(crate) fn is_interrupt(&self) -> bool {
self.kind.as_deref() == Some("user")
&& matches!(
self.user_text().map(str::trim),
Some(
"[Request interrupted by user]" | "[Request interrupted by user for tool use]"
)
)
}

fn content(&self) -> Option<&TranscriptContent> {
self.message.as_ref()?.content.as_ref()
}

fn user_text(&self) -> Option<&str> {
match self.content()? {
TranscriptContent::Text(text) => Some(text),
TranscriptContent::Blocks(blocks) => match blocks.as_slice() {
[block] if block.kind.as_deref() == Some("text") => block.text.as_deref(),
_ => None,
},
TranscriptContent::Other(_) => None,
}
}
}
4 changes: 3 additions & 1 deletion bt-daemon/src/translate/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,9 @@ mod muse;
mod opencode;
mod opencode_v2;
mod pi;
pub(crate) use claude::successful_subagent_handback_message;
pub(crate) use claude::{
successful_subagent_handback_message, TranscriptEnvelope as ClaudeTranscriptEnvelope,
};
pub(crate) use pi::request_config as pi_request_config;
mod origins;
pub(crate) mod recent;
Expand Down
7 changes: 7 additions & 0 deletions bt-daemon/tests/agent_integration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -368,6 +368,13 @@ async fn pi_session_emits_traces() {
if request.has_function_output("call_pi_1") {
return MockReply::response(OpenAiTurn::text("PI_MOCK_OK"));
}
// Oh My Pi sends auxiliary requests without tools to the same
// provider before the actual prompt. Only drive the shell turn when
// tools are offered. The assertions below still require the tool
// call, its result, and their delivered trace.
if request.tool_names().is_empty() {
return MockReply::response(OpenAiTurn::text("Integration test"));
}
MockReply::response(shell_tool_call(
&request,
"call_pi_1",
Expand Down
18 changes: 6 additions & 12 deletions src/plugins/pi/content/src/daemon-adapter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,18 +17,12 @@ const mockState = vi.hoisted(() => ({
permalink: "https://www.braintrust.dev/trace/1" as string | undefined,
}));

vi.mock("@earendil-works/pi-tui", async (importOriginal) => {
const original = await importOriginal<typeof import("@earendil-works/pi-tui")>();
return {
...original,
get getCapabilities() {
return mockState.ompTui ? undefined : () => ({ hyperlinks: mockState.hyperlinks });
},
get hyperlink() {
return mockState.ompTui ? undefined : original.hyperlink;
},
};
});
vi.mock("./pi-tui.ts", () => ({
loadPiHyperlinkHelpers: async () =>
mockState.ompTui
? {}
: { getCapabilities: () => ({ hyperlinks: mockState.hyperlinks }), hyperlink },
}));

vi.mock("./runtime/daemon-client.ts", () => ({
claimManagedTracingInstance: () => mockState.claim,
Expand Down
Loading
Loading