Skip to main content

mj_transcript/
projection.rs

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