trusty-code 0.5.1

Per-project Claude-Code-compatible MPM orchestration harness (bin: tcode) — an original coding harness, tracked under epic #2052.
Documentation
//! API-driven end-to-end test for #2056's `task.run` and #2058's
//! `session.get_transcript` — the M1 control-plane cut line: a task actually
//! EXECUTES through the daemon, produces LIVE tool events via the #2055
//! emission plumbing, and its transcript/usage/cost can be inspected
//! afterward over the wire.
//!
//! Why: the vision spec's Testability requirement (§9, "100% CLI/API
//! Testable") mandates that each slice be validated by spawning the REAL
//! `tcode serve` daemon and driving it over the actual wire protocol — never
//! by calling into `trusty_code`'s Rust API directly (see
//! `tests/session_e2e.rs`'s module docs for the same rationale, applied
//! there to #2054/#2055). Using a live LLM would make this test
//! nondeterministic and require `OPENROUTER_API_KEY` in CI, so this drives
//! the daemon with `TCODE_MOCK_LLM=echo` (#2056's offline `EchoLlmClient`)
//! — a real subprocess, a real JSON-RPC wire, a real in-process PM ->
//! engineer delegation, just a scripted model underneath.
//! What: [`task_run_streams_live_tool_events_to_completion`] provisions a
//! throwaway project with `pm.md` + `python-engineer.md`, calls
//! `task.run`, `session.attach`es (the mock run may already have finished by
//! the time this fires — the ring-buffer replay covers that race either
//! way, mirroring `session_e2e.rs`'s own read-until-terminal pattern), and
//! asserts the observed event kinds include the PM's `delegate_to_agent`
//! dispatch AND the delegated engineer's own `bash` dispatch (proving #2056
//! requirement 4 — a delegated sub-agent's activity is observable too) before
//! the session lands on `status: "finished"`.
//! [`task_run_rejects_a_second_overlapping_run`] proves the "no overlapping
//! runs per session" guarantee over the real wire, not just at the
//! `SessionRegistry` unit level.
//! [`task_run_then_get_transcript_exposes_turns_usage_and_cost`] (#2058) runs
//! a task to completion, then calls `session.get_transcript` and asserts the
//! returned turns cover both the `pm` and `python-engineer` roles with their
//! `delegate_to_agent`/`bash` tool calls, and that aggregate usage/cost are
//! non-zero — proving the stored run record is readable over the real wire,
//! not just at the `SessionRegistry` unit level.
//! Test: this file IS the test; see `support` for the process/protocol
//! plumbing shared with `session_e2e.rs`.

mod support;

use serde_json::json;
use support::{StdioSession, find_session_event, project_with_agents, run_task_to_completion};

/// `task.run` -> `session.attach` must observe the FULL PM -> engineer tool
/// dispatch as live (or, in the replay burst, if the mock run already
/// finished) events, ending with the session `finished`.
#[tokio::test]
async fn task_run_streams_live_tool_events_to_completion() {
    let project = project_with_agents();
    let mut daemon = StdioSession::spawn_with_mock_llm(project.path());

    // 1. task.run — must return immediately (not block on the whole run).
    let run_resp = daemon
        .call(1, "task.run", json!({"task_description": "say hi"}))
        .await;
    assert!(run_resp["error"].is_null(), "task.run failed: {run_resp}");
    let session_id = run_resp["result"]["session_id"]
        .as_str()
        .expect("task.run must return a session_id")
        .to_string();
    assert_eq!(run_resp["result"]["status"], "running");

    // 2. session.attach — the replay burst alone may already contain the
    // whole run (the mock completes near-instantly with no network
    // latency), or only part of it, with the rest arriving live; either way
    // this collects the FULL set of event kinds observed for this session.
    let attach_resp = daemon
        .call(2, "session.attach", json!({"session_id": session_id}))
        .await;
    assert!(
        attach_resp["error"].is_null(),
        "attach failed: {attach_resp}"
    );
    let mut kinds: Vec<String> = attach_resp["result"]["events"]
        .as_array()
        .expect("attach must return a replay events array")
        .iter()
        .map(|e| {
            e["kind"]
                .as_str()
                .expect("kind must be a string")
                .to_string()
        })
        .collect();

    // 3. Keep reading live NDJSON lines until the terminal `session_done`
    // event has been observed — the mock script is finite and deterministic,
    // so this always terminates; `read_lines`' own bounded timeout is the
    // backstop against a genuine regression hanging the test.
    let mut iterations = 0;
    while !kinds.iter().any(|k| k == "session_done") {
        iterations += 1;
        assert!(
            iterations < 20,
            "gave up waiting for session_done after {iterations} read rounds; kinds so far: {kinds:?}"
        );
        let lines = daemon.read_lines(20).await;
        assert!(
            !lines.is_empty(),
            "timed out waiting for more events; kinds so far: {kinds:?}"
        );
        for line in &lines {
            if let Some(envelope) = find_session_event(line, &session_id) {
                kinds.push(
                    envelope["kind"]
                        .as_str()
                        .expect("kind must be a string")
                        .to_string(),
                );
            }
        }
    }

    // 4. The live tool-event stream (#2056's core deliverable) must show
    // BOTH the PM's `delegate_to_agent` dispatch and the delegated
    // engineer's own `bash` dispatch — proving in-process delegation's
    // activity is observable end-to-end, not just the top-level PM loop's.
    let tool_started = kinds.iter().filter(|k| *k == "tool_started").count();
    let tool_finished = kinds.iter().filter(|k| *k == "tool_finished").count();
    assert_eq!(
        tool_started, 2,
        "expected tool_started for delegate_to_agent + bash: {kinds:?}"
    );
    assert_eq!(
        tool_finished, 2,
        "expected tool_finished for delegate_to_agent + bash: {kinds:?}"
    );
    assert!(
        !kinds.iter().any(|k| k == "tool_error"),
        "the scripted mock run must complete without a fatal tool error: {kinds:?}"
    );

    // 5. session.status must reflect the terminal outcome.
    let status_resp = daemon
        .call(3, "session.status", json!({"session_id": session_id}))
        .await;
    assert!(
        status_resp["error"].is_null(),
        "status failed: {status_resp}"
    );
    assert_eq!(status_resp["result"]["status"], "finished");

    daemon.shutdown_via_eof_and_assert_clean_exit().await;
}

/// A second `task.run` against the SAME `session_id` while the first is
/// still executing must be rejected over the real wire — not just at the
/// `SessionRegistry` unit level (`task::executor::tests::spawn_task_run_rejects_second_overlapping_run`).
#[tokio::test]
async fn task_run_rejects_a_second_overlapping_run() {
    let project = project_with_agents();
    let mut daemon = StdioSession::spawn_with_mock_llm(project.path());

    // Use an explicit session_id (sessionful mode) so both calls target the
    // exact same session deterministically.
    let create_resp = daemon
        .call(1, "session.create", json!({"task": "e2e overlap task"}))
        .await;
    assert!(
        create_resp["error"].is_null(),
        "create failed: {create_resp}"
    );
    let session_id = create_resp["result"]["id"]
        .as_str()
        .expect("session.create must return an id")
        .to_string();

    let first = daemon
        .call(
            2,
            "task.run",
            json!({"task_description": "say hi", "session_id": session_id}),
        )
        .await;
    assert!(
        first["error"].is_null(),
        "first task.run must succeed: {first}"
    );

    let second = daemon
        .call(
            3,
            "task.run",
            json!({"task_description": "say hi again", "session_id": session_id}),
        )
        .await;
    assert!(
        second["error"].is_object(),
        "a second overlapping task.run must be rejected: {second}"
    );
    assert_eq!(second["error"]["code"], -32003);

    daemon.shutdown_via_eof_and_assert_clean_exit().await;
}

/// `task.run` -> (wait for completion) -> `session.get_transcript` must
/// expose the stored run record over the real wire: turns for BOTH the `pm`
/// and `python-engineer` roles, their `delegate_to_agent`/`bash` tool calls,
/// and non-zero aggregate usage + a priced cost (#2058).
#[tokio::test]
async fn task_run_then_get_transcript_exposes_turns_usage_and_cost() {
    let project = project_with_agents();
    let mut daemon = StdioSession::spawn_with_mock_llm(project.path());

    // `run_task_to_completion` reserves request ids 1 (task.run) and 2
    // (session.attach); this test's own next id is 3.
    let session_id = run_task_to_completion(&mut daemon, "say hi").await;

    let transcript_resp = daemon
        .call(
            3,
            "session.get_transcript",
            json!({"session_id": session_id}),
        )
        .await;
    assert!(
        transcript_resp["error"].is_null(),
        "get_transcript failed: {transcript_resp}"
    );
    let result = &transcript_resp["result"];
    assert_eq!(result["session_id"], session_id);

    let turns = result["turns"].as_array().expect("turns must be an array");
    assert!(
        !turns.is_empty(),
        "a completed run must have recorded turns"
    );

    let roles: Vec<&str> = turns.iter().map(|t| t["role"].as_str().unwrap()).collect();
    assert!(roles.contains(&"pm"), "expected a pm turn: {roles:?}");
    assert!(
        roles.contains(&"python-engineer"),
        "expected a python-engineer turn: {roles:?}"
    );

    let all_tool_calls: Vec<&str> = turns
        .iter()
        .flat_map(|t| t["tool_calls"].as_array().unwrap())
        .map(|c| c.as_str().unwrap())
        .collect();
    assert!(
        all_tool_calls.contains(&"delegate_to_agent"),
        "expected the pm's delegate_to_agent call in the transcript: {all_tool_calls:?}"
    );
    assert!(
        all_tool_calls.contains(&"bash"),
        "expected the engineer's bash call in the transcript: {all_tool_calls:?}"
    );

    // Aggregate usage/cost must be non-zero (the mock script's fixtures
    // carry non-zero token counts on every turn) — and must NOT be
    // recomputed here, only read back exactly as `task::executor` stored it.
    assert!(
        result["usage"]["prompt_tokens"].as_u64().unwrap() > 0,
        "expected non-zero aggregate prompt_tokens: {}",
        result["usage"]
    );
    assert!(
        result["usage"]["completion_tokens"].as_u64().unwrap() > 0,
        "expected non-zero aggregate completion_tokens: {}",
        result["usage"]
    );
    assert!(
        result["cost_usd"].as_f64().unwrap() > 0.0,
        "expected a priced, non-zero cost_usd: {}",
        result["cost_usd"]
    );

    daemon.shutdown_via_eof_and_assert_clean_exit().await;
}

// ── Projectless + the three binding states (spec DOC-39 §4.2/§5.5) ────────────

/// **The Bob-mandated state, end to end.** A daemon started with NO `--project`
/// must run a task to completion without panicking.
///
/// Why: this exact invocation was IMPOSSIBLE before — `tcode serve`'s
/// `--project` was a required `PathBuf` and `task.run`'s project a required
/// path, so the shell's entry screen (7a) had no reachable API state to render.
/// Both halves are proven here: the daemon starts projectless, and `task.run`
/// runs against it.
/// What: spawns projectless with `$HOME` pointed at a user-level agents fixture
/// (the documented projectless `agents_dir` fallback), runs a task to
/// completion, and asserts the session reports the `projectless` binding state
/// with a null root and finishes cleanly.
#[tokio::test]
async fn projectless_task_runs_end_to_end() {
    let home = support::home_with_user_level_agents();
    let mut daemon = StdioSession::spawn_projectless_with_mock_llm(home.path());

    let session_id = run_task_to_completion(&mut daemon, "just chat, no project").await;

    let status = daemon
        .call(3, "session.status", json!({"session_id": session_id}))
        .await;
    assert!(status["error"].is_null(), "session.status failed: {status}");
    let result = &status["result"];

    assert_eq!(
        result["binding"]["state"], "projectless",
        "a daemon started without --project must report the projectless binding: {result}"
    );
    assert!(
        result["binding"]["root"].is_null(),
        "projectless must carry a null root: {result}"
    );
    assert!(
        result["project"].is_null(),
        "projectless must have no derived project label: {result}"
    );
    assert_eq!(
        result["status"], "finished",
        "a projectless run must reach `finished`, not fail: {result}"
    );

    daemon.shutdown_via_eof_and_assert_clean_exit().await;
}

/// A NON-GIT directory must BIND (state `directory`) — it must NOT be treated
/// as projectless.
///
/// Why: this is the correction the spec makes to the design proposal, whose own
/// text says binding happens "the moment work touches files in a git repo".
/// That git-only rule would exclude the non-git working dirs (#2728) and temp
/// dirs (#2747) we deliberately ship. `project_with_agents` returns a plain
/// tempdir with no `.git`, so this asserts the shipped behaviour over the wire.
#[tokio::test]
async fn non_git_project_binds_as_directory_not_projectless() {
    let project = project_with_agents();
    let mut daemon = StdioSession::spawn_with_mock_llm(project.path());

    let session_id = run_task_to_completion(&mut daemon, "say hi").await;
    let status = daemon
        .call(3, "session.status", json!({"session_id": session_id}))
        .await;
    let result = &status["result"];

    assert_eq!(
        result["binding"]["state"], "directory",
        "a non-git dir MUST bind as `directory` — binding is not gated on .git: {result}"
    );
    assert_ne!(
        result["binding"]["state"], "projectless",
        "a non-git dir is NOT projectless: {result}"
    );
    assert!(
        !result["binding"]["root"].is_null(),
        "a bound non-git dir must carry its root: {result}"
    );
    assert!(
        !result["project"].is_null(),
        "a bound project must have a derived label: {result}"
    );

    daemon.shutdown_via_eof_and_assert_clean_exit().await;
}

/// A GIT repo must bind as `git_repo` — the third state, distinguished from a
/// plain directory so git-only affordances can be offered (and, for the other
/// two states, hidden rather than faked).
#[tokio::test]
async fn git_project_binds_as_git_repo() {
    let project = project_with_agents();
    let ok = std::process::Command::new("git")
        .arg("-C")
        .arg(project.path())
        .arg("init")
        .output()
        .expect("git init must run")
        .status
        .success();
    assert!(ok, "git init must succeed");

    let mut daemon = StdioSession::spawn_with_mock_llm(project.path());
    let session_id = run_task_to_completion(&mut daemon, "say hi").await;
    let status = daemon
        .call(3, "session.status", json!({"session_id": session_id}))
        .await;
    let result = &status["result"];

    assert_eq!(
        result["binding"]["state"], "git_repo",
        "a git worktree must bind as `git_repo`: {result}"
    );
    assert!(
        !result["binding"]["root"].is_null(),
        "a bound git repo must carry its root: {result}"
    );

    daemon.shutdown_via_eof_and_assert_clean_exit().await;
}