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, ToolKind,
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    turn_boundaries: BTreeMap<u64, String>,
65    // Position keys let a boundary name its owning turn interval. The actor
66    // window reloads unsettled items together with their owning turn ranges.
67    open_foreground_tools: BTreeSet<(u64, String)>,
68    terminal_referrers: HashMap<String, BTreeSet<String>>,
69}
70
71pub struct HistoricalReferences {
72    pub ids: Vec<String>,
73    pub terminals: BTreeSet<String>,
74}
75
76/// Explicit references that may address rows older than a live window. Keep
77/// identity interpretation beside the projector that consumes these events.
78pub fn historical_references(events: &[RelayEvent]) -> Result<HistoricalReferences> {
79    let mut ids = BTreeSet::new();
80    let mut terminals = BTreeSet::new();
81    for event in events {
82        match &event.observation {
83            RelayObservation::SessionUpdate { update } => {
84                let content = match update.as_ref() {
85                    SessionUpdate::ToolCall(call) => {
86                        ids.insert(crate::tool_item_id(&call.tool_call_id));
87                        call.content.as_slice()
88                    }
89                    SessionUpdate::ToolCallUpdate(update) => {
90                        ids.insert(crate::tool_item_id(&update.tool_call_id));
91                        update.fields.content.as_deref().unwrap_or_default()
92                    }
93                    SessionUpdate::AgentMessageChunk(chunk) => {
94                        if let Some(id) = &chunk.message_id {
95                            ids.insert(format!("agent:{id}"));
96                        }
97                        &[]
98                    }
99                    SessionUpdate::AgentThoughtChunk(chunk) => {
100                        if let Some(id) = &chunk.message_id {
101                            ids.insert(format!("thought:{id}"));
102                        }
103                        &[]
104                    }
105                    _ => &[],
106                };
107                for block in content {
108                    if let ToolCallContent::Terminal(terminal) = block {
109                        terminals.insert(terminal.terminal_id.0.to_string());
110                    }
111                }
112            }
113            RelayObservation::TerminalOutput { terminal_id, .. } => {
114                terminals.insert(terminal_id.clone());
115            }
116            RelayObservation::CommandStarted { command_id, .. }
117            | RelayObservation::CommandCompleted { command_id, .. }
118            | RelayObservation::CommandRejected { command_id, .. }
119            | RelayObservation::CommandInterrupted { command_id, .. }
120            | RelayObservation::UserShellOutput { command_id, .. } => {
121                ids.insert(user_shell_item_id(command_id));
122                ids.insert(format!("user:{command_id}"));
123            }
124            RelayObservation::Notice { .. } => {
125                if let Some(id) = &event.command_id {
126                    ids.insert(format!("system:notice:{id}"));
127                }
128            }
129            RelayObservation::MailboxEventsDelivered {
130                event_keys,
131                events,
132                steering,
133                ..
134            } => {
135                ids.extend(
136                    event_keys
137                        .iter()
138                        .chain(events.iter().map(|event| &event.key))
139                        .map(|key| mj_core::transcript::message_item_id(key)),
140                );
141                ids.extend(observation::external_events_item_id(events));
142                if let Some(steering) = steering {
143                    ids.insert(format!("user:{}", steering.queued_prompt_id));
144                    ids.insert(format!("user:{}", steering.command_id));
145                }
146            }
147            RelayObservation::CommandQueued {
148                command: RelayCommand::MailboxWake { events },
149                ..
150            } => {
151                ids.extend(
152                    events
153                        .iter()
154                        .map(|event| mj_core::transcript::message_item_id(&event.key)),
155                );
156                ids.extend(observation::external_events_item_id(events));
157            }
158            _ => {}
159        }
160    }
161    for terminal in &terminals {
162        ids.insert(terminal_item_id(terminal));
163        ids.insert(fallback_terminal_tool_item_id(terminal));
164    }
165    Ok(HistoricalReferences {
166        ids: ids.into_iter().collect(),
167        terminals,
168    })
169}
170
171impl ProjectionIndex {
172    pub fn new(current: &MaterializedSession) -> Self {
173        let mut index = Self {
174            transcript: HashMap::with_capacity(current.transcript.len()),
175            transcript_positions: HashMap::with_capacity(current.transcript.len()),
176            open_agent_streams: BTreeSet::new(),
177            open_thought_streams: BTreeSet::new(),
178            turn_boundaries: BTreeMap::new(),
179            open_foreground_tools: BTreeSet::new(),
180            terminal_referrers: HashMap::new(),
181        };
182        for (position, item) in current.transcript.iter().enumerate() {
183            index.insert_at(item.clone(), position);
184        }
185        index
186    }
187
188    fn get(&self, stable_id: &str) -> Option<&Arc<TranscriptItem>> {
189        self.transcript.get(stable_id)
190    }
191
192    fn position(&self, stable_id: &str) -> Option<usize> {
193        self.transcript_positions.get(stable_id).copied()
194    }
195
196    fn insert(&mut self, item: Arc<TranscriptItem>) {
197        let position = self
198            .remove(&item.stable_id)
199            .unwrap_or(self.transcript.len());
200        self.insert_at(item, position);
201    }
202
203    fn insert_at(&mut self, item: Arc<TranscriptItem>, position: usize) {
204        let stream = (item.position, item.stable_id.clone());
205        if item.is_turn_start()
206            || item
207                .stable_id
208                .starts_with(crate::transcript::SESSION_RESTART_ITEM_PREFIX)
209            || item
210                .stable_id
211                .starts_with(mj_core::archive::CONTEXT_BOUNDARY_PREFIX)
212        {
213            self.turn_boundaries
214                .insert(item.position, item.stable_id.clone());
215        }
216        match &item.body {
217            TranscriptBody::Agent {
218                streaming: true, ..
219            } => {
220                self.open_agent_streams.insert(stream);
221            }
222            TranscriptBody::Thought {
223                streaming: true, ..
224            } => {
225                self.open_thought_streams.insert(stream);
226            }
227            TranscriptBody::Tool {
228                call,
229                terminal_refs,
230                ..
231            } => {
232                // A tool that hands work to a terminal may outlive the turn
233                // that launched it. Its terminal result owns completion; a
234                // turn boundary must not turn the still-running tool into a
235                // failed foreground call.
236                if !call.is_fallback()
237                    && matches!(
238                        call.raw_status().unwrap_or("pending"),
239                        "pending" | "in_progress"
240                    )
241                    && call.terminal_ids().is_empty()
242                {
243                    self.open_foreground_tools.insert(stream);
244                }
245                let mut terminal_ids = call.terminal_ids().to_vec();
246                terminal_ids.extend(terminal_refs.iter().cloned());
247                for terminal_id in terminal_ids {
248                    self.terminal_referrers
249                        .entry(terminal_id)
250                        .or_default()
251                        .insert(item.stable_id.clone());
252                }
253            }
254            _ => {}
255        }
256        self.transcript_positions
257            .insert(item.stable_id.clone(), position);
258        self.transcript.insert(item.stable_id.clone(), item);
259    }
260
261    fn remove(&mut self, stable_id: &str) -> Option<usize> {
262        let item = self.transcript.remove(stable_id)?;
263        let position = self.transcript_positions.remove(stable_id);
264        debug_assert!(position.is_some());
265        let stream = (item.position, item.stable_id.clone());
266        self.open_agent_streams.remove(&stream);
267        self.open_thought_streams.remove(&stream);
268        self.open_foreground_tools.remove(&stream);
269        if self
270            .turn_boundaries
271            .get(&item.position)
272            .is_some_and(|id| id == stable_id)
273        {
274            self.turn_boundaries.remove(&item.position);
275        }
276        if let TranscriptBody::Tool {
277            call,
278            terminal_refs,
279            ..
280        } = &item.body
281        {
282            let mut terminal_ids = call.terminal_ids().to_vec();
283            terminal_ids.extend(terminal_refs.iter().cloned());
284            for terminal_id in terminal_ids {
285                if let Some(referrers) = self.terminal_referrers.get_mut(&terminal_id) {
286                    referrers.remove(stable_id);
287                    if referrers.is_empty() {
288                        self.terminal_referrers.remove(&terminal_id);
289                    }
290                }
291            }
292        }
293        position
294    }
295
296    fn reindex_after_removal(&mut self, transcript: &[Arc<TranscriptItem>], removed: usize) {
297        for (position, item) in transcript.iter().enumerate().skip(removed) {
298            self.transcript_positions
299                .insert(item.stable_id.clone(), position);
300        }
301    }
302
303    fn latest_open_stream(&self, agent: bool) -> Option<&Arc<TranscriptItem>> {
304        let streams = if agent {
305            &self.open_agent_streams
306        } else {
307            &self.open_thought_streams
308        };
309        streams
310            .last()
311            .and_then(|(_, stable_id)| self.transcript.get(stable_id))
312    }
313
314    fn open_streams(&self, agent: bool) -> impl Iterator<Item = &Arc<TranscriptItem>> {
315        let streams = if agent {
316            &self.open_agent_streams
317        } else {
318            &self.open_thought_streams
319        };
320        streams
321            .iter()
322            .filter_map(|(_, stable_id)| self.transcript.get(stable_id))
323    }
324
325    fn open_tools_in_turn(
326        &self,
327        start: u64,
328        end: u64,
329    ) -> impl Iterator<Item = &Arc<TranscriptItem>> {
330        self.open_foreground_tools
331            .range((start, String::new())..(end, String::new()))
332            .filter_map(|(_, id)| self.get(id))
333    }
334
335    fn prompt_start(&self, turn: &MaterializedTurn) -> u64 {
336        turn.steered_into
337            .as_ref()
338            .and_then(|id| self.get(&format!("user:{id}")))
339            .map_or(turn.turn_start_position, |item| item.position)
340    }
341
342    fn running_turn_start(&self, current: &MaterializedSession) -> Option<u64> {
343        if let Some(turn) = &current.active_turn {
344            return Some(self.prompt_start(turn));
345        }
346        let MaterializedExecutionState::Running { started_at_ms } = current.execution else {
347            return None;
348        };
349        let (&start, id) = self.turn_boundaries.last_key_value()?;
350        // A native goal can continue after its prompt outcome. The original
351        // running clock still identifies that prompt's start.
352        if let Some(outcome) = &current.last_turn_outcome
353            && outcome.turn_start_position == Some(start)
354        {
355            return self
356                .get(&format!("user:{}", outcome.command_id))
357                .or_else(|| {
358                    self.get(&format!(
359                        "{}{id}",
360                        crate::transcript::HARNESS_TURN_ITEM_PREFIX,
361                        id = outcome.command_id
362                    ))
363                })
364                .filter(|item| item.created_at_ms == started_at_ms)
365                .map(|item| item.position);
366        }
367        is_open_autonomous_turn(current, start, id)
368            .then(|| self.adopted_autonomous_start(current, start))
369    }
370
371    fn open_autonomous_turn_before(&self, current: &MaterializedSession, end: u64) -> Option<u64> {
372        self.turn_boundaries
373            .range(..end)
374            .rev()
375            .take_while(|(_, id)| self.get(id).is_some_and(|item| item.is_turn_start()))
376            .find_map(|(&start, id)| is_open_autonomous_turn(current, start, id).then_some(start))
377    }
378
379    fn adopted_autonomous_start(&self, current: &MaterializedSession, turn_start: u64) -> u64 {
380        let Some((&previous, id)) = self.turn_boundaries.range(..turn_start).next_back() else {
381            return 0;
382        };
383        if self.get(id).is_some_and(|item| !item.is_turn_start()) {
384            return previous;
385        }
386        // A native tool can be announced before its harness turn marker.
387        // A previous turn's completion bounds which earlier calls it adopted.
388        current
389            .last_turn_outcome
390            .as_ref()
391            .map(|turn| turn.completed_ordinal)
392            .filter(|completed| (previous..turn_start).contains(completed))
393            .map_or(turn_start, |completed| completed.saturating_add(1))
394    }
395
396    pub fn terminal_referrers(
397        &self,
398        terminal_id: &str,
399    ) -> impl Iterator<Item = &Arc<TranscriptItem>> {
400        self.terminal_referrers
401            .get(terminal_id)
402            .into_iter()
403            .flatten()
404            .filter_map(|stable_id| self.transcript.get(stable_id))
405    }
406}
407
408fn is_open_autonomous_turn(current: &MaterializedSession, start: u64, id: &str) -> bool {
409    id.strip_prefix(crate::transcript::HARNESS_TURN_ITEM_PREFIX)
410        .and_then(|ordinal| ordinal.parse::<u64>().ok())
411        == Some(start)
412        && !current.last_turn_outcome.as_ref().is_some_and(|turn| {
413            turn.turn_start_position.is_some() && turn.completed_ordinal > start
414        })
415}
416
417fn tool_status_is_open(status: ToolCallStatus) -> bool {
418    matches!(status, ToolCallStatus::Pending | ToolCallStatus::InProgress)
419}
420
421/// Derive the minimal mutation for exactly the next relay event. This clones
422/// only logical items touched by the event; the actor-owned transcript is not
423/// copied.
424pub fn project_relay_event(
425    current: &MaterializedSession,
426    event: &RelayEvent,
427) -> Result<ProjectedRelayEvent> {
428    let index = ProjectionIndex::new(current);
429    project_relay_event_indexed(current, &index, event)
430}
431
432pub fn project_relay_event_indexed(
433    current: &MaterializedSession,
434    index: &ProjectionIndex,
435    event: &RelayEvent,
436) -> Result<ProjectedRelayEvent> {
437    validate_relay_event(
438        current.applied_event_ordinal,
439        &current.applied_event_digest,
440        event,
441    )?;
442
443    let mut mutation = MaterializedSessionMutation {
444        last_activity_at_ms: Some(event.recorded_at_ms),
445        ..MaterializedSessionMutation::default()
446    };
447    project_observation(current, index, event, &mut mutation)?;
448    mutation.api_events = api_events::derive(current, event, &mutation);
449    Ok(ProjectedRelayEvent { mutation })
450}
451
452/// Apply a mutation to the actor's sole in-memory projection after the same
453/// mutation and frontier have committed atomically in SQLite. The mutation is
454/// consumed so its committed values move into the projection instead of being
455/// copied a second time.
456pub fn apply_committed_projection_event(
457    current: &mut MaterializedSession,
458    event: &RelayEvent,
459    mutation: MaterializedSessionMutation,
460) -> Result<()> {
461    apply_committed_projection_event_inner(current, event, mutation, None)
462}
463
464pub fn apply_committed_projection_event_indexed(
465    current: &mut MaterializedSession,
466    index: &mut ProjectionIndex,
467    event: &RelayEvent,
468    mutation: MaterializedSessionMutation,
469) -> Result<()> {
470    apply_committed_projection_event_inner(current, event, mutation, Some(index))
471}
472
473fn apply_committed_projection_event_inner(
474    current: &mut MaterializedSession,
475    event: &RelayEvent,
476    mutation: MaterializedSessionMutation,
477    mut index: Option<&mut ProjectionIndex>,
478) -> Result<()> {
479    validate_relay_event(
480        current.applied_event_ordinal,
481        &current.applied_event_digest,
482        event,
483    )?;
484    if let Some(execution) = mutation.execution {
485        current.execution = execution;
486    }
487    if let Some(title) = mutation.session_title {
488        current.session_title = title;
489    }
490    if let Some(configuration) = mutation.configuration {
491        current.configuration = configuration;
492    }
493    for item_mutation in mutation.transcript {
494        match item_mutation {
495            TranscriptMutation::Upsert(item) => {
496                item.validate(event.ordinal)?;
497                let existing_position = index
498                    .as_deref()
499                    .and_then(|index| index.position(&item.stable_id));
500                let existing = if let Some(position) = existing_position {
501                    Some(current.transcript.get_mut(position).with_context(|| {
502                        format!(
503                            "transcript index position {position} for {:?} is out of bounds",
504                            item.stable_id
505                        )
506                    })?)
507                } else if index.is_none() {
508                    current
509                        .transcript
510                        .iter_mut()
511                        .find(|existing| existing.stable_id == item.stable_id)
512                } else {
513                    None
514                };
515                if let Some(existing) = existing {
516                    if existing.stable_id != item.stable_id {
517                        return Err(ProjectionIntegrityError(format!(
518                            "transcript index for {:?} points to {:?}",
519                            item.stable_id, existing.stable_id
520                        ))
521                        .into());
522                    }
523                    if existing.position != item.position
524                        || existing.created_at_ms != item.created_at_ms
525                    {
526                        return Err(ProjectionIntegrityError(format!(
527                            "transcript item {:?} changed immutable identity fields",
528                            item.stable_id
529                        ))
530                        .into());
531                    }
532                    if item.last_changed_at_ms < existing.last_changed_at_ms {
533                        return Err(ProjectionIntegrityError(format!(
534                            "transcript item {:?} moved its changed timestamp backwards",
535                            item.stable_id
536                        ))
537                        .into());
538                    }
539                    if existing
540                        .latest_content_event_ordinal
541                        .is_some_and(|existing| {
542                            item.latest_content_event_ordinal
543                                .is_none_or(|next| next < existing)
544                        })
545                    {
546                        return Err(ProjectionIntegrityError(format!(
547                            "transcript item {:?} moved its latest content ordinal backwards",
548                            item.stable_id
549                        ))
550                        .into());
551                    }
552                    // Reuse the item in place when no published snapshot shares
553                    // it; otherwise publish a fresh item so snapshots taken
554                    // earlier keep the value they were given.
555                    if let Some(owned) = Arc::get_mut(existing) {
556                        *owned = item;
557                    } else {
558                        *existing = Arc::new(item);
559                    }
560                    if let Some(index) = index.as_deref_mut() {
561                        index.insert(existing.clone());
562                    }
563                } else {
564                    let item = Arc::new(item);
565                    if let Some(index) = index.as_deref_mut() {
566                        index.insert(item.clone());
567                    }
568                    current.transcript.push(item);
569                }
570            }
571            TranscriptMutation::Remove { stable_id } => {
572                if let Some(index) = index.as_deref_mut() {
573                    if let Some(position) = index.remove(&stable_id) {
574                        let removed = current.transcript.remove(position);
575                        if removed.stable_id != stable_id {
576                            return Err(ProjectionIntegrityError(format!(
577                                "transcript index for {stable_id:?} removed {:?}",
578                                removed.stable_id
579                            ))
580                            .into());
581                        }
582                        index.reindex_after_removal(&current.transcript, position);
583                    }
584                } else {
585                    current
586                        .transcript
587                        .retain(|item| item.stable_id != stable_id);
588                }
589            }
590        }
591    }
592    if let Some(queued_prompts) = mutation.queued_prompts {
593        current.queued_prompts = queued_prompts;
594    }
595    if let Some(pending_elicitations) = mutation.pending_elicitations {
596        current.pending_elicitations = pending_elicitations;
597    }
598    if let Some(active_turn) = mutation.active_turn {
599        current.active_turn = active_turn;
600    }
601    if mutation.clear_turn_outcome {
602        current.last_turn_outcome = None;
603    }
604    if let Some(last_turn_outcome) = mutation.last_turn_outcome {
605        current.last_turn_outcome = Some(last_turn_outcome);
606    }
607    if let Some(activity) = mutation.last_activity_at_ms {
608        current.last_activity_at_ms = Some(
609            current
610                .last_activity_at_ms
611                .map_or(activity, |existing| existing.max(activity)),
612        );
613    }
614    current.applied_event_ordinal = event.ordinal;
615    current.applied_event_digest.clone_from(&event.digest);
616    Ok(())
617}
618
619#[cfg(test)]
620mod tests;
621
622/// Project a child-addressed update using the same transcript rules as a root.
623/// The owning relay has already validated ordering; child events are a sparse
624/// subsequence of that relay, so their local frontier may skip owner ordinals.
625pub fn project_native_update(
626    current: &MaterializedSession,
627    event: &RelayEvent,
628    update: &agent_client_protocol::v1::schema::SessionUpdate,
629) -> Result<MaterializedSessionMutation> {
630    let mut mutation = MaterializedSessionMutation {
631        last_activity_at_ms: Some(event.recorded_at_ms),
632        ..Default::default()
633    };
634    if let agent_client_protocol::v1::schema::SessionUpdate::UserMessageChunk(chunk) = update {
635        mutation
636            .transcript
637            .push(TranscriptMutation::Upsert(TranscriptItem {
638                stable_id: format!("native-user:{}", event.ordinal),
639                position: event.ordinal,
640                latest_content_event_ordinal: None,
641                created_at_ms: event.recorded_at_ms,
642                last_changed_at_ms: event.recorded_at_ms,
643                body: TranscriptBody::User {
644                    content: vec![serde_json::to_value(&chunk.content)?],
645                },
646            }));
647        return Ok(mutation);
648    }
649    let index = ProjectionIndex::new(current);
650    session_update::project_session_update(current, &index, event, update, &mut mutation)?;
651    Ok(mutation)
652}
653
654pub(crate) use terminals::tool_call_terminal_ids;