Skip to main content

mj_transcript/
projection.rs

1//! Controller-owned projection of the durable ACP relay stream.
2
3mod live;
4mod materialize;
5pub use live::*;
6mod observation;
7mod session_update;
8mod terminals;
9pub use materialize::*;
10pub use observation::*;
11pub use session_update::configuration_values;
12use session_update::*;
13use terminals::*;
14
15mod api_events;
16
17use std::collections::{BTreeMap, BTreeSet, HashMap};
18use std::sync::Arc;
19
20use agent_client_protocol::schema::MaybeUndefined;
21use agent_client_protocol::v1::schema::{
22    ContentBlock, ContentChunk, Plan, PlanEntry, PlanEntryPriority, PlanEntryStatus, SessionUpdate,
23    TextContent, ToolCall, ToolCallContent, ToolCallStatus, ToolCallUpdateFields,
24};
25use anyhow::{Context, Result, bail};
26use serde::Deserialize;
27use serde_json::Value;
28use sha2::{Digest, Sha256};
29
30use crate::transcript::{ChatEntry, ChatRole, PlanStatus, ToolStatus, tool_call_presentation};
31use mj_core::archive::{
32    CanonicalExecutionState, CanonicalQueuedCommandKind, CanonicalQueuedPrompt,
33    CanonicalSessionSnapshot, CanonicalSessionState, CanonicalTerminalOutput,
34    CanonicalTranscriptBody, CanonicalTranscriptItem,
35};
36use mj_core::relay::{
37    RELAY_EVENT_GENESIS_DIGEST, RelayCommand, RelayCommandKind, RelayEvent, RelayObservation,
38    SequencedEvent, WorkerEvent, WorkerPhase, validate_relay_event,
39};
40use mj_core::state::{
41    MaterializedExecutionState, MaterializedQueuedPrompt, MaterializedSession, MaterializedTurn,
42    MaterializedTurnOutcome, QueuedCommandKind, TerminalOutputRecord, TranscriptBody,
43    TranscriptItem, TurnOutcomeKind, config_command_text, normalize_session_title,
44    provisional_session_title,
45};
46use mj_core::storage::{MaterializedSessionMutation, ProjectionIntegrityError, TranscriptMutation};
47use mj_core::transcript::{coalesce_content_chunks, push_content_chunk};
48
49#[derive(Debug, Clone, PartialEq)]
50pub struct ProjectedRelayEvent {
51    pub mutation: MaterializedSessionMutation,
52}
53
54/// Ephemeral lookup state for projecting a relay page. It is deliberately not
55/// part of the serialized session: the durable transcript remains canonical,
56/// while catch-up avoids rediscovering keyed items and open streams with a
57/// full transcript walk for every event.
58#[derive(Debug, Clone)]
59pub struct ProjectionIndex {
60    transcript: HashMap<String, Arc<TranscriptItem>>,
61    transcript_positions: HashMap<String, usize>,
62    open_agent_streams: BTreeSet<(u64, String)>,
63    open_thought_streams: BTreeSet<(u64, String)>,
64    terminal_referrers: HashMap<String, BTreeSet<String>>,
65}
66
67pub struct HistoricalReferences {
68    pub ids: Vec<String>,
69    pub terminals: BTreeSet<String>,
70}
71
72/// Explicit references that may address rows older than a live window. Keep
73/// identity interpretation beside the projector that consumes these events.
74pub fn historical_references(events: &[RelayEvent]) -> Result<HistoricalReferences> {
75    let mut ids = BTreeSet::new();
76    let mut terminals = BTreeSet::new();
77    for event in events {
78        match &event.observation {
79            RelayObservation::SessionUpdate { update } => {
80                let content = match update.as_ref() {
81                    SessionUpdate::ToolCall(call) => {
82                        ids.insert(crate::tool_item_id(&call.tool_call_id));
83                        call.content.as_slice()
84                    }
85                    SessionUpdate::ToolCallUpdate(update) => {
86                        ids.insert(crate::tool_item_id(&update.tool_call_id));
87                        update.fields.content.as_deref().unwrap_or_default()
88                    }
89                    SessionUpdate::AgentMessageChunk(chunk) => {
90                        if let Some(id) = &chunk.message_id {
91                            ids.insert(format!("agent:{id}"));
92                        }
93                        &[]
94                    }
95                    SessionUpdate::AgentThoughtChunk(chunk) => {
96                        if let Some(id) = &chunk.message_id {
97                            ids.insert(format!("thought:{id}"));
98                        }
99                        &[]
100                    }
101                    _ => &[],
102                };
103                for block in content {
104                    if let ToolCallContent::Terminal(terminal) = block {
105                        terminals.insert(terminal.terminal_id.0.to_string());
106                    }
107                }
108            }
109            RelayObservation::TerminalOutput { terminal_id, .. } => {
110                terminals.insert(terminal_id.clone());
111            }
112            RelayObservation::CommandStarted { command_id, .. }
113            | RelayObservation::CommandCompleted { command_id, .. }
114            | RelayObservation::CommandRejected { command_id, .. }
115            | RelayObservation::CommandInterrupted { command_id, .. }
116            | RelayObservation::UserShellOutput { command_id, .. } => {
117                ids.insert(user_shell_item_id(command_id));
118                ids.insert(format!("user:{command_id}"));
119            }
120            RelayObservation::Notice { .. } => {
121                if let Some(id) = &event.command_id {
122                    ids.insert(format!("system:notice:{id}"));
123                }
124            }
125            RelayObservation::MailboxEventsDelivered {
126                event_keys,
127                events,
128                steering,
129                ..
130            } => {
131                ids.extend(
132                    event_keys
133                        .iter()
134                        .chain(events.iter().map(|event| &event.key))
135                        .map(|key| mj_core::transcript::message_item_id(key)),
136                );
137                ids.extend(observation::external_events_item_id(events));
138                if let Some(steering) = steering {
139                    ids.insert(format!("user:{}", steering.queued_prompt_id));
140                    ids.insert(format!("user:{}", steering.command_id));
141                }
142            }
143            RelayObservation::CommandQueued {
144                command: RelayCommand::MailboxWake { events },
145                ..
146            } => {
147                ids.extend(
148                    events
149                        .iter()
150                        .map(|event| mj_core::transcript::message_item_id(&event.key)),
151                );
152                ids.extend(observation::external_events_item_id(events));
153            }
154            _ => {}
155        }
156    }
157    for terminal in &terminals {
158        ids.insert(terminal_item_id(terminal));
159        ids.insert(fallback_terminal_tool_item_id(terminal));
160    }
161    Ok(HistoricalReferences {
162        ids: ids.into_iter().collect(),
163        terminals,
164    })
165}
166
167impl ProjectionIndex {
168    pub fn new(current: &MaterializedSession) -> Self {
169        let mut index = Self {
170            transcript: HashMap::with_capacity(current.transcript.len()),
171            transcript_positions: HashMap::with_capacity(current.transcript.len()),
172            open_agent_streams: BTreeSet::new(),
173            open_thought_streams: BTreeSet::new(),
174            terminal_referrers: HashMap::new(),
175        };
176        for (position, item) in current.transcript.iter().enumerate() {
177            index.insert_at(item.clone(), position);
178        }
179        index
180    }
181
182    fn get(&self, stable_id: &str) -> Option<&Arc<TranscriptItem>> {
183        self.transcript.get(stable_id)
184    }
185
186    fn position(&self, stable_id: &str) -> Option<usize> {
187        self.transcript_positions.get(stable_id).copied()
188    }
189
190    fn insert(&mut self, item: Arc<TranscriptItem>) {
191        let position = self
192            .remove(&item.stable_id)
193            .unwrap_or(self.transcript.len());
194        self.insert_at(item, position);
195    }
196
197    fn insert_at(&mut self, item: Arc<TranscriptItem>, position: usize) {
198        let stream = (item.position, item.stable_id.clone());
199        match &item.body {
200            TranscriptBody::Agent {
201                streaming: true, ..
202            } => {
203                self.open_agent_streams.insert(stream);
204            }
205            TranscriptBody::Thought {
206                streaming: true, ..
207            } => {
208                self.open_thought_streams.insert(stream);
209            }
210            TranscriptBody::Tool {
211                call,
212                terminal_refs,
213                ..
214            } => {
215                let mut terminal_ids = call.terminal_ids().to_vec();
216                terminal_ids.extend(terminal_refs.iter().cloned());
217                for terminal_id in terminal_ids {
218                    self.terminal_referrers
219                        .entry(terminal_id)
220                        .or_default()
221                        .insert(item.stable_id.clone());
222                }
223            }
224            _ => {}
225        }
226        self.transcript_positions
227            .insert(item.stable_id.clone(), position);
228        self.transcript.insert(item.stable_id.clone(), item);
229    }
230
231    fn remove(&mut self, stable_id: &str) -> Option<usize> {
232        let item = self.transcript.remove(stable_id)?;
233        let position = self.transcript_positions.remove(stable_id);
234        debug_assert!(position.is_some());
235        let stream = (item.position, item.stable_id.clone());
236        self.open_agent_streams.remove(&stream);
237        self.open_thought_streams.remove(&stream);
238        if let TranscriptBody::Tool {
239            call,
240            terminal_refs,
241            ..
242        } = &item.body
243        {
244            let mut terminal_ids = call.terminal_ids().to_vec();
245            terminal_ids.extend(terminal_refs.iter().cloned());
246            for terminal_id in terminal_ids {
247                if let Some(referrers) = self.terminal_referrers.get_mut(&terminal_id) {
248                    referrers.remove(stable_id);
249                    if referrers.is_empty() {
250                        self.terminal_referrers.remove(&terminal_id);
251                    }
252                }
253            }
254        }
255        position
256    }
257
258    fn reindex_after_removal(&mut self, transcript: &[Arc<TranscriptItem>], removed: usize) {
259        for (position, item) in transcript.iter().enumerate().skip(removed) {
260            self.transcript_positions
261                .insert(item.stable_id.clone(), position);
262        }
263    }
264
265    fn latest_open_stream(&self, agent: bool) -> Option<&Arc<TranscriptItem>> {
266        let streams = if agent {
267            &self.open_agent_streams
268        } else {
269            &self.open_thought_streams
270        };
271        streams
272            .last()
273            .and_then(|(_, stable_id)| self.transcript.get(stable_id))
274    }
275
276    fn open_streams(&self, agent: bool) -> impl Iterator<Item = &Arc<TranscriptItem>> {
277        let streams = if agent {
278            &self.open_agent_streams
279        } else {
280            &self.open_thought_streams
281        };
282        streams
283            .iter()
284            .filter_map(|(_, stable_id)| self.transcript.get(stable_id))
285    }
286
287    pub fn terminal_referrers(
288        &self,
289        terminal_id: &str,
290    ) -> impl Iterator<Item = &Arc<TranscriptItem>> {
291        self.terminal_referrers
292            .get(terminal_id)
293            .into_iter()
294            .flatten()
295            .filter_map(|stable_id| self.transcript.get(stable_id))
296    }
297}
298
299/// Derive the minimal mutation for exactly the next relay event. This clones
300/// only logical items touched by the event; the actor-owned transcript is not
301/// copied.
302pub fn project_relay_event(
303    current: &MaterializedSession,
304    event: &RelayEvent,
305) -> Result<ProjectedRelayEvent> {
306    let index = ProjectionIndex::new(current);
307    project_relay_event_indexed(current, &index, event)
308}
309
310pub fn project_relay_event_indexed(
311    current: &MaterializedSession,
312    index: &ProjectionIndex,
313    event: &RelayEvent,
314) -> Result<ProjectedRelayEvent> {
315    validate_relay_event(
316        current.applied_event_ordinal,
317        &current.applied_event_digest,
318        event,
319    )?;
320
321    let mut mutation = MaterializedSessionMutation {
322        last_activity_at_ms: Some(event.recorded_at_ms),
323        ..MaterializedSessionMutation::default()
324    };
325    project_observation(current, index, event, &mut mutation)?;
326    mutation.api_events = api_events::derive(current, event, &mutation);
327    Ok(ProjectedRelayEvent { mutation })
328}
329
330/// Apply a mutation to the actor's sole in-memory projection after the same
331/// mutation and frontier have committed atomically in SQLite. The mutation is
332/// consumed so its committed values move into the projection instead of being
333/// copied a second time.
334pub fn apply_committed_projection_event(
335    current: &mut MaterializedSession,
336    event: &RelayEvent,
337    mutation: MaterializedSessionMutation,
338) -> Result<()> {
339    apply_committed_projection_event_inner(current, event, mutation, None)
340}
341
342pub fn apply_committed_projection_event_indexed(
343    current: &mut MaterializedSession,
344    index: &mut ProjectionIndex,
345    event: &RelayEvent,
346    mutation: MaterializedSessionMutation,
347) -> Result<()> {
348    apply_committed_projection_event_inner(current, event, mutation, Some(index))
349}
350
351fn apply_committed_projection_event_inner(
352    current: &mut MaterializedSession,
353    event: &RelayEvent,
354    mutation: MaterializedSessionMutation,
355    mut index: Option<&mut ProjectionIndex>,
356) -> Result<()> {
357    validate_relay_event(
358        current.applied_event_ordinal,
359        &current.applied_event_digest,
360        event,
361    )?;
362    if let Some(execution) = mutation.execution {
363        current.execution = execution;
364    }
365    if let Some(title) = mutation.session_title {
366        current.session_title = title;
367    }
368    if let Some(configuration) = mutation.configuration {
369        current.configuration = configuration;
370    }
371    for item_mutation in mutation.transcript {
372        match item_mutation {
373            TranscriptMutation::Upsert(item) => {
374                item.validate(event.ordinal)?;
375                let existing_position = index
376                    .as_deref()
377                    .and_then(|index| index.position(&item.stable_id));
378                let existing = if let Some(position) = existing_position {
379                    Some(current.transcript.get_mut(position).with_context(|| {
380                        format!(
381                            "transcript index position {position} for {:?} is out of bounds",
382                            item.stable_id
383                        )
384                    })?)
385                } else if index.is_none() {
386                    current
387                        .transcript
388                        .iter_mut()
389                        .find(|existing| existing.stable_id == item.stable_id)
390                } else {
391                    None
392                };
393                if let Some(existing) = existing {
394                    if existing.stable_id != item.stable_id {
395                        return Err(ProjectionIntegrityError(format!(
396                            "transcript index for {:?} points to {:?}",
397                            item.stable_id, existing.stable_id
398                        ))
399                        .into());
400                    }
401                    if existing.position != item.position
402                        || existing.created_at_ms != item.created_at_ms
403                    {
404                        return Err(ProjectionIntegrityError(format!(
405                            "transcript item {:?} changed immutable identity fields",
406                            item.stable_id
407                        ))
408                        .into());
409                    }
410                    if item.last_changed_at_ms < existing.last_changed_at_ms {
411                        return Err(ProjectionIntegrityError(format!(
412                            "transcript item {:?} moved its changed timestamp backwards",
413                            item.stable_id
414                        ))
415                        .into());
416                    }
417                    if existing
418                        .latest_content_event_ordinal
419                        .is_some_and(|existing| {
420                            item.latest_content_event_ordinal
421                                .is_none_or(|next| next < existing)
422                        })
423                    {
424                        return Err(ProjectionIntegrityError(format!(
425                            "transcript item {:?} moved its latest content ordinal backwards",
426                            item.stable_id
427                        ))
428                        .into());
429                    }
430                    // Reuse the item in place when no published snapshot shares
431                    // it; otherwise publish a fresh item so snapshots taken
432                    // earlier keep the value they were given.
433                    if let Some(owned) = Arc::get_mut(existing) {
434                        *owned = item;
435                    } else {
436                        *existing = Arc::new(item);
437                    }
438                    if let Some(index) = index.as_deref_mut() {
439                        index.insert(existing.clone());
440                    }
441                } else {
442                    let item = Arc::new(item);
443                    if let Some(index) = index.as_deref_mut() {
444                        index.insert(item.clone());
445                    }
446                    current.transcript.push(item);
447                }
448            }
449            TranscriptMutation::Remove { stable_id } => {
450                if let Some(index) = index.as_deref_mut() {
451                    if let Some(position) = index.remove(&stable_id) {
452                        let removed = current.transcript.remove(position);
453                        if removed.stable_id != stable_id {
454                            return Err(ProjectionIntegrityError(format!(
455                                "transcript index for {stable_id:?} removed {:?}",
456                                removed.stable_id
457                            ))
458                            .into());
459                        }
460                        index.reindex_after_removal(&current.transcript, position);
461                    }
462                } else {
463                    current
464                        .transcript
465                        .retain(|item| item.stable_id != stable_id);
466                }
467            }
468        }
469    }
470    if let Some(queued_prompts) = mutation.queued_prompts {
471        current.queued_prompts = queued_prompts;
472    }
473    if let Some(pending_elicitations) = mutation.pending_elicitations {
474        current.pending_elicitations = pending_elicitations;
475    }
476    if let Some(active_turn) = mutation.active_turn {
477        current.active_turn = active_turn;
478    }
479    if mutation.clear_turn_outcome {
480        current.last_turn_outcome = None;
481    }
482    if let Some(last_turn_outcome) = mutation.last_turn_outcome {
483        current.last_turn_outcome = Some(last_turn_outcome);
484    }
485    if let Some(activity) = mutation.last_activity_at_ms {
486        current.last_activity_at_ms = Some(
487            current
488                .last_activity_at_ms
489                .map_or(activity, |existing| existing.max(activity)),
490        );
491    }
492    current.applied_event_ordinal = event.ordinal;
493    current.applied_event_digest.clone_from(&event.digest);
494    Ok(())
495}
496
497#[cfg(test)]
498mod tests;
499
500/// Project a child-addressed update using the same transcript rules as a root.
501/// The owning relay has already validated ordering; child events are a sparse
502/// subsequence of that relay, so their local frontier may skip owner ordinals.
503pub fn project_native_update(
504    current: &MaterializedSession,
505    event: &RelayEvent,
506    update: &agent_client_protocol::v1::schema::SessionUpdate,
507) -> Result<MaterializedSessionMutation> {
508    let mut mutation = MaterializedSessionMutation {
509        last_activity_at_ms: Some(event.recorded_at_ms),
510        ..Default::default()
511    };
512    if let agent_client_protocol::v1::schema::SessionUpdate::UserMessageChunk(chunk) = update {
513        mutation
514            .transcript
515            .push(TranscriptMutation::Upsert(TranscriptItem {
516                stable_id: format!("native-user:{}", event.ordinal),
517                position: event.ordinal,
518                latest_content_event_ordinal: None,
519                created_at_ms: event.recorded_at_ms,
520                last_changed_at_ms: event.recorded_at_ms,
521                body: TranscriptBody::User {
522                    content: vec![serde_json::to_value(&chunk.content)?],
523                },
524            }));
525        return Ok(mutation);
526    }
527    let index = ProjectionIndex::new(current);
528    session_update::project_session_update(current, &index, event, update, &mut mutation)?;
529    Ok(mutation)
530}
531
532pub(crate) use terminals::tool_call_terminal_ids;