diff --git a/bt-daemon/src/collections/events.rs b/bt-daemon/src/collections/events.rs index 12b568fa..212217f7 100644 --- a/bt-daemon/src/collections/events.rs +++ b/bt-daemon/src/collections/events.rs @@ -201,6 +201,21 @@ pub(super) fn retain_references(identity: &mut RedactedEnvelope, previous: &Reda payload.insert(key.into(), value.clone()); } } + if let Some(old_children) = old + .get("_bt_claude_children") + .and_then(serde_json::Value::as_object) + { + let children = payload + .entry("_bt_claude_children") + .or_insert_with(|| serde_json::json!({})); + if let Some(children) = children.as_object_mut() { + for (agent, observation) in old_children { + children + .entry(agent.clone()) + .or_insert_with(|| observation.clone()); + } + } + } } } @@ -213,6 +228,29 @@ pub(super) fn identity(event: &RedactedEnvelope) -> RedactedEnvelope { .filter_map(|key| Some(((*key).into(), event.payload.get(*key)?.clone()))) .collect(), ); + if event.source == "claude-code" + && matches!(event.event.as_str(), "SubagentStop" | "TranscriptUpdate") + { + if let (Some(agent), Some(path)) = ( + event + .payload + .get("agent_id") + .and_then(serde_json::Value::as_str), + event + .payload + .get("agent_transcript_path") + .and_then(serde_json::Value::as_str), + ) { + let through = event + .payload + .get("_bt_claude_transcript_mirrors") + .and_then(|m| m.get(path)) + .and_then(|m| m.get("through")) + .cloned(); + identity.payload["_bt_claude_children"] = + serde_json::json!({agent: {"path": path, "through": through}}); + } + } identity } diff --git a/bt-daemon/src/server/claude_transcripts.rs b/bt-daemon/src/server/claude_transcripts.rs index 25281d77..61e9f0e6 100644 --- a/bt-daemon/src/server/claude_transcripts.rs +++ b/bt-daemon/src/server/claude_transcripts.rs @@ -9,6 +9,13 @@ pub(super) struct ClaudeTranscriptObservation { /// Synthetic-event provenance only: never retain native prompts or responses. pub(super) template: Envelope, pub(super) through: Option, + pub(super) children: HashMap, +} + +#[derive(Clone)] +pub(super) struct ClaudeChildObservation { + pub(super) template: Envelope, + pub(super) through: Option, } impl Daemon { @@ -16,12 +23,6 @@ impl Daemon { if env.source != "claude-code" || env.payload.get("_bt_import_through_offset").is_some() { return; } - if env.event == "SessionEnd" { - self.claude_transcripts - .lock() - .retain(|key, _| key.source != env.source || key.session_id != env.session_id); - return; - } let Some(route) = env.route.as_ref() else { return; }; @@ -60,8 +61,9 @@ impl Daemon { config: None, }; let mut observations = self.claude_transcripts.lock(); - let previous = observations - .get(&key) + let old = observations.remove(&key); + let previous = old + .as_ref() .filter(|observation| { observation .template @@ -71,11 +73,64 @@ impl Daemon { == Some(path) }) .and_then(|observation| observation.through); + let mut children = old + .map(|observation| observation.children) + .unwrap_or_default(); + if let Some(saved) = env + .payload + .get("_bt_claude_children") + .and_then(Value::as_object) + { + for (agent_id, observation) in saved { + let Some(child_path) = observation.get("path").and_then(Value::as_str) else { + continue; + }; + let mut child_template = template.clone(); + child_template.payload["agent_id"] = Value::String(agent_id.clone()); + child_template.payload["agent_transcript_path"] = + Value::String(child_path.to_string()); + children.insert( + agent_id.clone(), + ClaudeChildObservation { + template: child_template, + through: observation.get("through").and_then(Value::as_u64), + }, + ); + } + } + if matches!(env.event.as_str(), "SubagentStop" | "TranscriptUpdate") { + if let (Some(agent_id), Some(child_path)) = ( + env.payload.get("agent_id").and_then(Value::as_str), + env.payload + .get("agent_transcript_path") + .and_then(Value::as_str), + ) { + let child_through = env + .payload + .get("_bt_claude_transcript_mirrors") + .and_then(|mirrors| mirrors.get(child_path)) + .and_then(|mirror| mirror.get("through")) + .and_then(Value::as_u64); + let mut child_template = template.clone(); + child_template.payload["agent_id"] = Value::String(agent_id.to_string()); + child_template.payload["agent_transcript_path"] = + Value::String(child_path.to_string()); + let previous = children.get(agent_id).and_then(|child| child.through); + children.insert( + agent_id.to_string(), + ClaudeChildObservation { + template: child_template, + through: child_through.or(previous), + }, + ); + } + } observations.insert( key, ClaudeTranscriptObservation { template, through: through.or(previous), + children, }, ); } @@ -117,35 +172,42 @@ impl Daemon { let Some(observation) = observation else { continue; }; - let Some(path) = observation - .template - .payload - .get("transcript_path") - .and_then(Value::as_str) - else { - tracing::warn!(session_id = %key.session_id, "Claude transcript observation has no transcript path"); - continue; - }; - let Ok(metadata) = tokio::fs::metadata(path).await else { - continue; - }; - if observation.through == Some(metadata.len()) { - continue; - } - let mut env = observation.template; - env.ts_ms = now_ms(); - hydrate_transcript_reference(&self.data_dir, &mut env).await; - let through = env - .payload - .get("_bt_claude_transcript_mirrors") - .and_then(|mirrors| mirrors.get(env.payload.get("transcript_path")?.as_str()?)) - .and_then(|mirror| mirror.get("through")) - .and_then(Value::as_u64); - if through.is_none() || through == observation.through { - continue; - } - if let Err(error) = self.journal_and_enqueue(env).await { - tracing::warn!(session_id = %key.session_id, %error, "Claude transcript observation failed"); + let mut targets = vec![(observation.template, observation.through, "transcript_path")]; + targets.extend( + observation + .children + .into_values() + .map(|child| (child.template, child.through, "agent_transcript_path")), + ); + for (mut env, previous, field) in targets { + let Some(path) = env + .payload + .get(field) + .and_then(Value::as_str) + .map(str::to_owned) + else { + continue; + }; + let Ok(metadata) = tokio::fs::metadata(&path).await else { + continue; + }; + if previous == Some(metadata.len()) { + continue; + } + env.ts_ms = now_ms(); + hydrate_transcript_reference(&self.data_dir, &mut env).await; + let through = env + .payload + .get("_bt_claude_transcript_mirrors") + .and_then(|mirrors| mirrors.get(&path)) + .and_then(|mirror| mirror.get("through")) + .and_then(Value::as_u64); + if through.is_none() || through == previous { + continue; + } + if let Err(error) = self.journal_and_enqueue(env).await { + tracing::warn!(session_id = %key.session_id, %error, "Claude transcript observation failed"); + } } } } diff --git a/bt-daemon/src/server/recovery.rs b/bt-daemon/src/server/recovery.rs index 00bc4987..29f80235 100644 --- a/bt-daemon/src/server/recovery.rs +++ b/bt-daemon/src/server/recovery.rs @@ -186,9 +186,21 @@ pub(super) async fn discover_unprocessed_journals(daemon: &Arc) -> Vec

, subagents: HashMap, subagent_handbacks: HashMap, + #[serde(default)] + observe_stopped_subagents: bool, /// Skills the user asked for on the current (or next) turn: `/skill` /// expansions and `SKILL.md` paths named in the prompt. Cleared when a /// turn stops, so a turn that ends without a Stop hands its skills to the @@ -360,6 +362,7 @@ impl ClaudeTranslator { pending_tools: HashMap::new(), subagents: HashMap::new(), subagent_handbacks: HashMap::new(), + observe_stopped_subagents: false, requested_skills: Vec::new(), pending_emission: None, claude_version: None, @@ -941,6 +944,11 @@ impl ClaudeTranslator { } fn stop_subagent(&mut self, event: &Envelope, hook: SubagentHook, ops: &mut Vec) { + if event.payload.get("_bt_import_through_offset").is_none() + && hook.agent_transcript_path.is_some() + { + self.observe_stopped_subagents = true; + } let agent_id = hook.agent_id.clone(); let parent = self.ensure_subagent(&hook, event, ops); let parent_span_ids = self @@ -1081,6 +1089,7 @@ impl ClaudeTranslator { } fn release_terminal_state(&mut self) { + self.observe_stopped_subagents = false; self.main_history = MessageHistory::default(); self.transcripts.clear(); self.subagents.clear(); @@ -1426,10 +1435,14 @@ impl ClaudeTranslator { } self.end_root(event.ts_ms, ops); self.root_open = false; - if let Some(pending) = &mut self.pending_emission { - pending.clear_after = true; - } else { - self.release_terminal_state(); + // A stopped live subagent may append after session end. Keep its + // deduplication state until the observer is finalized. + if !self.observe_stopped_subagents { + if let Some(pending) = &mut self.pending_emission { + pending.clear_after = true; + } else { + self.release_terminal_state(); + } } } } @@ -1556,6 +1569,23 @@ impl AgentTranslator for ClaudeTranslator { self.stop_subagent(event, hook, &mut ops); } } + "TranscriptUpdate" if event.payload.get("agent_transcript_path").is_some() => { + if let (Some(agent_id), Some(path)) = ( + string_field(&event.payload, "agent_id"), + string_field(&event.payload, "agent_transcript_path"), + ) { + let mut offset = 0; + let records = read_event_records(event, &path, &mut offset); + self.queue_transcript( + records, + PendingHistory::Owned(MessageHistory::default()), + format!("subagent:{agent_id}"), + ids::span_id(&self.session_id, &format!("subagent:{agent_id}")), + self.current_cwd.clone(), + &mut ops, + ); + } + } "TranscriptUpdate" if self.turn.is_none() => { if let Some(parent) = self.last_turn_id.clone() { self.emit_main(&parent, &mut ops); diff --git a/bt-daemon/tests/claude_translator.rs b/bt-daemon/tests/claude_translator.rs index cef84fdd..4d630420 100644 --- a/bt-daemon/tests/claude_translator.rs +++ b/bt-daemon/tests/claude_translator.rs @@ -774,6 +774,88 @@ fn claude_subagent_handback_report_is_the_span_output() { ); } +#[test] +fn claude_captures_subagent_model_call_appended_after_stop() { + let tmp = tempfile::tempdir().unwrap(); + let transcript = tmp.path().join("agent-worker.jsonl"); + let first = json!({"type":"assistant","timestamp":"1970-01-01T00:00:03Z","message":{"id":"first","model":"claude-test","content":[{"type":"text","text":"first"}],"usage":{"input_tokens":2,"output_tokens":1}}}); + let last = json!({"type":"assistant","timestamp":"1970-01-01T00:00:06Z","message":{"id":"last","model":"claude-test","content":[{"type":"text","text":"last"}],"usage":{"input_tokens":3,"output_tokens":2}}}); + std::fs::write(&transcript, format!("{first}\n")).unwrap(); + let registry = Registry::default_agents(); + let mut translator = registry.create("claude-code", "late-subagent"); + let ctx = SessionCtx { + session_id: "late-subagent".into(), + config: None, + }; + let path = transcript.to_str().unwrap(); + let mut ops = Vec::new(); + for event in [ + claude_event( + &ctx.session_id, + "UserPromptSubmit", + 1000, + json!({"prompt":"delegate"}), + ), + claude_event( + &ctx.session_id, + "SubagentStart", + 2000, + json!({"agent_id":"worker","agent_type":"reviewer"}), + ), + claude_event( + &ctx.session_id, + "SubagentStop", + 4000, + json!({"agent_id":"worker","agent_type":"reviewer","agent_transcript_path":path}), + ), + claude_event(&ctx.session_id, "SessionEnd", 5000, json!({})), + ] { + ops.extend(translator.handle(&event, &ctx).unwrap()); + while let Some(batch) = translator.drain_pending(&ctx).unwrap() { + ops.extend(batch); + } + } + std::fs::write(&transcript, format!("{first}\n{last}\n")).unwrap(); + let update = claude_event( + &ctx.session_id, + "TranscriptUpdate", + 7000, + json!({"agent_id":"worker","agent_transcript_path":path}), + ); + ops.extend(translator.handle(&update, &ctx).unwrap()); + while let Some(batch) = translator.drain_pending(&ctx).unwrap() { + ops.extend(batch); + } + ops.extend(translator.handle(&update, &ctx).unwrap()); + while let Some(batch) = translator.drain_pending(&ctx).unwrap() { + ops.extend(batch); + } + assert_eq!( + ops.iter() + .filter(|op| matches!(op, SpanOp::Insert(row) if row.span_type == SpanType::Llm)) + .count(), + 2 + ); + let rows = reduce(ops); + let agent = rows + .values() + .find(|row| row.name == "subagent: reviewer") + .unwrap(); + let calls = rows + .values() + .filter(|row| { + row.span_type == SpanType::Llm && row.parent_span_ids.contains(&agent.span_id) + }) + .collect::>(); + assert_eq!(calls.len(), 2); + assert!(calls.iter().any(|row| row + .metadata + .as_ref() + .and_then(|m| m.get("request_id")) + .and_then(Value::as_str) + == Some("last"))); +} + #[test] fn claude_subagent_stop_recovers_handback_from_transcript_without_post_tool_hook() { let tmp = tempfile::tempdir().unwrap(); diff --git a/bt-daemon/tests/pipeline.rs b/bt-daemon/tests/pipeline.rs index 7361d113..84f6f231 100644 --- a/bt-daemon/tests/pipeline.rs +++ b/bt-daemon/tests/pipeline.rs @@ -2450,6 +2450,81 @@ async fn claude_late_response_survives_acknowledged_idle_replay_and_restart() { assert_claude_late_response(&recording); } +#[tokio::test] +async fn claude_subagent_late_append_is_captured_after_session_end() { + let tmp = tempfile::tempdir().unwrap(); + let socket = test_endpoint(tmp.path()); + let transcript = tmp.path().join("claude.jsonl"); + let child = tmp.path().join("agent-worker.jsonl"); + let recording = Arc::new(RouteRecordingSinkFactory::default()); + let handle = start_claude_recording_daemon( + tmp.path().join("data"), + socket.clone(), + recording.clone(), + 0, + ) + .await; + claude_stop_before_response(&socket, &transcript).await; + let mut start = claude_stop("late-claude", &transcript, 1_790_873_301_000); + start.event = "SubagentStart".into(); + start.payload["agent_id"] = serde_json::json!("worker"); + start.payload["agent_type"] = serde_json::json!("reviewer"); + forward_envelope(&start, &socket, &dummy_host(), false) + .await + .unwrap(); + let first = serde_json::json!({"type":"assistant","timestamp":"2026-10-01T16:48:22Z","message":{"id":"child-first","model":"test","content":[{"type":"text","text":"first"}]}}); + std::fs::write(&child, format!("{first}\n")).unwrap(); + let mut stop = start.clone(); + stop.event = "SubagentStop".into(); + stop.ts_ms += 1000; + stop.payload["agent_transcript_path"] = serde_json::json!(child); + forward_envelope(&stop, &socket, &dummy_host(), false) + .await + .unwrap(); + let mut end = claude_stop("late-claude", &transcript, 1_790_873_304_000); + end.event = "SessionEnd".into(); + forward_envelope(&end, &socket, &dummy_host(), false) + .await + .unwrap(); + assert!( + flush_session("late-claude", &socket, 5_000) + .await + .unwrap() + .flushed + ); + let last = serde_json::json!({"type":"assistant","timestamp":"2026-10-01T16:48:25Z","message":{"id":"child-last","model":"test","content":[{"type":"text","text":"last"}],"usage":{"input_tokens":3,"output_tokens":2}}}); + std::fs::write(&child, format!("{first}\n{last}\n")).unwrap(); + tokio::time::timeout(Duration::from_secs(5), async { + loop { + if claude_recorded_ops(&recording).iter().any(|op| matches!(op, SpanOp::Insert(row) if row.metadata.as_ref().and_then(|m| m.get("request_id")).and_then(|v| v.as_str()) == Some("child-last"))) { break; } + tokio::time::sleep(Duration::from_millis(25)).await; + } + }).await.expect("late child response must be delivered"); + shutdown(&socket).await; + handle.await.unwrap(); + let third = serde_json::json!({"type":"assistant","timestamp":"2026-10-01T16:48:26Z","message":{"id":"child-restart","model":"test","content":[{"type":"text","text":"after restart"}]}}); + std::fs::write(&child, format!("{first}\n{last}\n{third}\n")).unwrap(); + let restarted = start_claude_recording_daemon( + tmp.path().join("data"), + socket.clone(), + recording.clone(), + 0, + ) + .await; + tokio::time::timeout(Duration::from_secs(5), async { + loop { + if claude_recorded_ops(&recording).iter().any(|op| matches!(op, SpanOp::Insert(row) if row.metadata.as_ref().and_then(|m| m.get("request_id")).and_then(|v| v.as_str()) == Some("child-restart"))) { break; } + tokio::time::sleep(Duration::from_millis(25)).await; + } + }).await.expect("late child response must survive restart"); + shutdown(&socket).await; + restarted.await.unwrap(); + for request in ["child-first", "child-last", "child-restart"] { + let count = claude_recorded_ops(&recording).iter().filter(|op| matches!(op, SpanOp::Insert(row) if row.metadata.as_ref().and_then(|m| m.get("request_id")).and_then(|v| v.as_str()) == Some(request))).count(); + assert_eq!(count, 1, "{request} must be inserted once across restart"); + } +} + #[tokio::test] async fn claude_late_response_is_delivered_without_another_hook() { let tmp = tempfile::tempdir().unwrap();