Skip to main content

trusty_code/task/
mock_llm.rs

1//! Deterministic, offline "echo" LLM client for #2056's mandatory offline
2//! testability (no live model, no API key).
3//!
4//! Why: task execution needs a live LLM in production, but the e2e/CI suite
5//! must exercise the FULL flow (create -> attach -> run -> live tool events
6//! -> done) without one. Setting `TCODE_MOCK_LLM=echo` (checked by
7//! [`build_llm_client`]) swaps this deterministic client in for the real
8//! `LlmClient` — the daemon still starts and serves `ping`/`health`/
9//! `session.*` fine with neither set; only `task.run` needs one or the
10//! other.
11//! What: [`EchoLlmClient`] replays a FIXED script exercising exactly the
12//! shape #2056 wires: the PM delegates once to `python-engineer`, which
13//! runs one `bash` tool call then stops, after which the PM sees the result
14//! and stops too. This is production code (not `#[cfg(test)]`) because the
15//! REAL `tcode` binary, spawned as a subprocess in `tests/task_e2e.rs`, must
16//! be able to construct it with no test harness in scope.
17//! Test: `task::mock_llm::tests::*`; exercised end-to-end (as a real
18//! subprocess) by `tests/task_e2e.rs`.
19
20use std::sync::Arc;
21use std::sync::atomic::{AtomicUsize, Ordering};
22
23use async_trait::async_trait;
24use serde_json::{Value, json};
25
26use crate::jsonrpc::RpcError;
27use crate::llm::{
28    ChatRequest, ChatResponse, DispatchingLlmClient, InferenceAdapter, InferenceError,
29};
30
31/// Environment variable selecting the mock LLM. Set to [`MOCK_LLM_ECHO`] to
32/// enable [`EchoLlmClient`] instead of a real OpenRouter client.
33pub const MOCK_LLM_ENV: &str = "TCODE_MOCK_LLM";
34
35/// The `TCODE_MOCK_LLM` value that selects [`EchoLlmClient`].
36pub const MOCK_LLM_ECHO: &str = "echo";
37
38/// The `TCODE_MOCK_LLM` value that selects [`FanoutEchoLlmClient`] (DOC-39
39/// AC-13).
40///
41/// Why: [`EchoLlmClient`]'s fixed script delegates to `python-engineer`
42/// exactly ONCE, which cannot exercise "two delegations to the SAME
43/// `agent_name`" — the acceptance proof AC-13 requires. A separate opt-in
44/// value keeps every existing `MOCK_LLM_ECHO` consumer (and its fixed
45/// 4-response script) byte-identical; only a test that explicitly asks for
46/// the fan-out shape sees it.
47pub const MOCK_LLM_ECHO_FANOUT: &str = "echo-fanout";
48
49/// The `TCODE_MOCK_LLM` value that selects [`RecallEchoLlmClient`] (DOC-39
50/// Slice C).
51///
52/// Why: neither [`EchoLlmClient`] nor [`FanoutEchoLlmClient`]'s scripts ever
53/// call `recall_session` — Slice C's e2e proof (recalled TEXT + `run_id`
54/// reaching `Event::MemoryRecalled` for a HELD-BACK result) needs the PM to
55/// issue that call against a mock trusty-memory backend, so this is its own
56/// opt-in value, same pattern as [`MOCK_LLM_ECHO_FANOUT`].
57pub const MOCK_LLM_ECHO_RECALL: &str = "echo-recall";
58
59/// The `TCODE_MOCK_LLM` value that selects [`SearchEchoLlmClient`] (DOC-39
60/// Slice B).
61///
62/// Why: neither [`EchoLlmClient`] nor [`FanoutEchoLlmClient`]'s scripts ever
63/// call `search_code` — the mandatory real-wire e2e proof that
64/// `Event::SearchPerformed.hits` carries real per-hit path/score data needs
65/// a script that does.
66pub const MOCK_LLM_ECHO_SEARCH: &str = "echo-search";
67
68/// The `TCODE_MOCK_LLM` value that selects [`SoakEchoLlmClient`] (issue
69/// #3869, epic #3866 Slice C).
70///
71/// Why: `task::protocol::task_run` rebuilds this `Arc<dyn InferenceAdapter>`
72/// fresh on EVERY `task.run` call, so the compression-effectiveness soak
73/// harness — which drives 200+ PM turns across many repeated `task.run`
74/// calls against one `session_id` — needs a script that ends cleanly
75/// (`SessionStatus::Finished`, resumable) within ONE call's turn budget,
76/// not a script that spans the whole soak. See
77/// `SoakEchoLlmClient`'s docs for why it ends every call in a bare `stop`.
78pub const MOCK_LLM_ECHO_SOAK: &str = "echo-soak";
79
80/// The `TCODE_MOCK_LLM` value that selects [`SoakLoadEchoLlmClient`] (epic
81/// #3866's load-realistic follow-up soak).
82///
83/// Why: [`MOCK_LLM_ECHO_SOAK`]'s own soak (PR #3887, issue #3869) proved the
84/// cadence mechanism functions but — per that soak's own report — never
85/// stressed the 60%-working-context-floor boundary: five of its six
86/// per-call turns carry near-empty arguments. This variant carries a
87/// realistically-sized payload (approximating a `git diff`/`grep`/`cargo
88/// test`-log dump) on every `set_goal` turn instead, so a single `task.run`
89/// call's turns actually approach/exceed the default overhead cap. Same
90/// resumable-`stop`-ending shape and reuse rationale as
91/// [`MOCK_LLM_ECHO_SOAK`] — see [`SoakLoadEchoLlmClient`]'s module docs.
92pub const MOCK_LLM_ECHO_SOAK_LOAD: &str = "echo-soak-load";
93
94/// Build the `Arc<dyn InferenceAdapter>` `task.run` executions share.
95///
96/// Why: the single seam that decides "real model or offline mock" — kept
97/// here (not inlined at each call site) so the decision is made exactly
98/// once and is easy to find.
99/// What: if [`MOCK_LLM_ENV`] is set to [`MOCK_LLM_ECHO`], returns an
100/// [`EchoLlmClient`]; if set to [`MOCK_LLM_ECHO_FANOUT`] (DOC-39 AC-13),
101/// returns a [`FanoutEchoLlmClient`]; if set to [`MOCK_LLM_ECHO_SEARCH`]
102/// (DOC-39 Slice B), returns a [`SearchEchoLlmClient`]; if set to
103/// [`MOCK_LLM_ECHO_SOAK`] (issue #3869), returns a [`SoakEchoLlmClient`].
104/// Otherwise builds a
105/// real `DispatchingLlmClient` — routing
106/// `bedrock/*` slugs to AWS Bedrock, `fireworks/*` to Fireworks, and everything
107/// else to OpenRouter (#1021 phase 1; #2406). Construction touches no
108/// credentials: the OpenAI-dialect providers resolve their key lazily via the
109/// shared env > `.env.local` > store chain at first use, and Bedrock uses the
110/// AWS credential chain — so a pure-Bedrock `task.run` is never blocked by a key
111/// it will never use (#2245). A missing key only surfaces (via
112/// `DispatchingLlmClient::chat` → an actionable error) when a model that needs
113/// it is actually dispatched.
114/// Test: `task::mock_llm::tests::mock_env_selects_echo_client`,
115/// `task::mock_llm::tests::real_client_builds_without_openrouter_key`.
116pub fn build_llm_client() -> Result<Arc<dyn InferenceAdapter>, RpcError> {
117    match std::env::var(MOCK_LLM_ENV).ok().as_deref() {
118        Some(MOCK_LLM_ECHO) => return Ok(Arc::new(EchoLlmClient::new())),
119        Some(MOCK_LLM_ECHO_FANOUT) => return Ok(Arc::new(FanoutEchoLlmClient::new())),
120        Some(MOCK_LLM_ECHO_RECALL) => return Ok(Arc::new(RecallEchoLlmClient::new())),
121        Some(MOCK_LLM_ECHO_SEARCH) => return Ok(Arc::new(SearchEchoLlmClient::new())),
122        Some(MOCK_LLM_ECHO_SOAK) => return Ok(Arc::new(SoakEchoLlmClient::new())),
123        Some(MOCK_LLM_ECHO_SOAK_LOAD) => return Ok(Arc::new(SoakLoadEchoLlmClient::new())),
124        _ => {}
125    }
126    Ok(Arc::new(DispatchingLlmClient::new()))
127}
128
129/// A deterministic, scripted `InferenceAdapter` for offline task-execution
130/// testing (#2056).
131///
132/// Why: exercises the SAME PM -> engineer -> tool -> engineer-stop ->
133/// PM-stop shape `run_task`'s own offline tests use, but as production code
134/// so the real daemon binary can drive it with no network access at all.
135/// What: an atomic cursor over a fixed 4-response script:
136///
137/// 1. PM calls `delegate_to_agent(python-engineer, ...)`.
138/// 2. Engineer calls `bash(command="echo hello-from-mock-engineer")`.
139/// 3. Engineer stops with final text.
140/// 4. PM stops with final text.
141///
142/// Running past the script's end returns an `InferenceError` rather than
143/// panicking, so a bug that adds an unexpected turn fails loudly instead of
144/// hanging.
145/// Test: `task::mock_llm::tests::script_drives_full_delegation_flow`.
146pub struct EchoLlmClient {
147    cursor: AtomicUsize,
148}
149
150impl EchoLlmClient {
151    /// Construct a fresh client at the start of its script.
152    pub fn new() -> Self {
153        Self {
154            cursor: AtomicUsize::new(0),
155        }
156    }
157}
158
159impl Default for EchoLlmClient {
160    fn default() -> Self {
161        Self::new()
162    }
163}
164
165#[async_trait]
166impl InferenceAdapter for EchoLlmClient {
167    crate::llm::mock_adapter_identity!("mock-echo");
168
169    async fn chat(&self, _req: &ChatRequest) -> Result<ChatResponse, InferenceError> {
170        let idx = self.cursor.fetch_add(1, Ordering::SeqCst);
171        let fixture = match idx {
172            0 => delegate_response(),
173            1 => bash_response(),
174            2 => stop_response("engineer: echoed hello-from-mock-engineer"),
175            3 => stop_response("pm: task complete"),
176            _ => {
177                return Err(InferenceError::MissingConfig(format!(
178                    "EchoLlmClient script exhausted at call {idx}"
179                )));
180            }
181        };
182        serde_json::from_value(fixture).map_err(|e| {
183            InferenceError::MissingConfig(format!("EchoLlmClient: invalid scripted fixture: {e}"))
184        })
185    }
186}
187
188/// Turn 1 fixture: the PM delegates to `python-engineer`.
189fn delegate_response() -> Value {
190    json!({
191        "id": "mock-delegate",
192        "choices": [{
193            "message": {
194                "role": "assistant",
195                "content": null,
196                "tool_calls": [{
197                    "id": "call-delegate",
198                    "type": "function",
199                    "function": {
200                        "name": "delegate_to_agent",
201                        "arguments": json!({"agent_name": "python-engineer", "task": "echo a greeting"}).to_string()
202                    }
203                }]
204            },
205            "finish_reason": "tool_calls"
206        }],
207        "usage": {"prompt_tokens": 40, "completion_tokens": 10, "total_tokens": 50}
208    })
209}
210
211/// Turn 2 fixture: the engineer runs a single, known, side-effect-free `bash`
212/// command.
213fn bash_response() -> Value {
214    json!({
215        "id": "mock-bash",
216        "choices": [{
217            "message": {
218                "role": "assistant",
219                "content": null,
220                "tool_calls": [{
221                    "id": "call-bash",
222                    "type": "function",
223                    "function": {
224                        "name": "bash",
225                        "arguments": json!({"command": "echo hello-from-mock-engineer"}).to_string()
226                    }
227                }]
228            },
229            "finish_reason": "tool_calls"
230        }],
231        "usage": {"prompt_tokens": 20, "completion_tokens": 8, "total_tokens": 28}
232    })
233}
234
235/// A no-tool-call final-answer fixture (turns 3 and 4).
236fn stop_response(text: &str) -> Value {
237    json!({
238        "id": "mock-stop",
239        "choices": [{
240            "message": {"role": "assistant", "content": text, "tool_calls": []},
241            "finish_reason": "stop"
242        }],
243        "usage": {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15}
244    })
245}
246
247/// A deterministic, scripted `InferenceAdapter` exercising a FAN-OUT to two
248/// concurrently-delegated `python-engineer` sub-agents (DOC-39 AC-13's
249/// acceptance proof).
250///
251/// Why: [`EchoLlmClient`]'s fixed script delegates to `python-engineer`
252/// exactly once, so it cannot prove the fix this ticket ships — that TWO
253/// delegations to the SAME `agent_name` mint DISTINCT `agent_id`s. This
254/// client scripts the PM issuing both `delegate_to_agent` calls in ONE
255/// assistant turn (a genuine tool-calls fan-out); `agent_loop::dispatch_all`
256/// still dispatches them one after another (there is no concurrent-execution
257/// primitive in the loop itself), but each dispatch re-enters
258/// `runner::in_process::InProcessAgentRunner::run_pipeline` — the ONE
259/// production call site that mints a fresh UUID v4 per spawn — so the
260/// two engineer sub-loops still get their OWN `agent_id` even though they run
261/// sequentially. That is exactly what AC-13 requires: `agent_name` alone
262/// cannot distinguish the two, `agent_id` can.
263/// What: an atomic cursor over a fixed 6-response script:
264///
265/// 1. PM's ONE assistant turn issues TWO `delegate_to_agent` tool calls, both
266///    targeting `python-engineer` (`call-delegate-a`, `call-delegate-b`).
267/// 2. Engineer A calls `bash(command="echo hello-from-engineer-a")`.
268/// 3. Engineer A stops with final text.
269/// 4. Engineer B calls `bash(command="echo hello-from-engineer-b")`.
270/// 5. Engineer B stops with final text.
271/// 6. PM stops with final text.
272///
273/// Running past the script's end returns an `InferenceError` rather than panicking.
274/// Test: `task::mock_llm::tests::fanout_script_drives_two_delegations_to_the_same_agent`;
275/// exercised end-to-end (as a real subprocess) by `tests/agent_id_e2e.rs`.
276pub struct FanoutEchoLlmClient {
277    cursor: AtomicUsize,
278}
279
280impl FanoutEchoLlmClient {
281    /// Construct a fresh client at the start of its script.
282    pub fn new() -> Self {
283        Self {
284            cursor: AtomicUsize::new(0),
285        }
286    }
287}
288
289impl Default for FanoutEchoLlmClient {
290    fn default() -> Self {
291        Self::new()
292    }
293}
294
295#[async_trait]
296impl InferenceAdapter for FanoutEchoLlmClient {
297    crate::llm::mock_adapter_identity!("mock-fanout-echo");
298
299    async fn chat(&self, _req: &ChatRequest) -> Result<ChatResponse, InferenceError> {
300        let idx = self.cursor.fetch_add(1, Ordering::SeqCst);
301        let fixture = match idx {
302            0 => fanout_delegate_response(),
303            1 => bash_response_named("call-bash-a", "echo hello-from-engineer-a"),
304            2 => stop_response("engineer A: done"),
305            3 => bash_response_named("call-bash-b", "echo hello-from-engineer-b"),
306            4 => stop_response("engineer B: done"),
307            5 => stop_response("pm: fan-out complete"),
308            _ => {
309                return Err(InferenceError::MissingConfig(format!(
310                    "FanoutEchoLlmClient script exhausted at call {idx}"
311                )));
312            }
313        };
314        serde_json::from_value(fixture).map_err(|e| {
315            InferenceError::MissingConfig(format!(
316                "FanoutEchoLlmClient: invalid scripted fixture: {e}"
317            ))
318        })
319    }
320}
321
322/// Turn 1 fixture: the PM's ONE assistant turn fans out to `python-engineer`
323/// TWICE — the two-tool-calls-in-one-turn shape `FanoutEchoLlmClient` needs.
324fn fanout_delegate_response() -> Value {
325    json!({
326        "id": "mock-fanout-delegate",
327        "choices": [{
328            "message": {
329                "role": "assistant",
330                "content": null,
331                "tool_calls": [
332                    {
333                        "id": "call-delegate-a",
334                        "type": "function",
335                        "function": {
336                            "name": "delegate_to_agent",
337                            "arguments": json!({"agent_name": "python-engineer", "task": "task A"}).to_string()
338                        }
339                    },
340                    {
341                        "id": "call-delegate-b",
342                        "type": "function",
343                        "function": {
344                            "name": "delegate_to_agent",
345                            "arguments": json!({"agent_name": "python-engineer", "task": "task B"}).to_string()
346                        }
347                    }
348                ]
349            },
350            "finish_reason": "tool_calls"
351        }],
352        "usage": {"prompt_tokens": 50, "completion_tokens": 20, "total_tokens": 70}
353    })
354}
355
356/// Like [`bash_response`] but with a caller-chosen `call_id`/command, so the
357/// fan-out script can distinguish engineer A's and engineer B's `bash` calls.
358fn bash_response_named(call_id: &str, command: &str) -> Value {
359    json!({
360        "id": "mock-bash",
361        "choices": [{
362            "message": {
363                "role": "assistant",
364                "content": null,
365                "tool_calls": [{
366                    "id": call_id,
367                    "type": "function",
368                    "function": {
369                        "name": "bash",
370                        "arguments": json!({"command": command}).to_string()
371                    }
372                }]
373            },
374            "finish_reason": "tool_calls"
375        }],
376        "usage": {"prompt_tokens": 20, "completion_tokens": 8, "total_tokens": 28}
377    })
378}
379
380/// A deterministic, scripted `InferenceAdapter` exercising the PM calling
381/// `recall_session` (DOC-39 Slice C's e2e proof).
382///
383/// Why: [`EchoLlmClient`] and [`FanoutEchoLlmClient`]'s scripts never call
384/// `recall_session`, so neither can drive the wire proof that a HELD-BACK
385/// recall result's actual TEXT (not just its score) reaches
386/// `Event::MemoryRecalled`. This script has the PM call `recall_session`
387/// exactly once, then stop — `tests/recall_content_e2e.rs` pairs it with a
388/// mock trusty-memory backend (`TRUSTY_MEMORY_SOCKET` override) that returns one
389/// huge, high-scored result and one small, lower-scored result so the tool's
390/// own token budget drops the second one whole (mirroring
391/// `tools::recall_session`'s own budget tests) — the held-back case this
392/// slice must prove survives onto the wire.
393/// What: an atomic cursor over a fixed 2-response script:
394///
395/// 1. PM calls `recall_session(query="pkce oauth flow")`.
396/// 2. PM stops with final text.
397///
398/// Running past the script's end returns an `InferenceError` rather than panicking.
399/// Test: `task::mock_llm::tests::recall_script_drives_a_single_recall_call`;
400/// exercised end-to-end (as a real subprocess) by
401/// `tests/recall_content_e2e.rs`.
402pub struct RecallEchoLlmClient {
403    cursor: AtomicUsize,
404}
405
406impl RecallEchoLlmClient {
407    /// Construct a fresh client at the start of its script.
408    pub fn new() -> Self {
409        Self {
410            cursor: AtomicUsize::new(0),
411        }
412    }
413}
414
415impl Default for RecallEchoLlmClient {
416    fn default() -> Self {
417        Self::new()
418    }
419}
420
421#[async_trait]
422impl InferenceAdapter for RecallEchoLlmClient {
423    crate::llm::mock_adapter_identity!("mock-recall-echo");
424
425    async fn chat(&self, _req: &ChatRequest) -> Result<ChatResponse, InferenceError> {
426        let idx = self.cursor.fetch_add(1, Ordering::SeqCst);
427        let fixture = match idx {
428            0 => recall_response(),
429            1 => stop_response("pm: recalled what I needed"),
430            _ => {
431                return Err(InferenceError::MissingConfig(format!(
432                    "RecallEchoLlmClient script exhausted at call {idx}"
433                )));
434            }
435        };
436        serde_json::from_value(fixture).map_err(|e| {
437            InferenceError::MissingConfig(format!(
438                "RecallEchoLlmClient: invalid scripted fixture: {e}"
439            ))
440        })
441    }
442}
443
444/// Turn 1 fixture: the PM calls `recall_session` once.
445fn recall_response() -> Value {
446    json!({
447        "id": "mock-recall",
448        "choices": [{
449            "message": {
450                "role": "assistant",
451                "content": null,
452                "tool_calls": [{
453                    "id": "call-recall",
454                    "type": "function",
455                    "function": {
456                        "name": "recall_session",
457                        "arguments": json!({"query": "pkce oauth flow"}).to_string()
458                    }
459                }]
460            },
461            "finish_reason": "tool_calls"
462        }],
463        "usage": {"prompt_tokens": 30, "completion_tokens": 10, "total_tokens": 40}
464    })
465}
466
467/// A deterministic, scripted `InferenceAdapter` exercising the engineer's
468/// `search_code` tool (DOC-39 Slice B's mandatory real-wire e2e proof that
469/// `Event::SearchPerformed.hits` carries real per-hit path/score data, not
470/// just a count).
471///
472/// Why: [`EchoLlmClient`]'s script only ever calls `bash`, so it cannot drive
473/// `search_code` at all. This client's fixed script is otherwise identical
474/// in shape (delegate once, one tool call, two stops) so it composes with
475/// the same daemon-driving harness `tests/task_e2e.rs` already uses.
476/// What: an atomic cursor over a fixed 4-response script:
477///
478/// 1. PM calls `delegate_to_agent(python-engineer, ...)`.
479/// 2. Engineer calls `search_code(query="where does auth live", mode="semantic")`.
480/// 3. Engineer stops with final text.
481/// 4. PM stops with final text.
482///
483/// Running past the script's end returns an `InferenceError` rather than
484/// panicking, mirroring [`EchoLlmClient`].
485/// Test: `task::mock_llm::tests::search_script_drives_full_delegation_flow`;
486/// exercised end-to-end (as a real subprocess, against a fake trusty-search
487/// MCP binary) by `tests/search_hits_e2e.rs`.
488pub struct SearchEchoLlmClient {
489    cursor: AtomicUsize,
490}
491
492impl SearchEchoLlmClient {
493    /// Construct a fresh client at the start of its script.
494    pub fn new() -> Self {
495        Self {
496            cursor: AtomicUsize::new(0),
497        }
498    }
499}
500
501impl Default for SearchEchoLlmClient {
502    fn default() -> Self {
503        Self::new()
504    }
505}
506
507#[async_trait]
508impl InferenceAdapter for SearchEchoLlmClient {
509    crate::llm::mock_adapter_identity!("mock-search-echo");
510
511    async fn chat(&self, _req: &ChatRequest) -> Result<ChatResponse, InferenceError> {
512        let idx = self.cursor.fetch_add(1, Ordering::SeqCst);
513        let fixture = match idx {
514            0 => delegate_response(),
515            1 => search_code_response(),
516            2 => stop_response("engineer: found it"),
517            3 => stop_response("pm: task complete"),
518            _ => {
519                return Err(InferenceError::MissingConfig(format!(
520                    "SearchEchoLlmClient script exhausted at call {idx}"
521                )));
522            }
523        };
524        serde_json::from_value(fixture).map_err(|e| {
525            InferenceError::MissingConfig(format!(
526                "SearchEchoLlmClient: invalid scripted fixture: {e}"
527            ))
528        })
529    }
530}
531
532/// Turn 2 fixture (search variant): the engineer calls `search_code` instead
533/// of `bash` — the whole reason [`SearchEchoLlmClient`] exists.
534fn search_code_response() -> Value {
535    json!({
536        "id": "mock-search",
537        "choices": [{
538            "message": {
539                "role": "assistant",
540                "content": null,
541                "tool_calls": [{
542                    "id": "call-search",
543                    "type": "function",
544                    "function": {
545                        "name": "search_code",
546                        "arguments": json!({"query": "where does auth live", "mode": "semantic"}).to_string()
547                    }
548                }]
549            },
550            "finish_reason": "tool_calls"
551        }],
552        "usage": {"prompt_tokens": 20, "completion_tokens": 8, "total_tokens": 28}
553    })
554}
555
556/// [`SoakEchoLlmClient`] (issue #3869's unbounded soak script), split into
557/// its own file purely to keep this production file under the crate's
558/// 500-SLOC cap — same rationale as `session::registry`'s `events`/
559/// `memory_sink_ext` child modules.
560#[path = "mock_llm_soak.rs"]
561mod mock_llm_soak;
562pub use mock_llm_soak::SoakEchoLlmClient;
563
564/// [`SoakLoadEchoLlmClient`] (epic #3866 load-realistic follow-up soak),
565/// split into its own file for the same 500-SLOC-cap reason as
566/// `mock_llm_soak` above.
567#[path = "mock_llm_soak_load.rs"]
568mod mock_llm_soak_load;
569pub use mock_llm_soak_load::SoakLoadEchoLlmClient;
570
571/// Serializes every test in this crate that sets/reads the process-wide
572/// [`MOCK_LLM_ENV`] var — `cargo test` runs tests in parallel within one
573/// binary, and an unguarded `set_var`/`remove_var` pair would race across
574/// modules (both here and in `task::protocol::tests`/`serve::tests`). A
575/// `tokio::sync::Mutex` (not `std::sync::Mutex`) because every caller holds
576/// the guard across an `.await` (the router dispatch the env var must stay
577/// set for) — clippy's `await_holding_lock` correctly flags a std mutex held
578/// that way.
579#[cfg(test)]
580pub(crate) static MOCK_LLM_ENV_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
581
582#[cfg(test)]
583mod tests {
584    use super::*;
585
586    /// The script must drive exactly the delegate -> bash -> stop -> stop
587    /// shape #2056's executor relies on.
588    #[tokio::test]
589    async fn script_drives_full_delegation_flow() {
590        let client = EchoLlmClient::new();
591        let req = ChatRequest {
592            model: "mock".to_string(),
593            messages: vec![],
594            temperature: None,
595            max_tokens: None,
596            tools: None,
597            tool_choice: None,
598            usage: None,
599            stop: None,
600        };
601
602        let turn1 = client.chat(&req).await.expect("turn 1");
603        assert_eq!(
604            turn1.first_tool_calls()[0].function.name,
605            "delegate_to_agent"
606        );
607
608        let turn2 = client.chat(&req).await.expect("turn 2");
609        assert_eq!(turn2.first_tool_calls()[0].function.name, "bash");
610
611        let turn3 = client.chat(&req).await.expect("turn 3");
612        assert!(turn3.first_tool_calls().is_empty());
613
614        let turn4 = client.chat(&req).await.expect("turn 4");
615        assert!(turn4.first_tool_calls().is_empty());
616
617        let err = client.chat(&req).await;
618        assert!(err.is_err(), "the script must not silently repeat");
619    }
620
621    /// (DOC-39 AC-13) The fan-out script must drive exactly the
622    /// two-delegate -> bash A -> stop A -> bash B -> stop B -> pm-stop shape
623    /// `tests/agent_id_e2e.rs` relies on.
624    #[tokio::test]
625    async fn fanout_script_drives_two_delegations_to_the_same_agent() {
626        let client = FanoutEchoLlmClient::new();
627        let req = ChatRequest {
628            model: "mock".to_string(),
629            messages: vec![],
630            temperature: None,
631            max_tokens: None,
632            tools: None,
633            tool_choice: None,
634            usage: None,
635            stop: None,
636        };
637
638        let turn1 = client.chat(&req).await.expect("turn 1");
639        let calls = turn1.first_tool_calls();
640        assert_eq!(calls.len(), 2, "the PM must fan out to TWO delegations");
641        assert!(calls.iter().all(|c| c.function.name == "delegate_to_agent"));
642        assert!(
643            calls
644                .iter()
645                .all(|c| c.function.arguments.contains("python-engineer")),
646            "both delegations must target the SAME agent_name"
647        );
648
649        let turn2 = client.chat(&req).await.expect("turn 2 (engineer A bash)");
650        assert_eq!(turn2.first_tool_calls()[0].function.name, "bash");
651
652        let turn3 = client.chat(&req).await.expect("turn 3 (engineer A stop)");
653        assert!(turn3.first_tool_calls().is_empty());
654
655        let turn4 = client.chat(&req).await.expect("turn 4 (engineer B bash)");
656        assert_eq!(turn4.first_tool_calls()[0].function.name, "bash");
657
658        let turn5 = client.chat(&req).await.expect("turn 5 (engineer B stop)");
659        assert!(turn5.first_tool_calls().is_empty());
660
661        let turn6 = client.chat(&req).await.expect("turn 6 (pm stop)");
662        assert!(turn6.first_tool_calls().is_empty());
663
664        let err = client.chat(&req).await;
665        assert!(err.is_err(), "the script must not silently repeat");
666    }
667
668    /// (DOC-39 Slice C) The recall script must drive exactly the
669    /// recall -> stop shape `tests/recall_content_e2e.rs` relies on.
670    #[tokio::test]
671    async fn recall_script_drives_a_single_recall_call() {
672        let client = RecallEchoLlmClient::new();
673        let req = ChatRequest {
674            model: "mock".to_string(),
675            messages: vec![],
676            temperature: None,
677            max_tokens: None,
678            tools: None,
679            tool_choice: None,
680            usage: None,
681            stop: None,
682        };
683
684        let turn1 = client.chat(&req).await.expect("turn 1");
685        let calls = turn1.first_tool_calls();
686        assert_eq!(calls.len(), 1);
687        assert_eq!(calls[0].function.name, "recall_session");
688        assert!(calls[0].function.arguments.contains("pkce"));
689
690        let turn2 = client.chat(&req).await.expect("turn 2 (pm stop)");
691        assert!(turn2.first_tool_calls().is_empty());
692
693        let err = client.chat(&req).await;
694        assert!(err.is_err(), "the script must not silently repeat");
695    }
696
697    /// (DOC-39 Slice B) The search script must drive exactly the
698    /// delegate -> search_code -> stop -> stop shape
699    /// `tests/search_hits_e2e.rs` relies on.
700    #[tokio::test]
701    async fn search_script_drives_full_delegation_flow() {
702        let client = SearchEchoLlmClient::new();
703        let req = ChatRequest {
704            model: "mock".to_string(),
705            messages: vec![],
706            temperature: None,
707            max_tokens: None,
708            tools: None,
709            tool_choice: None,
710            usage: None,
711            stop: None,
712        };
713
714        let turn1 = client.chat(&req).await.expect("turn 1");
715        assert_eq!(
716            turn1.first_tool_calls()[0].function.name,
717            "delegate_to_agent"
718        );
719
720        let turn2 = client.chat(&req).await.expect("turn 2");
721        assert_eq!(turn2.first_tool_calls()[0].function.name, "search_code");
722
723        let turn3 = client.chat(&req).await.expect("turn 3");
724        assert!(turn3.first_tool_calls().is_empty());
725
726        let turn4 = client.chat(&req).await.expect("turn 4");
727        assert!(turn4.first_tool_calls().is_empty());
728
729        let err = client.chat(&req).await;
730        assert!(err.is_err(), "the script must not silently repeat");
731    }
732
733    /// `build_llm_client` must select the echo client when the env var is set.
734    #[tokio::test]
735    async fn mock_env_selects_echo_client() {
736        let _guard = MOCK_LLM_ENV_LOCK.lock().await;
737        // SAFETY: test-only env mutation; serialized by `MOCK_LLM_ENV_LOCK`.
738        unsafe {
739            std::env::set_var(MOCK_LLM_ENV, MOCK_LLM_ECHO);
740        }
741        let result = build_llm_client();
742        unsafe {
743            std::env::remove_var(MOCK_LLM_ENV);
744        }
745        assert!(result.is_ok(), "echo mode must never fail to construct");
746    }
747
748    /// `build_llm_client` must succeed even when `OPENROUTER_API_KEY` is
749    /// unset and mock mode is off — the real daemon `task.run` path a
750    /// pure-Bedrock run takes (#2245).
751    ///
752    /// Why: This is the exact function the default (non-`--legacy-in-process`)
753    /// `tcode run-task` path calls inside the daemon; pinning the fix here,
754    /// not just in `main.rs`, covers both entry points the smoke test's root
755    /// cause named.
756    /// What: Locks out `mock_env_selects_echo_client` (both mutate process
757    /// env), unsets `OPENROUTER_API_KEY`, asserts `Ok`.
758    /// Test: this test.
759    #[tokio::test]
760    async fn real_client_builds_without_openrouter_key() {
761        let _guard = MOCK_LLM_ENV_LOCK.lock().await;
762        let prev = std::env::var("OPENROUTER_API_KEY").ok();
763        // SAFETY: test-only env mutation; serialized by `MOCK_LLM_ENV_LOCK`
764        // (every test touching process-wide LLM-selection env vars in this
765        // module takes that lock, so this is safe alongside them too).
766        unsafe {
767            std::env::remove_var("OPENROUTER_API_KEY");
768        }
769        let result = build_llm_client();
770        if let Some(key) = prev {
771            // SAFETY: see above.
772            unsafe {
773                std::env::set_var("OPENROUTER_API_KEY", key);
774            }
775        }
776        assert!(
777            result.is_ok(),
778            "expected Ok when OPENROUTER_API_KEY is unset, got err: {:?}",
779            result.err()
780        );
781    }
782}