trusty-code 0.8.0

Per-project Claude-Code-compatible MPM orchestration harness (bin: tcode) — an original coding harness, tracked under epic #2052.
//! Tests for `sse::aggregate_live` (DOC-48 §5.3, §5.3.1; issue #3297).
//!
//! #6637 slice 2c: the three tests that drove the retired
//! `GET /workstreams/{id}/events` route are gone with it;
//! `serve::uds_tests::workstream_events_refuses_an_unknown_id` and
//! `stream_names_win_over_the_fallback` cover the socket stream.

use std::sync::Arc;
use std::time::Duration;

use serde_json::Value;
use tokio::sync::Mutex;
use uuid::Uuid;

use super::*;
use crate::events::{Event, SessionEventEnvelope};
use crate::workstreams::WorkstreamStore;

/// Mint a session id unique to this test invocation.
///
/// Why: `crate::events::bus()` is a process-wide singleton shared by every
/// concurrently-running test (issue #3297 CI: `cargo test` runs tests in
/// parallel by default). A literal id like `"s1"` collides with any OTHER
/// test in this file using the same literal for its own, differently-bound
/// workstream — confirmed by CI: two concurrently-running tests both using
/// `"s1"` caused one test's fan-out to forward the OTHER's event, since
/// membership is checked by string equality alone. A fresh UUID suffix per
/// test makes cross-test collision practically impossible, mirroring how
/// `session::registry_tests`' real `SessionRegistry::create` calls get
/// unique ids for free.
fn unique_session_id(label: &str) -> String {
    format!("{label}-{}", Uuid::new_v4())
}

/// Build a `SharedWorkstreamStore` seeded with one workstream directly on
/// disk (bypassing the store's public API, which has no session-binding
/// method yet — session binding is issue #3298's scope, not this ticket's;
/// see `workstreams::model::Workstream::session_ids`'s field docs).
async fn seeded_store(
    session_ids: Vec<String>,
) -> (SharedWorkstreamStore, WorkstreamId, tempfile::TempDir) {
    let dir = tempfile::tempdir().expect("tempdir");
    let path = dir.path().join("workstreams-test.json");
    let id = WorkstreamId::new();
    let now = chrono::Utc::now();
    let raw = serde_json::json!({
        "version": "1.0",
        "active_workstream_id": Value::Null,
        "workstreams": [{
            "id": id,
            "name": "t",
            "session_ids": session_ids,
            "created_at": now,
            "updated_at": now,
            "metadata": {},
        }],
    });
    tokio::fs::write(&path, serde_json::to_string_pretty(&raw).unwrap())
        .await
        .expect("seed raw store file");
    let store = WorkstreamStore::load(&path)
        .await
        .expect("load seeded store");
    (Arc::new(Mutex::new(store)), id, dir)
}

fn session_started(session_id: &str) -> SessionEventEnvelope {
    SessionEventEnvelope::new(
        session_id.to_string(),
        1,
        chrono::Utc::now(),
        Event::SessionStarted {
            session_id: session_id.to_string(),
            project: "p".to_string(),
        },
    )
}

/// The fan-out must forward events from BOTH bound sessions, tagged with
/// their own `session_id`/`event_type`, and must NOT forward an event from a
/// third, unbound session.
#[tokio::test]
async fn fan_out_tags_events_from_bound_sessions_only() {
    let s1 = unique_session_id("s1");
    let s2 = unique_session_id("s2");
    let s3 = unique_session_id("s3"); // deliberately NOT added to session_ids below
    let (store, id, _dir) = seeded_store(vec![s1.clone(), s2.clone()]).await;
    let mut stream = std::pin::pin!(aggregate_live(id, store));

    crate::events::publish(session_started(&s1));
    crate::events::publish(session_started(&s2));
    crate::events::publish(session_started(&s3)); // not bound — must be filtered out

    let first = tokio::time::timeout(Duration::from_secs(2), stream.next())
        .await
        .expect("timed out")
        .expect("stream ended early");
    assert_eq!(first.session_id, s1);
    assert_eq!(first.event_type, "session_started");

    let second = tokio::time::timeout(Duration::from_secs(2), stream.next())
        .await
        .expect("timed out")
        .expect("stream ended early");
    assert_eq!(second.session_id, s2);

    // s3's event must never arrive — confirmed by a bounded wait timing out.
    // Any OTHER concurrently-running test's unrelated event is filtered out
    // upstream by `aggregate_live`'s own `session_ids.contains` check (this
    // workstream only binds s1/s2), so a stray foreign envelope cannot
    // masquerade as "the third event" here.
    let third = tokio::time::timeout(Duration::from_millis(300), stream.next()).await;
    assert!(
        third.is_err(),
        "an event from an unbound session must not be forwarded"
    );
}

/// A `WorkstreamActivationChanged` naming this workstream (as either the new
/// active id or the prior one) must be forwarded even though it carries no
/// bound session id at all.
#[tokio::test]
async fn activation_changed_event_is_forwarded_regardless_of_session_binding() {
    let (store, id, _dir) = seeded_store(vec![]).await;
    let mut stream = std::pin::pin!(aggregate_live(id, store));

    let event = Event::WorkstreamActivationChanged {
        new_active_id: Some(id.to_string()),
        prior_id: None,
    };
    crate::events::publish(SessionEventEnvelope::new(
        String::new(),
        0,
        chrono::Utc::now(),
        event,
    ));

    // `id` is a fresh UUID minted by `seeded_store` for this test alone, so
    // filtering the stream for the first matching envelope is robust to any
    // OTHER concurrently-running test's own `WorkstreamActivationChanged` —
    // `aggregate_live` already only forwards events naming THIS `id`.
    let forwarded = tokio::time::timeout(Duration::from_secs(2), stream.next())
        .await
        .expect("timed out waiting for the activation-changed event")
        .expect("stream ended early");
    assert_eq!(forwarded.event_type, "workstream_activation_changed");
    match forwarded.payload {
        Event::WorkstreamActivationChanged { new_active_id, .. } => {
            assert_eq!(new_active_id, Some(id.to_string()));
        }
        other => panic!("expected WorkstreamActivationChanged, got {other:?}"),
    }
}

/// A `WorkstreamStateInferred` naming THIS workstream must be forwarded even
/// with zero bound sessions; one naming a DIFFERENT workstream must not.
#[tokio::test]
async fn state_inferred_event_is_forwarded_for_this_workstream_only() {
    let (store, id, _dir) = seeded_store(vec![]).await;
    let mut stream = std::pin::pin!(aggregate_live(id, store));

    let other = WorkstreamId::new();
    crate::events::publish(SessionEventEnvelope::new(
        String::new(),
        0,
        chrono::Utc::now(),
        Event::WorkstreamStateInferred {
            workstream_id: other.to_string(),
            state: "closed".to_string(),
            reason: "closed".to_string(),
        },
    ));
    crate::events::publish(SessionEventEnvelope::new(
        String::new(),
        0,
        chrono::Utc::now(),
        Event::WorkstreamStateInferred {
            workstream_id: id.to_string(),
            state: "idle".to_string(),
            reason: "deactivated".to_string(),
        },
    ));

    let forwarded = tokio::time::timeout(Duration::from_secs(2), stream.next())
        .await
        .expect("timed out waiting for the state-inferred event")
        .expect("stream ended early");
    match forwarded.payload {
        Event::WorkstreamStateInferred {
            workstream_id,
            state,
            ..
        } => {
            assert_eq!(workstream_id, id.to_string());
            assert_eq!(state, "idle");
        }
        other => panic!("expected WorkstreamStateInferred, got {other:?}"),
    }
}

/// A zero-session workstream's stream must stay open (never close, never
/// error) with no events flowing — it is not an empty/closed stream, just a
/// quiet one until a session is bound or its activation state changes.
#[tokio::test]
async fn empty_workstream_stream_yields_nothing() {
    let (store, id, _dir) = seeded_store(vec![]).await;
    let mut stream = std::pin::pin!(aggregate_live(id, store));

    crate::events::publish(session_started(&unique_session_id("unrelated")));

    let outcome = tokio::time::timeout(Duration::from_millis(300), stream.next()).await;
    assert!(
        outcome.is_err(),
        "an empty workstream must not forward any session's events"
    );
}