vtcode-exec-events 0.185.4

Structured execution telemetry event schema used across VT Code crates.
Documentation
use super::*;
use crate::{
    AgentMessageItem, ErrorItem, ItemStartedEvent, ItemUpdatedEvent, ToolInvocationItem, ToolOutputItem,
    TurnCompletedEvent, TurnFailedEvent, Usage,
};

fn item(id: &str, details: ThreadItemDetails) -> ThreadItem {
    ThreadItem { context: None, id: id.to_string(), details }
}

fn message(id: &str, text: &str) -> ThreadItem {
    item(id, ThreadItemDetails::AgentMessage(AgentMessageItem { text: text.to_string() }))
}

fn invocation(id: &str, status: ToolCallStatus) -> ThreadItem {
    item(
        id,
        ThreadItemDetails::ToolInvocation(Box::new(ToolInvocationItem {
            tool_name: "unified_search".to_string(),
            arguments: None,
            tool_call_id: Some("call-1".to_string()),
            status,
            outcome: None,
        })),
    )
}

fn output(id: &str, status: ToolCallStatus) -> ThreadItem {
    item(
        id,
        ThreadItemDetails::ToolOutput(Box::new(ToolOutputItem {
            call_id: "call-item".to_string(),
            tool_call_id: None,
            spool_path: None,
            output: String::new(),
            is_delta: Some(true),
            exit_code: None,
            status,
            app_previews: Vec::new(),
        })),
    )
}

fn error_item(id: &str) -> ThreadItem {
    item(id, ThreadItemDetails::Error(ErrorItem { message: "boom".to_string() }))
}

fn turn_started() -> ThreadEvent {
    ThreadEvent::TurnStarted(TurnStartedEvent::default())
}

fn turn_completed() -> ThreadEvent {
    ThreadEvent::TurnCompleted(TurnCompletedEvent {
        final_response_item_id: None,
        completed_at: None,
        usage: Usage::default(),
        in_progress_exec_sessions: Vec::new(),
    })
}

fn turn_failed() -> ThreadEvent {
    ThreadEvent::TurnFailed(TurnFailedEvent {
        completed_at: None,
        message: "failed".to_string(),
        usage: None,
    })
}

fn started(item: ThreadItem) -> ThreadEvent {
    ThreadEvent::ItemStarted(ItemStartedEvent { item })
}

fn updated(item: ThreadItem) -> ThreadEvent {
    ThreadEvent::ItemUpdated(ItemUpdatedEvent { item })
}

fn completed(item: ThreadItem) -> ThreadEvent {
    ThreadEvent::ItemCompleted(ItemCompletedEvent { item })
}

/// Admit a stream, returning the events a funnel would emit and the violations.
fn run(policy: RepairPolicy, events: Vec<ThreadEvent>) -> (Vec<ThreadEvent>, Vec<Violation>) {
    let mut guard = LifecycleGuard::new(policy);
    let mut emitted = Vec::new();
    let mut violations = Vec::new();
    for event in events {
        let mut admission = guard.admit(event);
        violations.append(&mut admission.violations);
        emitted.extend(admission.into_events());
    }
    (emitted, violations)
}

fn kinds(violations: &[Violation]) -> Vec<ViolationKind> {
    violations.iter().map(|violation| violation.kind).collect()
}

#[test]
fn well_formed_turn_passes_through_untouched() {
    let stream = vec![
        turn_started(),
        started(invocation("call", ToolCallStatus::InProgress)),
        updated(invocation("call", ToolCallStatus::InProgress)),
        completed(invocation("call", ToolCallStatus::Completed)),
        started(message("msg", "")),
        completed(message("msg", "done")),
        turn_completed(),
    ];
    let (emitted, violations) = run(RepairPolicy::Repair, stream.clone());
    assert_eq!(emitted, stream);
    assert!(violations.is_empty(), "{violations:?}");
    assert!(audit(&stream).is_empty());
}

/// `06c6ad81a`: streamed tool-call items that never dispatched were closed
/// after the terminal event. The guard closes them first, as cancelled
/// failures, without any call-site ordering.
#[test]
fn open_tool_items_are_closed_before_the_terminal_event() {
    let stream = vec![
        turn_started(),
        started(invocation("call", ToolCallStatus::InProgress)),
        started(output("call:output", ToolCallStatus::InProgress)),
        started(message("msg", "partial")),
        turn_failed(),
    ];
    let (emitted, violations) = run(RepairPolicy::Repair, stream);

    assert_eq!(kinds(&violations), vec![ViolationKind::OpenItemAtTerminal; 3]);
    let terminal = emitted.len() - 1;
    assert!(matches!(emitted[terminal], ThreadEvent::TurnFailed(_)));

    let closed = &emitted[4..terminal];
    assert_eq!(closed.len(), 3, "one completion per open item, before the terminal");
    let ThreadEvent::ItemCompleted(ItemCompletedEvent { item: invocation }) = &closed[0] else {
        panic!("expected item.completed, got {:?}", closed[0]);
    };
    let ThreadItemDetails::ToolInvocation(invocation) = &invocation.details else {
        panic!("expected a tool invocation");
    };
    assert_eq!(invocation.status, ToolCallStatus::Failed);
    assert_eq!(invocation.outcome, Some(ToolOutcome::Cancelled));
    let ThreadEvent::ItemCompleted(ItemCompletedEvent { item: output }) = &closed[1] else {
        panic!("expected item.completed, got {:?}", closed[1]);
    };
    let ThreadItemDetails::ToolOutput(output) = &output.details else {
        panic!("expected a tool output");
    };
    assert_eq!(output.status, ToolCallStatus::Failed);
    // The streamed text item keeps what it had.
    let ThreadEvent::ItemCompleted(ItemCompletedEvent { item: text }) = &closed[2] else {
        panic!("expected item.completed, got {:?}", closed[2]);
    };
    assert_eq!(text, &message("msg", "partial"));
}

#[test]
fn observe_policy_reports_but_never_rewrites() {
    let stream = vec![turn_started(), started(message("msg", "x")), turn_completed()];
    let (emitted, violations) = run(RepairPolicy::Observe, stream.clone());
    assert_eq!(emitted, stream);
    assert_eq!(kinds(&violations), vec![ViolationKind::OpenItemAtTerminal]);
}

/// `73c9a1ea1`: a running exec session reported `item.completed` on every poll.
#[test]
fn a_repeated_item_completed_is_dropped() {
    let stream = vec![
        turn_started(),
        started(invocation("call", ToolCallStatus::InProgress)),
        completed(invocation("call", ToolCallStatus::Completed)),
        completed(invocation("call", ToolCallStatus::InProgress)),
        turn_completed(),
    ];
    let (emitted, violations) = run(RepairPolicy::Repair, stream);
    assert_eq!(kinds(&violations), vec![ViolationKind::DuplicateItemCompleted]);
    let completions = emitted
        .iter()
        .filter(|event| matches!(event, ThreadEvent::ItemCompleted(_)))
        .count();
    assert_eq!(completions, 1);
}

/// The producer's late completion of an item the guard already closed is a
/// duplicate, not a second terminal state.
#[test]
fn a_late_completion_of_a_guard_closed_item_is_dropped() {
    let stream = vec![
        turn_started(),
        started(invocation("call", ToolCallStatus::InProgress)),
        turn_completed(),
        completed(invocation("call", ToolCallStatus::Completed)),
    ];
    let (emitted, violations) = run(RepairPolicy::Repair, stream);
    assert_eq!(kinds(&violations), vec![ViolationKind::OpenItemAtTerminal, ViolationKind::DuplicateItemCompleted]);
    let completions = emitted
        .iter()
        .filter(|event| matches!(event, ThreadEvent::ItemCompleted(_)))
        .count();
    assert_eq!(completions, 1, "only the guard's cancelled completion is emitted");
}

/// `8500b91d5`: a preparation failure reported before the turn opened.
#[test]
fn a_terminal_turn_event_without_a_turn_gets_a_turn_started() {
    let (emitted, violations) = run(RepairPolicy::Repair, vec![turn_failed()]);
    assert_eq!(kinds(&violations), vec![ViolationKind::TerminalWithoutTurn]);
    assert!(matches!(emitted.as_slice(), [ThreadEvent::TurnStarted(_), ThreadEvent::TurnFailed(_)]));

    let (emitted, violations) = run(RepairPolicy::Repair, vec![turn_completed()]);
    assert_eq!(kinds(&violations), vec![ViolationKind::TerminalWithoutTurn]);
    assert!(matches!(emitted.as_slice(), [ThreadEvent::TurnStarted(_), ThreadEvent::TurnCompleted(_)]));

    // Observe never invents events.
    let (emitted, _) = run(RepairPolicy::Observe, vec![turn_failed()]);
    assert_eq!(emitted.len(), 1);
}

#[test]
fn turn_blocked_annotates_without_ending_the_turn() {
    let blocked = ThreadEvent::TurnBlocked(Box::new(crate::TurnBlockedEvent {
        completed_at: None,
        message: "blocked".to_string(),
        last_tool: None,
        blocked_streak: 8,
        blocked_total: 8,
        consecutive_cap: 8,
        total_cap: 16,
        recovery_active: false,
        usage: None,
    }));
    // Interactive loop order (failed, blocked) and runner order (blocked, failed).
    for stream in [
        vec![
            turn_started(),
            turn_failed(),
            blocked.clone(),
            completed(error_item("harness")),
        ],
        vec![
            turn_started(),
            blocked.clone(),
            completed(error_item("harness")),
            turn_failed(),
        ],
    ] {
        let (emitted, violations) = run(RepairPolicy::Repair, stream.clone());
        assert!(violations.is_empty(), "{violations:?}");
        assert_eq!(emitted, stream);
    }
}

#[test]
fn items_outside_a_turn_and_unstarted_updates_are_exempt() {
    let stream = vec![
        // A one-shot item before any turn (skill command, rewind notice).
        completed(error_item("notice")),
        turn_started(),
        turn_completed(),
        // A diagnostic: an update that was never started, after the turn ended.
        updated(message("diagnostic", "note")),
        // A one-shot error item after the turn ended.
        completed(error_item("late-error")),
    ];
    let (emitted, violations) = run(RepairPolicy::Repair, stream.clone());
    assert!(violations.is_empty(), "{violations:?}");
    assert_eq!(emitted, stream);
}

#[test]
fn a_running_exec_session_item_outlives_the_turn() {
    let session = item(
        "launch:exec-session-output",
        ThreadItemDetails::ToolOutput(Box::new(ToolOutputItem {
            call_id: "launch".to_string(),
            tool_call_id: None,
            spool_path: None,
            output: String::new(),
            is_delta: None,
            exit_code: None,
            status: ToolCallStatus::InProgress,
            app_previews: Vec::new(),
        })),
    );
    let stream = vec![
        turn_started(),
        started(session.clone()),
        updated(session.clone()),
        turn_completed(),
        turn_started(),
        updated(session.clone()),
        completed(session),
        turn_completed(),
    ];
    let (emitted, violations) = run(RepairPolicy::Repair, stream.clone());
    assert!(violations.is_empty(), "{violations:?}");
    assert_eq!(emitted, stream);
}

#[test]
fn an_item_started_after_the_turn_ended_is_reported() {
    let stream = vec![turn_started(), turn_completed(), started(message("late", ""))];
    let (emitted, violations) = run(RepairPolicy::Repair, stream.clone());
    assert_eq!(kinds(&violations), vec![ViolationKind::ItemAfterTurnEnd]);
    assert_eq!(emitted, stream, "unrepairable violations pass through");
}

#[test]
fn reopening_a_turn_and_ending_it_twice_are_reported() {
    let (_, violations) = run(RepairPolicy::Repair, vec![turn_started(), turn_started()]);
    assert_eq!(kinds(&violations), vec![ViolationKind::TurnReopened]);

    let (_, violations) = run(RepairPolicy::Repair, vec![turn_started(), turn_completed(), turn_failed()]);
    assert_eq!(kinds(&violations), vec![ViolationKind::DuplicateTerminal]);
}

#[test]
fn a_new_turn_after_a_closed_one_is_clean() {
    let stream = vec![
        turn_started(),
        started(message("a", "")),
        completed(message("a", "x")),
        turn_completed(),
        turn_started(),
        started(message("b", "")),
        completed(message("b", "y")),
        turn_completed(),
    ];
    let (emitted, violations) = run(RepairPolicy::Repair, stream.clone());
    assert!(violations.is_empty(), "{violations:?}");
    assert_eq!(emitted, stream);
}

#[test]
fn violations_render_stable_diagnostics() {
    let violation = Violation {
        kind: ViolationKind::DuplicateItemCompleted,
        item_id: Some("item_7".to_string()),
    };
    let diagnostic = violation.diagnostic();
    assert_eq!(diagnostic.code, "lifecycle.duplicate_item_completed");
    assert_eq!(diagnostic.correlation_id, "lifecycle.duplicate_item_completed:item_7");
    assert_eq!(diagnostic.severity, DiagnosticSeverity::Warning);
    assert!(diagnostic.agent_details.contains("item_7"));

    let turn_level = Violation { kind: ViolationKind::TurnReopened, item_id: None };
    assert_eq!(turn_level.diagnostic().correlation_id, "lifecycle.turn_reopened:turn");
}

/// Every stream up to five events over a small alphabet: whatever a producer
/// does, the repaired stream never contains the violations the guard can fix.
#[test]
fn repaired_streams_never_contain_a_repairable_violation() {
    let alphabet: Vec<ThreadEvent> = vec![
        turn_started(),
        turn_completed(),
        turn_failed(),
        started(invocation("a", ToolCallStatus::InProgress)),
        updated(invocation("a", ToolCallStatus::InProgress)),
        completed(invocation("a", ToolCallStatus::Completed)),
        started(message("b", "")),
        completed(message("b", "x")),
    ];
    let repairable = [
        ViolationKind::OpenItemAtTerminal,
        ViolationKind::DuplicateItemCompleted,
        ViolationKind::TerminalWithoutTurn,
    ];

    let mut checked = 0_usize;
    let mut indices = [0_usize; 5];
    loop {
        let stream: Vec<ThreadEvent> = indices.iter().map(|&index| alphabet[index].clone()).collect();
        let (emitted, _) = run(RepairPolicy::Repair, stream.clone());
        let remaining = audit(&emitted);
        assert!(
            remaining.iter().all(|violation| !repairable.contains(&violation.kind)),
            "repaired stream still violates: {remaining:?}\ninput: {stream:?}"
        );
        checked += 1;

        // Odometer over the alphabet.
        let mut position = indices.len();
        loop {
            if position == 0 {
                assert_eq!(checked, alphabet.len().pow(5));
                return;
            }
            position -= 1;
            indices[position] += 1;
            if indices[position] < alphabet.len() {
                break;
            }
            indices[position] = 0;
        }
    }
}