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