vtcode-exec-events 0.185.4

Structured execution telemetry event schema used across VT Code crates.
Documentation
//! Lifecycle guard for [`ThreadEvent`] streams.
//!
//! The turn and item lifecycle used to be enforced only by call-site
//! convention, so each violation was repaired by hand where it was noticed
//! (`item.completed` after `turn.completed`, `item.completed` repeated for one
//! item, a turn that failed before it started). [`LifecycleGuard`] is the one
//! place that knows the rules. Every emitter funnel passes events through
//! [`LifecycleGuard::admit`]; the pure [`audit`] runs the same rules over a
//! recorded stream.
//!
//! The guard is pure state: no I/O, no clock, no locking. Callers own the
//! synchronization (the interactive emitter already serializes emission).
//!
//! # Rules
//!
//! - An item that was started inside a turn is completed before that turn's
//!   terminal event. Open items are closed by the guard when a producer forgot.
//! - An item id completes at most once. A repeat is dropped.
//! - A terminal turn event without a started turn gets a `turn.started` first.
//! - `turn.blocked` annotates a turn and never ends it, so the interactive loop
//!   (failed, blocked) and the runner (blocked, failed) orderings are both valid.
//! - Harness and error items, items with no `item.started`, and exec-session
//!   output items are exempt: they legitimately occur outside a turn or outlive
//!   one.

use std::collections::VecDeque;

use hashbrown::HashSet;

use crate::{
    Diagnostic, DiagnosticSeverity, ItemCompletedEvent, ItemUpdatedEvent, ReasoningItem, ThreadEvent, ThreadItem,
    ThreadItemDetails, ToolCallStatus, ToolOutcome, TurnStartedEvent,
};

/// Suffix of the item id that tracks a still-running exec session's output.
///
/// These items are updated while the command runs and completed once on exit,
/// which can be a later turn, so the guard never closes them at a turn end.
pub const EXEC_SESSION_OUTPUT_ITEM_SUFFIX: &str = ":exec-session-output";

/// Completed item ids remembered for duplicate detection. Item ids are unique
/// per session, so a bounded window is enough to catch a repeat that follows
/// its original closely, which is how every observed duplicate arrived.
const COMPLETED_ID_WINDOW: usize = 4096;

/// What the guard does when it can repair a violation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RepairPolicy {
    /// Report violations and pass every event through unchanged.
    Observe,
    /// Report violations and repair the ones with a lossless fix: close open
    /// items before a terminal event, drop a duplicate `item.completed`, and
    /// open a turn before an orphan terminal turn event.
    Repair,
}

/// A broken lifecycle rule.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ViolationKind {
    /// `turn.started` while a turn was already open.
    TurnReopened,
    /// `turn.completed` or `turn.failed` with no turn to end.
    TerminalWithoutTurn,
    /// A second `turn.completed` or `turn.failed` for one turn.
    DuplicateTerminal,
    /// A terminal turn event while items started in the turn were still open.
    OpenItemAtTerminal,
    /// `item.completed` for an id that already completed.
    DuplicateItemCompleted,
    /// An item event for an item started in a turn that has already ended.
    ItemAfterTurnEnd,
    /// `item.started` or `item.updated` for an id that already completed: a
    /// completed handle was reused for different content.
    ItemReusedAfterCompleted,
}

impl ViolationKind {
    /// Stable machine-readable diagnostic code.
    pub const fn code(self) -> &'static str {
        match self {
            Self::TurnReopened => "lifecycle.turn_reopened",
            Self::TerminalWithoutTurn => "lifecycle.terminal_without_turn",
            Self::DuplicateTerminal => "lifecycle.duplicate_terminal",
            Self::OpenItemAtTerminal => "lifecycle.open_item_at_terminal",
            Self::DuplicateItemCompleted => "lifecycle.duplicate_item_completed",
            Self::ItemAfterTurnEnd => "lifecycle.item_after_turn_end",
            Self::ItemReusedAfterCompleted => "lifecycle.item_reused_after_completed",
        }
    }

    const fn summary(self) -> &'static str {
        match self {
            Self::TurnReopened => "A turn started while another turn was still open.",
            Self::TerminalWithoutTurn => "A turn ended without having started.",
            Self::DuplicateTerminal => "A turn ended more than once.",
            Self::OpenItemAtTerminal => "A turn ended while items it started were still open.",
            Self::DuplicateItemCompleted => "An item completed more than once.",
            Self::ItemAfterTurnEnd => "An item event arrived after its turn ended.",
            Self::ItemReusedAfterCompleted => "An item id was reused after the item completed.",
        }
    }
}

/// One lifecycle violation and the item it concerns, when there is one.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Violation {
    pub kind: ViolationKind,
    pub item_id: Option<String>,
}

impl Violation {
    /// Operational diagnostic for this violation. The correlation id is stable
    /// per kind and item so repeated reports replace one another.
    pub fn diagnostic(&self) -> Diagnostic {
        let code = self.kind.code();
        let subject = self.item_id.as_deref().unwrap_or("turn");
        Diagnostic {
            severity: DiagnosticSeverity::Warning,
            code: code.to_string(),
            summary: self.kind.summary().to_string(),
            agent_details: self.item_id.as_ref().map(|id| format!("item: {id}")).unwrap_or_default(),
            correlation_id: format!("{code}:{subject}"),
            actions: Vec::new(),
        }
    }
}

impl Violation {
    /// The diagnostic as an `item.updated` event, the shape every other
    /// operational diagnostic uses. It is an update to an item that was never
    /// started, which the guard exempts, so reporting a violation cannot itself
    /// violate the rules.
    pub fn event(&self) -> ThreadEvent {
        let diagnostic = self.diagnostic();
        ThreadEvent::ItemUpdated(ItemUpdatedEvent {
            item: ThreadItem {
                context: None,
                id: diagnostic.correlation_id.clone(),
                details: ThreadItemDetails::Reasoning(Box::new(ReasoningItem {
                    text: diagnostic.summary.clone(),
                    stage: Some("diagnosis".into()),
                    diagnostic: Some(Box::new(diagnostic)),
                })),
            },
        })
    }
}

/// Result of admitting one event.
#[derive(Debug, Default, PartialEq, Eq)]
pub struct Admission {
    /// Repair events to emit before [`Admission::event`].
    pub before: Vec<ThreadEvent>,
    /// The admitted event, or `None` when it was dropped as a duplicate.
    pub event: Option<ThreadEvent>,
    /// Violations found while admitting the event.
    pub violations: Vec<Violation>,
}

impl Admission {
    /// Every event to emit, in order: repairs first, then the admitted event.
    pub fn into_events(self) -> impl Iterator<Item = ThreadEvent> {
        self.before.into_iter().chain(self.event)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Phase {
    /// No turn has started yet.
    Idle,
    Open,
    /// The turn reached `turn.completed` or `turn.failed`.
    Closed,
}

/// Tracks the turn and item lifecycle of one event stream.
#[derive(Debug)]
pub struct LifecycleGuard {
    policy: RepairPolicy,
    phase: Phase,
    /// Items started in the open turn, with their latest snapshot.
    open: Vec<ThreadItem>,
    completed: HashSet<String>,
    completed_order: VecDeque<String>,
}

impl Default for LifecycleGuard {
    /// Emitter funnels repair by default: the repairs are lossless and match
    /// what call sites used to hand-roll.
    fn default() -> Self {
        Self::new(RepairPolicy::Repair)
    }
}

impl LifecycleGuard {
    pub fn new(policy: RepairPolicy) -> Self {
        Self {
            policy,
            phase: Phase::Idle,
            open: Vec::new(),
            completed: HashSet::new(),
            completed_order: VecDeque::new(),
        }
    }

    /// Whether the guard is currently inside a turn.
    pub fn turn_is_open(&self) -> bool {
        self.phase == Phase::Open
    }

    /// Admit one event, returning what to emit and what was violated.
    pub fn admit(&mut self, event: ThreadEvent) -> Admission {
        let mut admission = Admission::default();
        match &event {
            ThreadEvent::TurnStarted(_) => {
                if self.phase == Phase::Open {
                    admission
                        .violations
                        .push(Violation { kind: ViolationKind::TurnReopened, item_id: None });
                }
                self.phase = Phase::Open;
            }
            ThreadEvent::TurnCompleted(_) | ThreadEvent::TurnFailed(_) => {
                self.admit_terminal(&mut admission);
            }
            ThreadEvent::ItemStarted(started) => self.admit_item_started(&started.item, &mut admission),
            ThreadEvent::ItemUpdated(updated) => self.admit_item_updated(&updated.item, &mut admission),
            ThreadEvent::ItemCompleted(completed) => {
                let keep = self.admit_item_completed(&completed.item, &mut admission);
                if !keep {
                    return admission;
                }
            }
            _ => {}
        }
        admission.event = Some(event);
        admission
    }

    fn admit_terminal(&mut self, admission: &mut Admission) {
        match self.phase {
            Phase::Open => {
                let open = std::mem::take(&mut self.open);
                for item in open {
                    admission.violations.push(Violation {
                        kind: ViolationKind::OpenItemAtTerminal,
                        item_id: Some(item.id.clone()),
                    });
                    if self.policy == RepairPolicy::Repair {
                        let closed = close_item(item);
                        self.remember_completed(&closed.id);
                        admission
                            .before
                            .push(ThreadEvent::ItemCompleted(ItemCompletedEvent { item: closed }));
                    }
                }
            }
            Phase::Idle => {
                admission.violations.push(Violation {
                    kind: ViolationKind::TerminalWithoutTurn,
                    item_id: None,
                });
                if self.policy == RepairPolicy::Repair {
                    admission.before.push(ThreadEvent::TurnStarted(TurnStartedEvent::default()));
                }
            }
            Phase::Closed => {
                admission.violations.push(Violation {
                    kind: ViolationKind::DuplicateTerminal,
                    item_id: None,
                });
            }
        }
        self.phase = Phase::Closed;
    }

    fn admit_item_started(&mut self, item: &ThreadItem, admission: &mut Admission) {
        if is_exempt(item) {
            return;
        }
        if self.completed.contains(&item.id) {
            // Not tracked as open: the id already has its terminal state, and
            // closing it again would repeat `item.completed`.
            admission.violations.push(Violation {
                kind: ViolationKind::ItemReusedAfterCompleted,
                item_id: Some(item.id.clone()),
            });
            return;
        }
        match self.phase {
            Phase::Closed => admission.violations.push(Violation {
                kind: ViolationKind::ItemAfterTurnEnd,
                item_id: Some(item.id.clone()),
            }),
            Phase::Open => self.track_open(item),
            Phase::Idle => {}
        }
    }

    fn admit_item_updated(&mut self, item: &ThreadItem, admission: &mut Admission) {
        if let Some(open) = self.open.iter_mut().find(|open| open.id == item.id) {
            *open = item.clone();
        } else if self.completed.contains(&item.id) && !is_exempt(item) {
            admission.violations.push(Violation {
                kind: ViolationKind::ItemReusedAfterCompleted,
                item_id: Some(item.id.clone()),
            });
        }
    }

    /// Returns whether the event is admitted (`false` drops a duplicate).
    fn admit_item_completed(&mut self, item: &ThreadItem, admission: &mut Admission) -> bool {
        if self.completed.contains(&item.id) {
            admission.violations.push(Violation {
                kind: ViolationKind::DuplicateItemCompleted,
                item_id: Some(item.id.clone()),
            });
            return self.policy != RepairPolicy::Repair;
        }
        let was_open = self.open.iter().any(|open| open.id == item.id);
        self.open.retain(|open| open.id != item.id);
        if !was_open && self.phase == Phase::Closed && !is_exempt(item) {
            admission.violations.push(Violation {
                kind: ViolationKind::ItemAfterTurnEnd,
                item_id: Some(item.id.clone()),
            });
        }
        self.remember_completed(&item.id);
        true
    }

    fn track_open(&mut self, item: &ThreadItem) {
        match self.open.iter_mut().find(|open| open.id == item.id) {
            Some(open) => *open = item.clone(),
            None => self.open.push(item.clone()),
        }
    }

    fn remember_completed(&mut self, id: &str) {
        if self.completed.insert(id.to_string()) {
            self.completed_order.push_back(id.to_string());
            if self.completed_order.len() > COMPLETED_ID_WINDOW
                && let Some(oldest) = self.completed_order.pop_front()
            {
                let _forgotten = self.completed.remove(&oldest);
            }
        }
    }
}

/// Run the lifecycle rules over a recorded stream without repairing it.
pub fn audit(events: &[ThreadEvent]) -> Vec<Violation> {
    let mut guard = LifecycleGuard::new(RepairPolicy::Observe);
    events.iter().flat_map(|event| guard.admit(event.clone()).violations).collect()
}

/// Items the lifecycle rules do not apply to: they occur outside a turn
/// (harness notices, errors) or outlive one (running exec sessions).
fn is_exempt(item: &ThreadItem) -> bool {
    item.id.ends_with(EXEC_SESSION_OUTPUT_ITEM_SUFFIX)
        || matches!(item.details, ThreadItemDetails::Harness(_) | ThreadItemDetails::Error(_))
}

/// Terminal snapshot for an item the producer never completed. Tool items end
/// as cancelled failures; streamed text keeps the text it had.
fn close_item(mut item: ThreadItem) -> ThreadItem {
    match &mut item.details {
        ThreadItemDetails::ToolInvocation(invocation) => {
            invocation.status = ToolCallStatus::Failed;
            invocation.outcome = Some(ToolOutcome::Cancelled);
        }
        ThreadItemDetails::ToolOutput(output) => {
            output.status = ToolCallStatus::Failed;
            output.is_delta = None;
        }
        _ => {}
    }
    item
}

#[cfg(test)]
mod tests;