brokk-mj-transcript 2.75.0

Transcript projection and presentation for Mjolnir
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
//! Controller-owned projection of the durable ACP relay stream.

mod live;
mod materialize;
pub use live::*;
mod observation;
mod session_update;
mod terminals;
pub use materialize::*;
pub use observation::*;
pub use session_update::configuration_values;
use session_update::*;
use terminals::*;

mod api_events;

use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::sync::Arc;

use agent_client_protocol::schema::MaybeUndefined;
use agent_client_protocol::v1::schema::{
    ContentBlock, ContentChunk, Plan, PlanEntry, PlanEntryPriority, PlanEntryStatus, SessionUpdate,
    TextContent, ToolCall, ToolCallContent, ToolCallStatus, ToolCallUpdateFields, ToolKind,
};
use anyhow::{Context, Result, bail};
use serde::Deserialize;
use serde_json::Value;
use sha2::{Digest, Sha256};

use crate::transcript::{ChatEntry, ChatRole, PlanStatus, ToolStatus, tool_call_presentation};
use mj_core::archive::{
    CanonicalExecutionState, CanonicalQueuedCommandKind, CanonicalQueuedPrompt,
    CanonicalSessionSnapshot, CanonicalSessionState, CanonicalTerminalOutput,
    CanonicalTranscriptBody, CanonicalTranscriptItem,
};
use mj_core::relay::{
    RELAY_EVENT_GENESIS_DIGEST, RelayCommand, RelayCommandKind, RelayEvent, RelayObservation,
    SequencedEvent, WorkerEvent, WorkerPhase, validate_relay_event,
};
use mj_core::state::{
    MaterializedExecutionState, MaterializedQueuedPrompt, MaterializedSession, MaterializedTurn,
    MaterializedTurnOutcome, QueuedCommandKind, TerminalOutputRecord, TranscriptBody,
    TranscriptItem, TurnOutcomeKind, config_command_text, normalize_session_title,
    provisional_session_title,
};
use mj_core::storage::{MaterializedSessionMutation, ProjectionIntegrityError, TranscriptMutation};
use mj_core::transcript::{coalesce_content_chunks, push_content_chunk};

#[derive(Debug, Clone, PartialEq)]
pub struct ProjectedRelayEvent {
    pub mutation: MaterializedSessionMutation,
}

/// Ephemeral lookup state for projecting a relay page. It is deliberately not
/// part of the serialized session: the durable transcript remains canonical,
/// while catch-up avoids rediscovering keyed items and open streams with a
/// full transcript walk for every event.
#[derive(Debug, Clone)]
pub struct ProjectionIndex {
    transcript: HashMap<String, Arc<TranscriptItem>>,
    transcript_positions: HashMap<String, usize>,
    open_agent_streams: BTreeSet<(u64, String)>,
    open_thought_streams: BTreeSet<(u64, String)>,
    turn_boundaries: BTreeMap<u64, String>,
    // Position keys let a boundary name its owning turn interval. The actor
    // window reloads unsettled items together with their owning turn ranges.
    open_foreground_tools: BTreeSet<(u64, String)>,
    terminal_referrers: HashMap<String, BTreeSet<String>>,
}

pub struct HistoricalReferences {
    pub ids: Vec<String>,
    pub terminals: BTreeSet<String>,
}

/// Explicit references that may address rows older than a live window. Keep
/// identity interpretation beside the projector that consumes these events.
pub fn historical_references(events: &[RelayEvent]) -> Result<HistoricalReferences> {
    let mut ids = BTreeSet::new();
    let mut terminals = BTreeSet::new();
    for event in events {
        match &event.observation {
            RelayObservation::SessionUpdate { update } => {
                let content = match update.as_ref() {
                    SessionUpdate::ToolCall(call) => {
                        ids.insert(crate::tool_item_id(&call.tool_call_id));
                        call.content.as_slice()
                    }
                    SessionUpdate::ToolCallUpdate(update) => {
                        ids.insert(crate::tool_item_id(&update.tool_call_id));
                        update.fields.content.as_deref().unwrap_or_default()
                    }
                    SessionUpdate::AgentMessageChunk(chunk) => {
                        if let Some(id) = &chunk.message_id {
                            ids.insert(format!("agent:{id}"));
                        }
                        &[]
                    }
                    SessionUpdate::AgentThoughtChunk(chunk) => {
                        if let Some(id) = &chunk.message_id {
                            ids.insert(format!("thought:{id}"));
                        }
                        &[]
                    }
                    _ => &[],
                };
                for block in content {
                    if let ToolCallContent::Terminal(terminal) = block {
                        terminals.insert(terminal.terminal_id.0.to_string());
                    }
                }
            }
            RelayObservation::TerminalOutput { terminal_id, .. } => {
                terminals.insert(terminal_id.clone());
            }
            RelayObservation::CommandStarted { command_id, .. }
            | RelayObservation::CommandCompleted { command_id, .. }
            | RelayObservation::CommandRejected { command_id, .. }
            | RelayObservation::CommandInterrupted { command_id, .. }
            | RelayObservation::UserShellOutput { command_id, .. } => {
                ids.insert(user_shell_item_id(command_id));
                ids.insert(format!("user:{command_id}"));
            }
            RelayObservation::Notice { .. } => {
                if let Some(id) = &event.command_id {
                    ids.insert(format!("system:notice:{id}"));
                }
            }
            RelayObservation::MailboxEventsDelivered {
                event_keys,
                events,
                steering,
                ..
            } => {
                ids.extend(
                    event_keys
                        .iter()
                        .chain(events.iter().map(|event| &event.key))
                        .map(|key| mj_core::transcript::message_item_id(key)),
                );
                ids.extend(observation::external_events_item_id(events));
                if let Some(steering) = steering {
                    ids.insert(format!("user:{}", steering.queued_prompt_id));
                    ids.insert(format!("user:{}", steering.command_id));
                }
            }
            RelayObservation::CommandQueued {
                command: RelayCommand::MailboxWake { events },
                ..
            } => {
                ids.extend(
                    events
                        .iter()
                        .map(|event| mj_core::transcript::message_item_id(&event.key)),
                );
                ids.extend(observation::external_events_item_id(events));
            }
            _ => {}
        }
    }
    for terminal in &terminals {
        ids.insert(terminal_item_id(terminal));
        ids.insert(fallback_terminal_tool_item_id(terminal));
    }
    Ok(HistoricalReferences {
        ids: ids.into_iter().collect(),
        terminals,
    })
}

impl ProjectionIndex {
    pub fn new(current: &MaterializedSession) -> Self {
        let mut index = Self {
            transcript: HashMap::with_capacity(current.transcript.len()),
            transcript_positions: HashMap::with_capacity(current.transcript.len()),
            open_agent_streams: BTreeSet::new(),
            open_thought_streams: BTreeSet::new(),
            turn_boundaries: BTreeMap::new(),
            open_foreground_tools: BTreeSet::new(),
            terminal_referrers: HashMap::new(),
        };
        for (position, item) in current.transcript.iter().enumerate() {
            index.insert_at(item.clone(), position);
        }
        index
    }

    fn get(&self, stable_id: &str) -> Option<&Arc<TranscriptItem>> {
        self.transcript.get(stable_id)
    }

    fn position(&self, stable_id: &str) -> Option<usize> {
        self.transcript_positions.get(stable_id).copied()
    }

    fn insert(&mut self, item: Arc<TranscriptItem>) {
        let position = self
            .remove(&item.stable_id)
            .unwrap_or(self.transcript.len());
        self.insert_at(item, position);
    }

    fn insert_at(&mut self, item: Arc<TranscriptItem>, position: usize) {
        let stream = (item.position, item.stable_id.clone());
        if item.is_turn_start()
            || item
                .stable_id
                .starts_with(crate::transcript::SESSION_RESTART_ITEM_PREFIX)
            || item
                .stable_id
                .starts_with(mj_core::archive::CONTEXT_BOUNDARY_PREFIX)
        {
            self.turn_boundaries
                .insert(item.position, item.stable_id.clone());
        }
        match &item.body {
            TranscriptBody::Agent {
                streaming: true, ..
            } => {
                self.open_agent_streams.insert(stream);
            }
            TranscriptBody::Thought {
                streaming: true, ..
            } => {
                self.open_thought_streams.insert(stream);
            }
            TranscriptBody::Tool {
                call,
                terminal_refs,
                ..
            } => {
                // A tool that hands work to a terminal may outlive the turn
                // that launched it. Its terminal result owns completion; a
                // turn boundary must not turn the still-running tool into a
                // failed foreground call.
                if !call.is_fallback()
                    && matches!(
                        call.raw_status().unwrap_or("pending"),
                        "pending" | "in_progress"
                    )
                    && call.terminal_ids().is_empty()
                {
                    self.open_foreground_tools.insert(stream);
                }
                let mut terminal_ids = call.terminal_ids().to_vec();
                terminal_ids.extend(terminal_refs.iter().cloned());
                for terminal_id in terminal_ids {
                    self.terminal_referrers
                        .entry(terminal_id)
                        .or_default()
                        .insert(item.stable_id.clone());
                }
            }
            _ => {}
        }
        self.transcript_positions
            .insert(item.stable_id.clone(), position);
        self.transcript.insert(item.stable_id.clone(), item);
    }

    fn remove(&mut self, stable_id: &str) -> Option<usize> {
        let item = self.transcript.remove(stable_id)?;
        let position = self.transcript_positions.remove(stable_id);
        debug_assert!(position.is_some());
        let stream = (item.position, item.stable_id.clone());
        self.open_agent_streams.remove(&stream);
        self.open_thought_streams.remove(&stream);
        self.open_foreground_tools.remove(&stream);
        if self
            .turn_boundaries
            .get(&item.position)
            .is_some_and(|id| id == stable_id)
        {
            self.turn_boundaries.remove(&item.position);
        }
        if let TranscriptBody::Tool {
            call,
            terminal_refs,
            ..
        } = &item.body
        {
            let mut terminal_ids = call.terminal_ids().to_vec();
            terminal_ids.extend(terminal_refs.iter().cloned());
            for terminal_id in terminal_ids {
                if let Some(referrers) = self.terminal_referrers.get_mut(&terminal_id) {
                    referrers.remove(stable_id);
                    if referrers.is_empty() {
                        self.terminal_referrers.remove(&terminal_id);
                    }
                }
            }
        }
        position
    }

    fn reindex_after_removal(&mut self, transcript: &[Arc<TranscriptItem>], removed: usize) {
        for (position, item) in transcript.iter().enumerate().skip(removed) {
            self.transcript_positions
                .insert(item.stable_id.clone(), position);
        }
    }

    fn latest_open_stream(&self, agent: bool) -> Option<&Arc<TranscriptItem>> {
        let streams = if agent {
            &self.open_agent_streams
        } else {
            &self.open_thought_streams
        };
        streams
            .last()
            .and_then(|(_, stable_id)| self.transcript.get(stable_id))
    }

    fn open_streams(&self, agent: bool) -> impl Iterator<Item = &Arc<TranscriptItem>> {
        let streams = if agent {
            &self.open_agent_streams
        } else {
            &self.open_thought_streams
        };
        streams
            .iter()
            .filter_map(|(_, stable_id)| self.transcript.get(stable_id))
    }

    fn open_tools_in_turn(
        &self,
        start: u64,
        end: u64,
    ) -> impl Iterator<Item = &Arc<TranscriptItem>> {
        self.open_foreground_tools
            .range((start, String::new())..(end, String::new()))
            .filter_map(|(_, id)| self.get(id))
    }

    fn prompt_start(&self, turn: &MaterializedTurn) -> u64 {
        turn.steered_into
            .as_ref()
            .and_then(|id| self.get(&format!("user:{id}")))
            .map_or(turn.turn_start_position, |item| item.position)
    }

    fn running_turn_start(&self, current: &MaterializedSession) -> Option<u64> {
        if let Some(turn) = &current.active_turn {
            return Some(self.prompt_start(turn));
        }
        let MaterializedExecutionState::Running { started_at_ms } = current.execution else {
            return None;
        };
        let (&start, id) = self.turn_boundaries.last_key_value()?;
        // A native goal can continue after its prompt outcome. The original
        // running clock still identifies that prompt's start.
        if let Some(outcome) = &current.last_turn_outcome
            && outcome.turn_start_position == Some(start)
        {
            return self
                .get(&format!("user:{}", outcome.command_id))
                .or_else(|| {
                    self.get(&format!(
                        "{}{id}",
                        crate::transcript::HARNESS_TURN_ITEM_PREFIX,
                        id = outcome.command_id
                    ))
                })
                .filter(|item| item.created_at_ms == started_at_ms)
                .map(|item| item.position);
        }
        is_open_autonomous_turn(current, start, id)
            .then(|| self.adopted_autonomous_start(current, start))
    }

    fn open_autonomous_turn_before(&self, current: &MaterializedSession, end: u64) -> Option<u64> {
        self.turn_boundaries
            .range(..end)
            .rev()
            .take_while(|(_, id)| self.get(id).is_some_and(|item| item.is_turn_start()))
            .find_map(|(&start, id)| is_open_autonomous_turn(current, start, id).then_some(start))
    }

    fn adopted_autonomous_start(&self, current: &MaterializedSession, turn_start: u64) -> u64 {
        let Some((&previous, id)) = self.turn_boundaries.range(..turn_start).next_back() else {
            return 0;
        };
        if self.get(id).is_some_and(|item| !item.is_turn_start()) {
            return previous;
        }
        // A native tool can be announced before its harness turn marker.
        // A previous turn's completion bounds which earlier calls it adopted.
        current
            .last_turn_outcome
            .as_ref()
            .map(|turn| turn.completed_ordinal)
            .filter(|completed| (previous..turn_start).contains(completed))
            .map_or(turn_start, |completed| completed.saturating_add(1))
    }

    pub fn terminal_referrers(
        &self,
        terminal_id: &str,
    ) -> impl Iterator<Item = &Arc<TranscriptItem>> {
        self.terminal_referrers
            .get(terminal_id)
            .into_iter()
            .flatten()
            .filter_map(|stable_id| self.transcript.get(stable_id))
    }
}

fn is_open_autonomous_turn(current: &MaterializedSession, start: u64, id: &str) -> bool {
    id.strip_prefix(crate::transcript::HARNESS_TURN_ITEM_PREFIX)
        .and_then(|ordinal| ordinal.parse::<u64>().ok())
        == Some(start)
        && !current.last_turn_outcome.as_ref().is_some_and(|turn| {
            turn.turn_start_position.is_some() && turn.completed_ordinal > start
        })
}

fn tool_status_is_open(status: ToolCallStatus) -> bool {
    matches!(status, ToolCallStatus::Pending | ToolCallStatus::InProgress)
}

/// Derive the minimal mutation for exactly the next relay event. This clones
/// only logical items touched by the event; the actor-owned transcript is not
/// copied.
pub fn project_relay_event(
    current: &MaterializedSession,
    event: &RelayEvent,
) -> Result<ProjectedRelayEvent> {
    let index = ProjectionIndex::new(current);
    project_relay_event_indexed(current, &index, event)
}

pub fn project_relay_event_indexed(
    current: &MaterializedSession,
    index: &ProjectionIndex,
    event: &RelayEvent,
) -> Result<ProjectedRelayEvent> {
    validate_relay_event(
        current.applied_event_ordinal,
        &current.applied_event_digest,
        event,
    )?;

    let mut mutation = MaterializedSessionMutation {
        last_activity_at_ms: Some(event.recorded_at_ms),
        ..MaterializedSessionMutation::default()
    };
    project_observation(current, index, event, &mut mutation)?;
    mutation.api_events = api_events::derive(current, event, &mutation);
    Ok(ProjectedRelayEvent { mutation })
}

/// Apply a mutation to the actor's sole in-memory projection after the same
/// mutation and frontier have committed atomically in SQLite. The mutation is
/// consumed so its committed values move into the projection instead of being
/// copied a second time.
pub fn apply_committed_projection_event(
    current: &mut MaterializedSession,
    event: &RelayEvent,
    mutation: MaterializedSessionMutation,
) -> Result<()> {
    apply_committed_projection_event_inner(current, event, mutation, None)
}

pub fn apply_committed_projection_event_indexed(
    current: &mut MaterializedSession,
    index: &mut ProjectionIndex,
    event: &RelayEvent,
    mutation: MaterializedSessionMutation,
) -> Result<()> {
    apply_committed_projection_event_inner(current, event, mutation, Some(index))
}

fn apply_committed_projection_event_inner(
    current: &mut MaterializedSession,
    event: &RelayEvent,
    mutation: MaterializedSessionMutation,
    mut index: Option<&mut ProjectionIndex>,
) -> Result<()> {
    validate_relay_event(
        current.applied_event_ordinal,
        &current.applied_event_digest,
        event,
    )?;
    if let Some(execution) = mutation.execution {
        current.execution = execution;
    }
    if let Some(title) = mutation.session_title {
        current.session_title = title;
    }
    if let Some(configuration) = mutation.configuration {
        current.configuration = configuration;
    }
    for item_mutation in mutation.transcript {
        match item_mutation {
            TranscriptMutation::Upsert(item) => {
                item.validate(event.ordinal)?;
                let existing_position = index
                    .as_deref()
                    .and_then(|index| index.position(&item.stable_id));
                let existing = if let Some(position) = existing_position {
                    Some(current.transcript.get_mut(position).with_context(|| {
                        format!(
                            "transcript index position {position} for {:?} is out of bounds",
                            item.stable_id
                        )
                    })?)
                } else if index.is_none() {
                    current
                        .transcript
                        .iter_mut()
                        .find(|existing| existing.stable_id == item.stable_id)
                } else {
                    None
                };
                if let Some(existing) = existing {
                    if existing.stable_id != item.stable_id {
                        return Err(ProjectionIntegrityError(format!(
                            "transcript index for {:?} points to {:?}",
                            item.stable_id, existing.stable_id
                        ))
                        .into());
                    }
                    if existing.position != item.position
                        || existing.created_at_ms != item.created_at_ms
                    {
                        return Err(ProjectionIntegrityError(format!(
                            "transcript item {:?} changed immutable identity fields",
                            item.stable_id
                        ))
                        .into());
                    }
                    if item.last_changed_at_ms < existing.last_changed_at_ms {
                        return Err(ProjectionIntegrityError(format!(
                            "transcript item {:?} moved its changed timestamp backwards",
                            item.stable_id
                        ))
                        .into());
                    }
                    if existing
                        .latest_content_event_ordinal
                        .is_some_and(|existing| {
                            item.latest_content_event_ordinal
                                .is_none_or(|next| next < existing)
                        })
                    {
                        return Err(ProjectionIntegrityError(format!(
                            "transcript item {:?} moved its latest content ordinal backwards",
                            item.stable_id
                        ))
                        .into());
                    }
                    // Reuse the item in place when no published snapshot shares
                    // it; otherwise publish a fresh item so snapshots taken
                    // earlier keep the value they were given.
                    if let Some(owned) = Arc::get_mut(existing) {
                        *owned = item;
                    } else {
                        *existing = Arc::new(item);
                    }
                    if let Some(index) = index.as_deref_mut() {
                        index.insert(existing.clone());
                    }
                } else {
                    let item = Arc::new(item);
                    if let Some(index) = index.as_deref_mut() {
                        index.insert(item.clone());
                    }
                    current.transcript.push(item);
                }
            }
            TranscriptMutation::Remove { stable_id } => {
                if let Some(index) = index.as_deref_mut() {
                    if let Some(position) = index.remove(&stable_id) {
                        let removed = current.transcript.remove(position);
                        if removed.stable_id != stable_id {
                            return Err(ProjectionIntegrityError(format!(
                                "transcript index for {stable_id:?} removed {:?}",
                                removed.stable_id
                            ))
                            .into());
                        }
                        index.reindex_after_removal(&current.transcript, position);
                    }
                } else {
                    current
                        .transcript
                        .retain(|item| item.stable_id != stable_id);
                }
            }
        }
    }
    if let Some(queued_prompts) = mutation.queued_prompts {
        current.queued_prompts = queued_prompts;
    }
    if let Some(pending_elicitations) = mutation.pending_elicitations {
        current.pending_elicitations = pending_elicitations;
    }
    if let Some(active_turn) = mutation.active_turn {
        current.active_turn = active_turn;
    }
    if mutation.clear_turn_outcome {
        current.last_turn_outcome = None;
    }
    if let Some(last_turn_outcome) = mutation.last_turn_outcome {
        current.last_turn_outcome = Some(last_turn_outcome);
    }
    if let Some(activity) = mutation.last_activity_at_ms {
        current.last_activity_at_ms = Some(
            current
                .last_activity_at_ms
                .map_or(activity, |existing| existing.max(activity)),
        );
    }
    current.applied_event_ordinal = event.ordinal;
    current.applied_event_digest.clone_from(&event.digest);
    Ok(())
}

#[cfg(test)]
mod tests;

/// Project a child-addressed update using the same transcript rules as a root.
/// The owning relay has already validated ordering; child events are a sparse
/// subsequence of that relay, so their local frontier may skip owner ordinals.
pub fn project_native_update(
    current: &MaterializedSession,
    event: &RelayEvent,
    update: &agent_client_protocol::v1::schema::SessionUpdate,
) -> Result<MaterializedSessionMutation> {
    let mut mutation = MaterializedSessionMutation {
        last_activity_at_ms: Some(event.recorded_at_ms),
        ..Default::default()
    };
    if let agent_client_protocol::v1::schema::SessionUpdate::UserMessageChunk(chunk) = update {
        mutation
            .transcript
            .push(TranscriptMutation::Upsert(TranscriptItem {
                stable_id: format!("native-user:{}", event.ordinal),
                position: event.ordinal,
                latest_content_event_ordinal: None,
                created_at_ms: event.recorded_at_ms,
                last_changed_at_ms: event.recorded_at_ms,
                body: TranscriptBody::User {
                    content: vec![serde_json::to_value(&chunk.content)?],
                },
            }));
        return Ok(mutation);
    }
    let index = ProjectionIndex::new(current);
    session_update::project_session_update(current, &index, event, update, &mut mutation)?;
    Ok(mutation)
}

pub(crate) use terminals::tool_call_terminal_ids;