Skip to main content

merry_runtime/subagent/
events.rs

1//! Parent-session event sink and persisted subagent record contracts.
2//!
3//! Bridges `SubagentManager` lifecycle transitions and usage rollups back into
4//! the parent session's durable journal and live broadcast stream without
5//! creating a circular dependency on `Runtime`.
6
7use super::manager::{
8    ManagedSubagent, SUBAGENT_EVENT_CHANNEL_CAPACITY, SubagentInspectSession, SubagentManager,
9    SubagentManagerState,
10};
11use super::protocol::{
12    SubagentResultView, SubagentStatusLabel, SubagentStatusView, SubagentWorkspaceMode,
13    SubagentWorktreeView,
14};
15use super::scope::{ChildWorkspaceFinalization, ChildWorkspaceLifecycle};
16use super::spec::SubagentTaskSpec;
17use crate::{
18    FileSessionStore, LoadedSession, Runtime, SessionTranscriptItem, TaskAnchor,
19    session::SessionState, trajectory::RuntimeObservability,
20};
21use merry_core::{
22    ErrorInfo, ModelUsage, RuntimeJournalEvent, RuntimeJournalPayload, SessionId, SubagentId,
23    SubagentStatus, SubagentTaskId,
24};
25use serde::{Deserialize, Serialize};
26use std::{
27    collections::{BTreeSet, VecDeque},
28    sync::Arc,
29    time::Duration,
30};
31use tokio::sync::{Mutex, broadcast};
32use tokio_util::sync::CancellationToken;
33
34/// Compact, durable record of one subagent persisted inside the parent's `journal.jsonl`.
35///
36/// Restored on parent session resume so TUI/CLI/SDK surfaces immediately display
37/// historical subagent cards and can lazily load or wake each child from
38/// `<sessions_dir>/<parent_id>/subagents/<agent_id>/journal.jsonl`.
39#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
40#[serde(deny_unknown_fields)]
41pub(crate) struct PersistedSubagentRecord {
42    pub(crate) agent_id: SubagentId,
43    pub(crate) task_id: SubagentTaskId,
44    pub(crate) task: String,
45    #[serde(default, skip_serializing_if = "Option::is_none")]
46    pub(crate) display_name: Option<String>,
47    #[serde(default, skip_serializing_if = "Option::is_none")]
48    pub(crate) role: Option<String>,
49    pub(crate) status: SubagentStatusLabel,
50    pub(crate) summary: String,
51    #[serde(default, skip_serializing_if = "Option::is_none")]
52    pub(crate) conclusion: Option<String>,
53    #[serde(default, skip_serializing_if = "Vec::is_empty")]
54    pub(crate) output_paths: Vec<String>,
55    #[serde(default, skip_serializing_if = "Vec::is_empty")]
56    pub(crate) changed_paths: Vec<String>,
57    #[serde(default, skip_serializing_if = "Option::is_none")]
58    pub(crate) diagnostic: Option<ErrorInfo>,
59    #[serde(default)]
60    pub(crate) turns_used: u32,
61    #[serde(default)]
62    pub(crate) tool_calls: u32,
63    #[serde(default)]
64    pub(crate) elapsed_ms: u64,
65    #[serde(default, skip_serializing_if = "Option::is_none")]
66    pub(crate) usage: Option<ModelUsage>,
67    #[serde(default, skip_serializing_if = "Option::is_none")]
68    pub(crate) worktree: Option<SubagentWorktreeView>,
69}
70
71impl PersistedSubagentRecord {
72    pub(crate) fn from_status_view(task: String, view: &SubagentStatusView) -> Self {
73        Self {
74            agent_id: view.agent_id.clone(),
75            task_id: view.task_id.clone(),
76            task,
77            display_name: view.display_name.clone(),
78            role: view.role.clone(),
79            status: view.status.clone(),
80            summary: view.summary.clone(),
81            conclusion: view.result.as_ref().map(|res| res.conclusion.clone()),
82            output_paths: view.output_paths.clone(),
83            changed_paths: view.changed_paths.clone(),
84            diagnostic: view.diagnostics.clone(),
85            turns_used: view.turns_used,
86            tool_calls: view.tool_calls,
87            elapsed_ms: view.elapsed_ms,
88            usage: view.usage,
89            worktree: view.worktree.clone(),
90        }
91    }
92}
93
94/// Converts internal runtime subagent status label into public [`SubagentStatus`].
95pub(crate) fn to_public_subagent_status(status: &SubagentStatusLabel) -> SubagentStatus {
96    match status {
97        SubagentStatusLabel::Queued => SubagentStatus::Queued,
98        SubagentStatusLabel::Running => SubagentStatus::Running,
99        SubagentStatusLabel::Completed => SubagentStatus::Completed,
100        SubagentStatusLabel::Failed => SubagentStatus::Failed,
101        SubagentStatusLabel::Cancelled => SubagentStatus::Cancelled,
102        SubagentStatusLabel::Blocked => SubagentStatus::Blocked,
103    }
104}
105
106/// Lightweight parent-owned event and persistence sink injected into [`super::SubagentManager`].
107#[derive(Clone)]
108pub(crate) struct SubagentEventSink {
109    session: Arc<Mutex<SessionState>>,
110    session_store: Option<FileSessionStore>,
111    trajectory: Arc<RuntimeObservability>,
112    event_tx: broadcast::Sender<RuntimeJournalEvent>,
113}
114
115impl SubagentEventSink {
116    pub(crate) fn new(
117        session: Arc<Mutex<SessionState>>,
118        session_store: Option<FileSessionStore>,
119        trajectory: Arc<RuntimeObservability>,
120        capacity: usize,
121    ) -> Self {
122        let (event_tx, _) = broadcast::channel(capacity.max(64));
123        Self {
124            session,
125            session_store,
126            trajectory,
127            event_tx,
128        }
129    }
130
131    /// Subscribes to live journal events emitted asynchronously by managed subagents.
132    pub(crate) fn subscribe(&self) -> broadcast::Receiver<RuntimeJournalEvent> {
133        self.event_tx.subscribe()
134    }
135
136    /// Appends one journal payload onto the parent session and broadcasts it live.
137    pub(crate) async fn emit_journal_payload(
138        &self,
139        payload: RuntimeJournalPayload,
140    ) -> RuntimeJournalEvent {
141        let event = {
142            let mut session = self.session.lock().await;
143            session.record_event(payload)
144        };
145        self.trajectory.observe_journal_event(&event);
146        let _ = self.event_tx.send(event.clone());
147        event
148    }
149
150    /// Folds incremental subagent token usage into the parent session's usage ledger
151    /// and broadcasts the updated `SessionUsageUpdated` event.
152    pub(crate) async fn record_subagent_usage(
153        &self,
154        delta: ModelUsage,
155    ) -> Option<RuntimeJournalEvent> {
156        if delta.input_tokens == 0 && delta.output_tokens == 0 && delta.total_tokens == 0 {
157            return None;
158        }
159        let recorded = {
160            let mut session = self.session.lock().await;
161            session.record_subagent_usage(delta)
162        };
163        match recorded {
164            Ok(event) => {
165                self.trajectory.observe_journal_event(&event);
166                let _ = self.event_tx.send(event.clone());
167                Some(event)
168            }
169            Err(diagnostic) => {
170                tracing::warn!(
171                    code = diagnostic.code(),
172                    message = diagnostic.message(),
173                    "failed to fold subagent usage into parent session"
174                );
175                None
176            }
177        }
178    }
179
180    /// Records or updates one persisted subagent snapshot in parent `SessionState`
181    /// and flushes a resume-safe savepoint when the parent has a `FileSessionStore`.
182    pub(crate) async fn upsert_persisted_subagent(&self, record: PersistedSubagentRecord) {
183        let prepared = {
184            let mut session = self.session.lock().await;
185            session.upsert_persisted_subagent(record);
186            self.session_store
187                .as_ref()
188                .map(|_| session.persistable_bundle_if_resume_safe())
189        };
190        let (Some(store), Some(Ok(Some(bundle)))) = (self.session_store.as_ref(), prepared) else {
191            return;
192        };
193        let cursor = bundle.cursor.clone();
194        if let Err(error) = store.write_bundle(bundle).await {
195            tracing::warn!(
196                error = %error,
197                "failed to flush parent session savepoint after subagent state update"
198            );
199            return;
200        }
201        self.session.lock().await.adopt_journal_cursor(cursor);
202    }
203}
204
205/// Computes the positive token usage delta between a previous cumulative child
206/// `ModelUsage` snapshot and a newer cumulative snapshot.
207pub(crate) fn usage_delta(previous: Option<ModelUsage>, current: ModelUsage) -> Option<ModelUsage> {
208    let Some(prev) = previous else {
209        return (current.input_tokens > 0 || current.output_tokens > 0 || current.total_tokens > 0)
210            .then_some(current);
211    };
212    let input_tokens = current.input_tokens.saturating_sub(prev.input_tokens);
213    let output_tokens = current.output_tokens.saturating_sub(prev.output_tokens);
214    let total_tokens = current.total_tokens.saturating_sub(prev.total_tokens);
215    let cached_input_tokens = match (current.cached_input_tokens, prev.cached_input_tokens) {
216        (Some(cur), Some(old)) => Some(cur.saturating_sub(old)),
217        (Some(cur), None) => Some(cur),
218        (None, _) => None,
219    };
220    let reasoning_output_tokens = match (
221        current.reasoning_output_tokens,
222        prev.reasoning_output_tokens,
223    ) {
224        (Some(cur), Some(old)) => Some(cur.saturating_sub(old)),
225        (Some(cur), None) => Some(cur),
226        (None, _) => None,
227    };
228    if input_tokens == 0 && output_tokens == 0 && total_tokens == 0 {
229        return None;
230    }
231    Some(ModelUsage::with_details(
232        input_tokens,
233        cached_input_tokens,
234        output_tokens,
235        reasoning_output_tokens,
236        total_tokens,
237    ))
238}
239
240/// Persists the final subagent snapshot into the parent session and emits the
241/// corresponding terminal `RuntimeJournalPayload::Subagent*` event.
242pub(crate) async fn emit_terminal_event_and_persist(
243    sink: Option<&SubagentEventSink>,
244    task: String,
245    view: &SubagentStatusView,
246) {
247    let Some(sink) = sink else {
248        return;
249    };
250    let payload = match view.status {
251        SubagentStatusLabel::Completed => RuntimeJournalPayload::SubagentCompleted {
252            agent_id: view.agent_id.clone(),
253            task_id: view.task_id.clone(),
254            summary: view.summary.clone(),
255            output_paths: view.output_paths.clone(),
256            changed_paths: view.changed_paths.clone(),
257            usage: view.usage,
258        },
259        SubagentStatusLabel::Failed => RuntimeJournalPayload::SubagentFailed {
260            agent_id: view.agent_id.clone(),
261            task_id: view.task_id.clone(),
262            diagnostic: view.diagnostics.clone().unwrap_or_else(|| {
263                ErrorInfo::new("subagent_failed", &view.summary)
264                    .expect("static diagnostic code is valid")
265            }),
266        },
267        SubagentStatusLabel::Cancelled => RuntimeJournalPayload::SubagentCancelled {
268            agent_id: view.agent_id.clone(),
269            task_id: view.task_id.clone(),
270            diagnostic: view.diagnostics.clone().unwrap_or_else(|| {
271                ErrorInfo::new("subagent_cancelled", &view.summary)
272                    .expect("static diagnostic code is valid")
273            }),
274        },
275        SubagentStatusLabel::Blocked => RuntimeJournalPayload::SubagentStatusChanged {
276            agent_id: view.agent_id.clone(),
277            task_id: view.task_id.clone(),
278            status: SubagentStatus::Blocked,
279        },
280        SubagentStatusLabel::Queued | SubagentStatusLabel::Running => {
281            RuntimeJournalPayload::SubagentStatusChanged {
282                agent_id: view.agent_id.clone(),
283                task_id: view.task_id.clone(),
284                status: to_public_subagent_status(&view.status),
285            }
286        }
287    };
288    sink.emit_journal_payload(payload).await;
289    sink.upsert_persisted_subagent(PersistedSubagentRecord::from_status_view(task, view))
290        .await;
291}
292
293/// Timeout for flushing a child's durable session journal during teardown.
294const CHILD_FLUSH_TIMEOUT: Duration = Duration::from_secs(5);
295/// Timeout for folding subagent token usage into the parent session during teardown.
296const CHILD_USAGE_ROLLUP_TIMEOUT: Duration = Duration::from_secs(2);
297/// Timeout for collecting isolated worktree diffs and running fail-toward-keep cleanup.
298const CHILD_WORKSPACE_FINALIZE_TIMEOUT: Duration = Duration::from_secs(10);
299
300/// Runs an isolated child workspace finalization hook on a blocking worker thread
301/// with a bounded timeout, failing toward keeping the workspace on timeout/panic.
302pub(super) async fn finalize_child_workspace(
303    hook: Option<Arc<dyn ChildWorkspaceLifecycle>>,
304    allow_cleanup: bool,
305) -> Option<ChildWorkspaceFinalization> {
306    let hook = hook?;
307    let task = tokio::task::spawn_blocking(move || hook.finalize(allow_cleanup));
308    match tokio::time::timeout(CHILD_WORKSPACE_FINALIZE_TIMEOUT, task).await {
309        Ok(Ok(finalization)) => Some(finalization),
310        Ok(Err(error)) => {
311            tracing::warn!(
312                error = %error,
313                "child workspace finalization task panicked; failing toward keeping workspace"
314            );
315            None
316        }
317        Err(_) => {
318            tracing::warn!(
319                timeout_secs = CHILD_WORKSPACE_FINALIZE_TIMEOUT.as_secs(),
320                "child workspace finalization timed out; failing toward keeping workspace"
321            );
322            None
323        }
324    }
325}
326
327/// Merges a finalized isolated workspace result into one [`ManagedSubagent`] in place.
328pub(super) fn apply_workspace_finalization(
329    agent: &mut ManagedSubagent,
330    finalization: Option<ChildWorkspaceFinalization>,
331) {
332    let Some(finalization) = finalization else {
333        return;
334    };
335    if !finalization.changed_paths.is_empty() {
336        let mut merged = agent
337            .changed_paths
338            .iter()
339            .cloned()
340            .collect::<BTreeSet<String>>();
341        merged.extend(finalization.changed_paths);
342        agent.changed_paths = merged.into_iter().collect();
343    }
344    let removed = finalization
345        .worktree
346        .as_ref()
347        .is_some_and(|worktree| !worktree.retained);
348    if finalization.worktree.is_some() {
349        agent.worktree = finalization.worktree;
350    }
351    if removed {
352        // The isolated worktree directory was deleted after zero net changes;
353        // clear the cached runtime so a future wake creates a fresh worktree
354        // instead of executing tools inside a deleted directory.
355        agent.runtime = None;
356        agent.workspace_lifecycle = None;
357    }
358}
359
360/// Finalizes one agent's isolated workspace (if any) without holding the manager
361/// state lock across blocking git operations, then merges discovered paths and
362/// updated worktree metadata back into manager state.
363pub(super) async fn finalize_agent_workspace_into_state(
364    state: &Mutex<SubagentManagerState>,
365    agent_id: &SubagentId,
366    allow_cleanup: bool,
367) {
368    let hook = {
369        let guard = state.lock().await;
370        guard
371            .agents
372            .get(agent_id)
373            .and_then(|agent| agent.workspace_lifecycle.clone())
374    };
375    let finalization = finalize_child_workspace(hook, allow_cleanup).await;
376    let mut guard = state.lock().await;
377    if let Some(agent) = guard.agents.get_mut(agent_id) {
378        apply_workspace_finalization(agent, finalization);
379    }
380}
381
382/// Executes the strict 4-step child teardown sequence:
383/// 1. Flush child durable session store (bounded timeout)
384/// 2. Reconcile any remaining unreported token usage into parent (bounded timeout + fallback)
385/// 3. Clean up any surviving background processes owned by the child
386/// 4. Persist final parent subagent snapshot and emit parent terminal journal event
387pub(crate) async fn teardown_child_runtime(
388    sink: Option<&SubagentEventSink>,
389    child_runtime: &Runtime,
390    reported_usage: Option<ModelUsage>,
391    final_usage: Option<ModelUsage>,
392    task: String,
393    view: &SubagentStatusView,
394) {
395    // Step 1: Flush child journal so immediate wake/inspect sees all turns on disk.
396    match tokio::time::timeout(
397        CHILD_FLUSH_TIMEOUT,
398        child_runtime.flush_attached_session_store(),
399    )
400    .await
401    {
402        Ok(Ok(())) => {}
403        Ok(Err(error)) => {
404            tracing::warn!(
405                subagent_id = %view.agent_id,
406                error = %error,
407                "failed to flush child session store during teardown"
408            );
409        }
410        Err(_) => {
411            tracing::warn!(
412                subagent_id = %view.agent_id,
413                timeout_secs = CHILD_FLUSH_TIMEOUT.as_secs(),
414                "timed out flushing child session store during teardown"
415            );
416        }
417    }
418
419    // Step 2: Reconcile any un-reported usage delta with bounded timeout + fallback.
420    if let (Some(sink), Some(final_total)) = (sink, final_usage)
421        && let Some(delta) = usage_delta(reported_usage, final_total)
422        && tokio::time::timeout(
423            CHILD_USAGE_ROLLUP_TIMEOUT,
424            sink.record_subagent_usage(delta),
425        )
426        .await
427        .is_err()
428    {
429        tracing::warn!(
430            subagent_id = %view.agent_id,
431            timeout_secs = CHILD_USAGE_ROLLUP_TIMEOUT.as_secs(),
432            "timed out folding subagent token usage into parent session; continuing teardown"
433        );
434    }
435
436    // Step 3: Stop any surviving background processes spawned by the child.
437    child_runtime.shutdown_background_processes();
438
439    // Step 4: Persist parent subagent record and emit terminal parent journal event.
440    emit_terminal_event_and_persist(sink, task, view).await;
441}
442
443/// Folds one incremental child usage delta into the parent session with bounded timeout.
444pub(crate) async fn fold_incremental_child_usage(
445    sink: Option<&SubagentEventSink>,
446    reported_usage: &mut Option<ModelUsage>,
447    current_total: ModelUsage,
448) {
449    let Some(delta) = usage_delta(*reported_usage, current_total) else {
450        return;
451    };
452    *reported_usage = Some(current_total);
453    if let Some(sink) = sink
454        && tokio::time::timeout(
455            CHILD_USAGE_ROLLUP_TIMEOUT,
456            sink.record_subagent_usage(delta),
457        )
458        .await
459        .is_err()
460    {
461        tracing::warn!(
462            timeout_secs = CHILD_USAGE_ROLLUP_TIMEOUT.as_secs(),
463            "timed out recording incremental subagent token usage"
464        );
465    }
466}
467
468/// Returns the deterministic child [`SessionId`] used to store the child's
469/// journal at `<sessions_dir>/<parent_id>/subagents/<agent_id>/journal.jsonl`.
470pub(crate) fn child_session_id_for_agent(agent_id: &SubagentId) -> SessionId {
471    SessionId::new(agent_id.as_str()).expect("valid SubagentId is always a valid SessionId")
472}
473
474impl SubagentManager {
475    /// Attaches the parent-session event/persistence sink so subagent lifecycle
476    /// transitions and usage rollups enter the parent's durable journal and live streams.
477    pub(crate) fn attach_event_sink(&self, sink: SubagentEventSink) {
478        *self
479            .event_sink
480            .lock()
481            .expect("subagent event sink mutex is not poisoned") = Some(sink);
482    }
483
484    pub(super) fn attached_event_sink(&self) -> Option<SubagentEventSink> {
485        self.event_sink
486            .lock()
487            .expect("subagent event sink mutex is not poisoned")
488            .clone()
489    }
490
491    /// Attaches the child-scoped session store (`<sessions_dir>/<parent_id>/subagents`).
492    pub(crate) fn attach_child_session_store(&self, store: FileSessionStore) {
493        *self
494            .child_session_store
495            .lock()
496            .expect("subagent child session store mutex is not poisoned") = Some(store);
497    }
498
499    pub(super) fn attached_child_session_store(&self) -> Option<FileSessionStore> {
500        self.child_session_store
501            .lock()
502            .expect("subagent child session store mutex is not poisoned")
503            .clone()
504    }
505
506    /// Hydrates historical subagent entries persisted in the parent's `journal.jsonl`
507    /// when resuming a session, advancing `next_id` past all restored numeric suffixes.
508    pub(crate) fn hydrate_persisted(&self, records: Vec<PersistedSubagentRecord>) {
509        if records.is_empty() {
510            return;
511        }
512        let mut max_numeric_id: u64 = 0;
513        let Ok(mut state) = self.state.try_lock() else {
514            return;
515        };
516        for record in records {
517            if let Some(num) = record
518                .agent_id
519                .as_str()
520                .strip_prefix("agent-")
521                .or_else(|| record.agent_id.as_str().strip_prefix("subagent-"))
522                .and_then(|suffix| suffix.parse::<u64>().ok())
523            {
524                max_numeric_id = max_numeric_id.max(num);
525            }
526            if state.agents.contains_key(&record.agent_id) {
527                continue;
528            }
529            let (status, summary, diagnostics) = if record.status.is_terminal() {
530                (record.status, record.summary, record.diagnostic)
531            } else {
532                (
533                    SubagentStatusLabel::Cancelled,
534                    "interrupted by previous session exit".to_owned(),
535                    Some(
536                        ErrorInfo::new(
537                            "subagent_interrupted",
538                            "subagent was still active when the previous session exited; send a message to resume",
539                        )
540                        .expect("static diagnostic code is valid"),
541                    ),
542                )
543            };
544            let task_text = if record.task.trim().is_empty() {
545                summary.clone()
546            } else {
547                record.task
548            };
549            let mut task_spec =
550                SubagentTaskSpec::new(task_text.clone(), self.max_model_turns().max(1))
551                    .unwrap_or_else(|_| {
552                        SubagentTaskSpec::new("resumed subagent task", 1)
553                            .expect("static task is valid")
554                    });
555            if let Some(name) = record.display_name {
556                task_spec = task_spec.with_display_name(Some(name));
557            }
558            if let Some(role) = record.role
559                && let Ok(updated) = task_spec.clone().with_role(Some(role))
560            {
561                task_spec = updated;
562            }
563            if record.worktree.is_some() {
564                task_spec = task_spec.with_workspace_mode(SubagentWorkspaceMode::Worktree);
565            }
566            let task_anchor = TaskAnchor::new(&task_text)
567                .unwrap_or_else(|_| TaskAnchor::new("resumed subagent task").expect("valid"));
568            let result = record
569                .conclusion
570                .and_then(SubagentResultView::from_conclusion);
571            let (event_tx, _) = broadcast::channel(SUBAGENT_EVENT_CHANNEL_CAPACITY);
572            state.agents.insert(
573                record.agent_id.clone(),
574                ManagedSubagent {
575                    batch_id: 0,
576                    agent_id: record.agent_id,
577                    task_id: record.task_id,
578                    task: task_spec,
579                    task_anchor,
580                    status,
581                    summary,
582                    result,
583                    output_paths: record.output_paths,
584                    changed_paths: record.changed_paths,
585                    diagnostics,
586                    cancellation_token: CancellationToken::new(),
587                    completion_notification_acknowledged: true,
588                    runtime: None,
589                    generation_config: None,
590                    event_tx,
591                    pending_follow_ups: VecDeque::new(),
592                    resume_turn_override: None,
593                    started_at: None,
594                    turns_used: record.turns_used,
595                    tool_calls: record.tool_calls,
596                    elapsed_ms: record.elapsed_ms,
597                    usage: record.usage,
598                    raw_output_bytes: 0,
599                    workspace_lifecycle: None,
600                    worktree: record.worktree,
601                },
602            );
603        }
604        if max_numeric_id > 0 {
605            self.next_id.fetch_max(
606                max_numeric_id.saturating_add(1),
607                std::sync::atomic::Ordering::AcqRel,
608            );
609        }
610        self.has_agents.store(
611            !state.agents.is_empty(),
612            std::sync::atomic::Ordering::Release,
613        );
614    }
615
616    /// Returns a lazy transcript snapshot and live event subscription for one subagent.
617    pub async fn inspect(&self, agent_id: &SubagentId) -> Option<SubagentInspectSession> {
618        let (status, task, runtime, events) = {
619            let state = self.state.lock().await;
620            let agent = state.agents.get(agent_id)?;
621            (
622                agent.status_view(),
623                agent.task.task().to_owned(),
624                agent.runtime.clone(),
625                agent.event_tx.subscribe(),
626            )
627        };
628        let transcript = match runtime {
629            Some(runtime) => runtime.session_transcript().await.unwrap_or_default(),
630            None => self.lazy_load_child_transcript(agent_id).await,
631        };
632        Some(SubagentInspectSession {
633            status,
634            task,
635            transcript,
636            events,
637        })
638    }
639
640    /// Lazily loads a persisted child's transcript from `<sessions_dir>/<parent_id>/subagents/<agent_id>/journal.jsonl`.
641    pub(super) async fn lazy_load_child_transcript(
642        &self,
643        agent_id: &SubagentId,
644    ) -> Vec<SessionTranscriptItem> {
645        let Some(store) = self.attached_child_session_store() else {
646            return Vec::new();
647        };
648        let session_id = child_session_id_for_agent(agent_id);
649        match LoadedSession::load(&store, &session_id).await {
650            Ok(loaded) => loaded.transcript_items(),
651            Err(_) => Vec::new(),
652        }
653    }
654
655    /// Cancels all live children owned by this manager and awaits their task
656    /// handles up to a bounded shutdown timeout.
657    pub async fn shutdown(&self) {
658        self.session_token.cancel();
659        let handles = {
660            let mut state = self.state.lock().await;
661            for agent in state.agents.values_mut() {
662                if !agent.status.is_terminal() {
663                    agent.cancellation_token.cancel();
664                    agent.status = SubagentStatusLabel::Cancelled;
665                    agent.summary = "child cancelled during parent shutdown".to_owned();
666                    agent.diagnostics = Some(super::manager_helpers::error_info(
667                        "subagent_cancelled",
668                        "child cancelled during parent session shutdown",
669                    ));
670                }
671            }
672            std::mem::take(&mut state.handles)
673                .into_values()
674                .collect::<Vec<_>>()
675        };
676        self.notify.notify_waiters();
677        self.completion_notify.notify_waiters();
678
679        const SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(5);
680        for mut handle in handles {
681            if tokio::time::timeout(SHUTDOWN_TIMEOUT, &mut handle)
682                .await
683                .is_err()
684            {
685                handle.abort();
686            }
687        }
688    }
689}