zeph-core 0.22.1

Core agent loop, configuration, context builder, metrics, and vault for Zeph
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
// SPDX-FileCopyrightText: 2026 Andrei G <bug-ops>
// SPDX-License-Identifier: MIT OR Apache-2.0

#![cfg(feature = "scheduler")]

use std::sync::Mutex;

use zeph_llm::any::AnyProvider;
use zeph_llm::mock::MockProvider;
use zeph_llm::provider::{ChatResponse, ToolUseRequest};
use zeph_tools::executor::{ToolCall, ToolError, ToolExecutor, ToolOutput};

use crate::agent::Agent;
use crate::agent::agent_tests::{MockChannel, create_test_registry};

/// A `ToolExecutor` that responds to `execute_tool_call` with a fixed output sequence.
struct CallableToolExecutor {
    outputs: Mutex<Vec<Result<Option<ToolOutput>, ToolError>>>,
}

impl CallableToolExecutor {
    fn new(outputs: Vec<Result<Option<ToolOutput>, ToolError>>) -> Self {
        Self {
            outputs: Mutex::new(outputs),
        }
    }

    fn fixed_output(summary: &str) -> Self {
        Self::new(vec![Ok(Some(ToolOutput {
            tool_name: "test_tool".into(),
            summary: summary.to_owned(),
            blocks_executed: 1,
            filter_stats: None,
            diff: None,
            streamed: false,
            terminal_id: None,
            locations: None,
            raw_response: None,
            claim_source: None,
            ..Default::default()
        }))])
    }

    fn failing() -> Self {
        Self::new(vec![Err(ToolError::InvalidParams {
            message: "tool failed".into(),
        })])
    }
}

impl ToolExecutor for CallableToolExecutor {
    async fn execute(&self, _response: &str) -> Result<Option<ToolOutput>, ToolError> {
        Ok(None)
    }

    async fn execute_tool_call(&self, _call: &ToolCall) -> Result<Option<ToolOutput>, ToolError> {
        let mut outputs = self.outputs.lock().unwrap();
        if outputs.is_empty() {
            Ok(None)
        } else {
            outputs.remove(0)
        }
    }

    zeph_tools::tool_executor_no_inner_defaults!();
}

fn tool_use_response(tool_id: &str, tool_name: &str) -> ChatResponse {
    ChatResponse::ToolUse {
        text: None,
        tool_calls: vec![ToolUseRequest {
            id: tool_id.to_owned(),
            name: tool_name.into(),
            input: serde_json::json!({"arg": "val"}),
        }],
        thinking_blocks: vec![],
    }
}

#[tokio::test]
async fn text_only_response_returns_immediately() {
    let (mock, _counter) =
        MockProvider::default().with_tool_use(vec![ChatResponse::Text("the answer".into())]);
    let provider = AnyProvider::Mock(mock);
    let channel = MockChannel::new(vec![]);
    let registry = create_test_registry();
    let executor = CallableToolExecutor::new(vec![]);

    let mut agent = Agent::new(provider, channel, registry, None, 5, executor);
    let result = agent.run_inline_tool_loop("what is 2+2?", 10).await;

    assert_eq!(result.unwrap().text, "the answer");
}

#[tokio::test]
async fn single_tool_iteration_returns_final_text() {
    let (mock, counter) = MockProvider::default().with_tool_use(vec![
        tool_use_response("call-1", "test_tool"),
        ChatResponse::Text("done".into()),
    ]);
    let provider = AnyProvider::Mock(mock);
    let channel = MockChannel::new(vec![]);
    let registry = create_test_registry();
    let executor = CallableToolExecutor::fixed_output("tool result");

    let mut agent = Agent::new(provider, channel, registry, None, 5, executor);
    let result = agent.run_inline_tool_loop("run a tool", 10).await;

    assert_eq!(result.unwrap().text, "done");
    assert_eq!(*counter.lock().unwrap(), 2);
}

#[tokio::test]
async fn loop_terminates_at_max_iterations() {
    // Provider always returns ToolUse — loop must stop after max_iterations.
    let responses: Vec<ChatResponse> = (0..25)
        .map(|i| tool_use_response(&format!("call-{i}"), "test_tool"))
        .collect();
    let (mock, counter) = MockProvider::default().with_tool_use(responses);
    let provider = AnyProvider::Mock(mock);
    let channel = MockChannel::new(vec![]);
    let registry = create_test_registry();
    let executor = CallableToolExecutor::fixed_output("ok");

    let max_iter = 5usize;
    let mut agent = Agent::new(provider, channel, registry, None, 5, executor);
    let result = agent.run_inline_tool_loop("loop forever", max_iter).await;

    // Must return Ok (not panic or hang) and have called the provider exactly max_iter times.
    assert!(result.is_ok());
    assert_eq!(*counter.lock().unwrap(), u32::try_from(max_iter).unwrap());
}

#[tokio::test]
async fn tool_error_produces_is_error_result_and_loop_continues() {
    // First call: ToolUse with a failing executor → ToolResult with is_error=true.
    // Second call: Text → loop ends.
    // We verify the loop continues (doesn't abort) and returns the final text.
    let (mock, _counter) = MockProvider::default().with_tool_use(vec![
        tool_use_response("call-err", "test_tool"),
        ChatResponse::Text("recovered".into()),
    ]);
    let provider = AnyProvider::Mock(mock);
    let channel = MockChannel::new(vec![]);
    let registry = create_test_registry();
    let executor = CallableToolExecutor::failing();

    let mut agent = Agent::new(provider, channel, registry, None, 5, executor);
    let result = agent.run_inline_tool_loop("trigger error", 10).await;

    assert_eq!(result.unwrap().text, "recovered");
}

#[tokio::test]
async fn multiple_tool_iterations_before_text() {
    // Two ToolUse rounds, then Text. Verifies the loop handles chained tool calls.
    let (mock, counter) = MockProvider::default().with_tool_use(vec![
        tool_use_response("call-1", "test_tool"),
        tool_use_response("call-2", "test_tool"),
        ChatResponse::Text("all done".into()),
    ]);
    let provider = AnyProvider::Mock(mock);
    let channel = MockChannel::new(vec![]);
    let registry = create_test_registry();
    // Need two successful outputs for the two tool calls.
    let executor = CallableToolExecutor::new(vec![
        Ok(Some(ToolOutput {
            tool_name: "test_tool".into(),
            summary: "result-1".into(),
            blocks_executed: 1,
            filter_stats: None,
            diff: None,
            streamed: false,
            terminal_id: None,
            locations: None,
            raw_response: None,
            claim_source: None,
            ..Default::default()
        })),
        Ok(Some(ToolOutput {
            tool_name: "test_tool".into(),
            summary: "result-2".into(),
            blocks_executed: 1,
            filter_stats: None,
            diff: None,
            streamed: false,
            terminal_id: None,
            locations: None,
            raw_response: None,
            claim_source: None,
            ..Default::default()
        })),
    ]);

    let mut agent = Agent::new(provider, channel, registry, None, 5, executor);
    let result = agent
        .run_inline_tool_loop("two tools then answer", 10)
        .await
        .unwrap();

    assert_eq!(result.text, "all done");
    assert_eq!(*counter.lock().unwrap(), 3);

    // AC-8 (spec 009 § Verifier Tool-Call Grounding): the in-loop-collected tool_trace must
    // contain both tool calls in order, not just the narrated text.
    assert_eq!(result.tool_trace.len(), 2);
    assert!(result.tool_trace.iter().all(|t| t.tool == "test_tool"));
    assert!(result.tool_trace.iter().all(|t| t.ok));
    assert!(
        result
            .tool_trace
            .iter()
            .all(|t| t.args_summary.as_deref() == Some("val"))
    );
}

#[tokio::test]
async fn provider_error_is_propagated() {
    // MockProvider::failing() makes chat_with_tools return Err via the fallback chat() path.
    let provider = AnyProvider::Mock(zeph_llm::mock::MockProvider::failing());
    let channel = MockChannel::new(vec![]);
    let registry = create_test_registry();
    let executor = CallableToolExecutor::new(vec![]);

    let mut agent = Agent::new(provider, channel, registry, None, 5, executor);
    let result = agent.run_inline_tool_loop("this will fail", 10).await;

    assert!(result.is_err());
}

// Regression test for #6030 S1 (critic finding): `handle_run_inline_action` wraps
// `self.tool_executor` with `NetworkDenyToolExecutor` for the duration of a single inline
// turn when the task carries `NetworkScope::Deny`, since `RunInline` tasks share the
// parent agent's own tool loop (no per-spawn executor to wrap, unlike spawned sub-agents).
// This test exercises that exact mechanism directly against `run_inline_tool_loop` — the
// same call `handle_run_inline_action` awaits — proving the `fetch` tool call never
// reaches the inner executor once wrapped.
#[tokio::test]
async fn network_deny_wrapped_executor_blocks_fetch_before_reaching_inner() {
    use std::sync::Arc;
    use std::sync::atomic::{AtomicBool, Ordering};

    struct FlaggingExecutor {
        called: Arc<AtomicBool>,
    }

    impl ToolExecutor for FlaggingExecutor {
        async fn execute(&self, _response: &str) -> Result<Option<ToolOutput>, ToolError> {
            Ok(None)
        }

        async fn execute_tool_call(
            &self,
            _call: &ToolCall,
        ) -> Result<Option<ToolOutput>, ToolError> {
            self.called.store(true, Ordering::SeqCst);
            Ok(Some(ToolOutput {
                tool_name: "fetch".into(),
                summary: "should not be reached".into(),
                blocks_executed: 1,
                filter_stats: None,
                diff: None,
                streamed: false,
                terminal_id: None,
                locations: None,
                raw_response: None,
                claim_source: None,
                ..Default::default()
            }))
        }

        zeph_tools::tool_executor_no_inner_defaults!();
    }

    let (mock, _counter) = MockProvider::default().with_tool_use(vec![
        tool_use_response("call-1", "fetch"),
        ChatResponse::Text("done".into()),
    ]);
    let provider = AnyProvider::Mock(mock);
    let channel = MockChannel::new(vec![]);
    let registry = create_test_registry();
    let called = Arc::new(AtomicBool::new(false));
    let executor = FlaggingExecutor {
        called: called.clone(),
    };

    let mut agent = Agent::new(provider, channel, registry, None, 5, executor);
    // Simulate the swap `handle_run_inline_action` performs when `network_denied_for_task`
    // returns `true` for the dispatched task.
    agent.tool_executor = Arc::new(zeph_subagent::NetworkDenyToolExecutor::new(
        agent.tool_executor.clone(),
    ));

    let result = agent.run_inline_tool_loop("fetch a url", 10).await;

    assert_eq!(result.unwrap().text, "done");
    assert!(
        !called.load(Ordering::SeqCst),
        "fetch tool call must be blocked before reaching the inner executor"
    );
}

// Regression test for issue #2542: elicitation deadlock in run_inline_tool_loop.
//
// The real deadlock scenario: MCP tool sends an elicitation event and then blocks
// waiting for the agent to respond via response_tx. Meanwhile execute_tool_call_erased
// also blocks waiting for the MCP tool — neither side makes progress.
//
// The fix: select! concurrently drains elicitation_rx while awaiting the tool result.
//
// Test design: BlockingElicitingExecutor sends an elicitation event then blocks on
// `unblock_rx` (a oneshot whose sender is never signalled — it stays pending until
// the future is cancelled). When select! picks the elicitation branch it cancels the
// tool future, dropping `unblock_rx`. On the next invocation `unblock_rx` is None so
// the executor returns immediately. This guarantees select! MUST pick the elicitation
// branch on the first iteration (tool is the only blocking party). If the fix were
// absent, the test would deadlock and time out.
#[tokio::test]
async fn elicitation_event_during_tool_execution_is_handled() {
    use std::sync::Arc;
    use std::time::Duration;
    use tokio::sync::{mpsc, oneshot};
    use zeph_mcp::ElicitationEvent;

    struct BlockingElicitingExecutor {
        elic_tx: mpsc::Sender<ElicitationEvent>,
        // Holds the oneshot rx that the executor awaits on the first call.
        // Dropped (None) on re-invocation after select! cancels the first future.
        unblock_rx: Arc<std::sync::Mutex<Option<oneshot::Receiver<()>>>>,
        sent: Arc<std::sync::atomic::AtomicBool>,
    }

    impl ToolExecutor for BlockingElicitingExecutor {
        async fn execute(&self, _response: &str) -> Result<Option<ToolOutput>, ToolError> {
            Ok(None)
        }

        async fn execute_tool_call(
            &self,
            _call: &ToolCall,
        ) -> Result<Option<ToolOutput>, ToolError> {
            if !self.sent.swap(true, std::sync::atomic::Ordering::SeqCst) {
                let (response_tx, _response_rx) = oneshot::channel();
                let event = ElicitationEvent {
                    server_id: "test-server".to_owned(),
                    request: rmcp::model::ElicitRequestParams::FormElicitationParams {
                        meta: None,
                        message: "please fill in".to_owned(),
                        requested_schema: rmcp::model::ElicitationSchema::new(
                            std::collections::BTreeMap::new(),
                        ),
                    },
                    response_tx,
                };
                let _ = self.elic_tx.send(event).await;
                // Block until select! cancels this future (simulates the MCP server
                // waiting for a response). Cancellation drops unblock_rx, causing
                // this await to resolve with Err — but the future is already dropped
                // by then. On re-invocation unblock_rx is None, so we skip blocking.
                let rx = self.unblock_rx.lock().unwrap().take();
                if let Some(rx) = rx {
                    let _ = rx.await;
                }
            }
            Ok(Some(ToolOutput {
                tool_name: "elicit_tool".into(),
                summary: "result".into(),
                blocks_executed: 1,
                filter_stats: None,
                diff: None,
                streamed: false,
                terminal_id: None,
                locations: None,
                raw_response: None,
                claim_source: None,
                ..Default::default()
            }))
        }

        zeph_tools::tool_executor_no_inner_defaults!();
    }

    let (elic_tx, elic_rx) = mpsc::channel::<ElicitationEvent>(4);
    // Keep _unblock_tx alive for the duration of the test so that unblock_rx.await
    // truly blocks (channel not closed) until the future holding it is cancelled.
    let (_unblock_tx, unblock_rx) = oneshot::channel::<()>();

    let (mock, _counter) = MockProvider::default().with_tool_use(vec![
        tool_use_response("call-elic", "elicit_tool"),
        ChatResponse::Text("done".into()),
    ]);
    let provider = AnyProvider::Mock(mock);
    let channel = MockChannel::new(vec![]);
    let registry = create_test_registry();
    let executor = BlockingElicitingExecutor {
        elic_tx,
        unblock_rx: Arc::new(std::sync::Mutex::new(Some(unblock_rx))),
        sent: Arc::new(std::sync::atomic::AtomicBool::new(false)),
    };

    let mut agent =
        Agent::new(provider, channel, registry, None, 5, executor).with_mcp_elicitation_rx(elic_rx);

    // A 5-second timeout turns a deadlock into a clear test failure instead of a hang.
    let result = tokio::time::timeout(
        Duration::from_secs(5),
        agent.run_inline_tool_loop("trigger elicitation", 10),
    )
    .await
    .expect("run_inline_tool_loop timed out — elicitation deadlock not fixed")
    .unwrap();

    assert_eq!(result.text, "done");
}

// spec-075 (#6243) Phase 5: RunInline per-task `run_timeout_secs` enforcement via
// `handle_run_inline_action`'s third `tokio::select!` branch. These exercise the full
// `Agent::run_scheduler_loop` seam (not just `run_inline_tool_loop` in isolation), since the
// timeout branch lives in the scheduler-dispatch wrapper, not the inner tool loop.
mod run_inline_timeout {
    use std::time::Duration;

    use zeph_orchestration::{
        DagScheduler, GraphStatus, RuleBasedRouter, TaskGraph, TaskNode, TaskStatus, TimeoutPolicy,
    };

    use super::*;

    struct SlowToolExecutor {
        delay: Duration,
    }

    impl ToolExecutor for SlowToolExecutor {
        async fn execute(&self, _response: &str) -> Result<Option<ToolOutput>, ToolError> {
            Ok(None)
        }

        async fn execute_tool_call(
            &self,
            _call: &ToolCall,
        ) -> Result<Option<ToolOutput>, ToolError> {
            tokio::time::sleep(self.delay).await;
            Ok(Some(ToolOutput {
                tool_name: "test_tool".into(),
                summary: "slow result".into(),
                blocks_executed: 1,
                filter_stats: None,
                diff: None,
                streamed: false,
                terminal_id: None,
                locations: None,
                raw_response: None,
                claim_source: None,
                ..Default::default()
            }))
        }

        zeph_tools::tool_executor_no_inner_defaults!();
    }

    /// T5.3: a `RunInline` task with a short `run_timeout_secs` override and a tool loop that
    /// runs longer than the override (but well under the long global default) — the timeout
    /// branch must fire and fail the graph (default `Abort` strategy).
    #[tokio::test]
    async fn short_override_fires_before_slow_tool_loop_completes() {
        let (mock, _counter) = MockProvider::default().with_tool_use(vec![
            tool_use_response("call-1", "test_tool"),
            ChatResponse::Text("done".into()),
        ]);
        let provider = AnyProvider::Mock(mock);
        let channel = MockChannel::new(vec![]);
        let registry = create_test_registry();
        let executor = SlowToolExecutor {
            delay: Duration::from_secs(3),
        };

        let mut graph = TaskGraph::new("slow run-inline task");
        let mut node = TaskNode::new(0, "slow task", "run something slow");
        node.timeout = Some(TimeoutPolicy {
            run_timeout_secs: Some(1),
            idle_timeout_secs: None,
        });
        graph.tasks.push(node);

        let config = zeph_config::OrchestrationConfig {
            task_timeout_secs: 300, // long global default — proves the override (not it) fired
            ..zeph_config::OrchestrationConfig::default()
        };
        let mut scheduler =
            DagScheduler::new(graph, &config, Box::new(RuleBasedRouter), vec![], None).unwrap();

        let mut agent = Agent::new(provider, channel, registry, None, 5, executor);
        agent.services.orchestration.orchestration_config = config;

        let token = tokio_util::sync::CancellationToken::new();
        let status = tokio::time::timeout(
            Duration::from_secs(10),
            agent.run_scheduler_loop(&mut scheduler, 1, token),
        )
        .await
        .expect("run_scheduler_loop must not hang past the 1s override")
        .unwrap();

        assert_eq!(
            status,
            GraphStatus::Failed,
            "timed-out RunInline task with default Abort strategy fails the graph"
        );
        assert_eq!(scheduler.graph().tasks[0].status, TaskStatus::Failed);
    }

    /// T5.4 regression: a `RunInline` task with no override and a fast-completing tool loop
    /// completes normally — the new timeout branch must never fire when unused.
    #[tokio::test]
    async fn no_override_fast_completion_is_unaffected() {
        let (mock, _counter) = MockProvider::default().with_tool_use(vec![
            tool_use_response("call-1", "test_tool"),
            ChatResponse::Text("done".into()),
        ]);
        let provider = AnyProvider::Mock(mock);
        let channel = MockChannel::new(vec![]);
        let registry = create_test_registry();
        let executor = CallableToolExecutor::fixed_output("fast result");

        let mut graph = TaskGraph::new("fast run-inline task");
        let node = TaskNode::new(0, "fast task", "run something fast");
        graph.tasks.push(node);

        let config = zeph_config::OrchestrationConfig::default();
        let mut scheduler =
            DagScheduler::new(graph, &config, Box::new(RuleBasedRouter), vec![], None).unwrap();

        let mut agent = Agent::new(provider, channel, registry, None, 5, executor);
        agent.services.orchestration.orchestration_config = config;

        let token = tokio_util::sync::CancellationToken::new();
        let status = agent
            .run_scheduler_loop(&mut scheduler, 1, token)
            .await
            .unwrap();

        assert_eq!(status, GraphStatus::Completed);
        assert_eq!(scheduler.graph().tasks[0].status, TaskStatus::Completed);
    }

    /// Behavior-change regression (CHANGELOG `[Unreleased]` "BEHAVIOR CHANGE" entry): a
    /// `RunInline` task with **no** per-task `timeout` override was previously unbounded on
    /// this dispatch path (`check_timeouts()` cannot observe a task blocking the tick loop for
    /// its whole duration). It is now capped by the graph-global `task_timeout_secs` default,
    /// exactly like a spawned task. This test uses a short global default (rather than waiting
    /// out the real 300s default) to prove the cap applies even with zero per-task
    /// configuration.
    #[tokio::test]
    async fn no_override_task_is_capped_by_global_default_previously_unbounded() {
        let (mock, _counter) = MockProvider::default().with_tool_use(vec![
            tool_use_response("call-1", "test_tool"),
            ChatResponse::Text("unused".into()),
        ]);
        let provider = AnyProvider::Mock(mock);
        let channel = MockChannel::new(vec![]);
        let registry = create_test_registry();
        let executor = SlowToolExecutor {
            delay: Duration::from_secs(3),
        };

        let mut graph = TaskGraph::new("no-override slow run-inline task");
        // No `.timeout` set on this node — relies entirely on the graph-global default.
        let node = TaskNode::new(0, "slow task, no override", "run something slow");
        graph.tasks.push(node);

        let config = zeph_config::OrchestrationConfig {
            task_timeout_secs: 1, // short global default stands in for the real 300s default
            ..zeph_config::OrchestrationConfig::default()
        };
        let mut scheduler =
            DagScheduler::new(graph, &config, Box::new(RuleBasedRouter), vec![], None).unwrap();

        let mut agent = Agent::new(provider, channel, registry, None, 5, executor);
        agent.services.orchestration.orchestration_config = config;

        let token = tokio_util::sync::CancellationToken::new();
        let status = tokio::time::timeout(
            Duration::from_secs(10),
            agent.run_scheduler_loop(&mut scheduler, 1, token),
        )
        .await
        .expect("run_scheduler_loop must not hang past the 1s global default")
        .unwrap();

        assert_eq!(
            status,
            GraphStatus::Failed,
            "a RunInline task with no override must now be capped by the global default \
             (previously this dispatch path was entirely unbounded)"
        );
        assert_eq!(scheduler.graph().tasks[0].status, TaskStatus::Failed);
    }

    /// T5.5 (cross-phase Phase 3 + Phase 5): a `RunInline` task with both `timeout` and
    /// `recovery` configured — the timeout fires, Mode-1 recovery applies (since the default
    /// strategy is `Abort`), and the dependent task unblocks and dispatches.
    #[tokio::test]
    async fn timeout_and_recovery_together_unblocks_dependent() {
        let (mock, _counter) = MockProvider::default().with_tool_use(vec![
            // task 0: the tool_use response is consumed, but the ensuing tool call sleeps
            // past the 1s override — the select! timeout branch cancels the loop before a
            // second provider call would ever happen for this task.
            tool_use_response("call-1", "test_tool"),
            // task 1 (the dependent, unblocked by recovery): completes immediately.
            ChatResponse::Text("dependent done".into()),
        ]);
        let provider = AnyProvider::Mock(mock);
        let channel = MockChannel::new(vec![]);
        let registry = create_test_registry();
        let executor = SlowToolExecutor {
            delay: Duration::from_secs(3),
        };

        let mut graph = TaskGraph::new("timeout + recovery run-inline test");
        let mut node0 = TaskNode::new(0, "slow recoverable task", "run something slow");
        node0.timeout = Some(TimeoutPolicy {
            run_timeout_secs: Some(1),
            idle_timeout_secs: None,
        });
        node0.recovery = Some(zeph_orchestration::RecoveryAction {
            state_injection: Some("recovered output".to_string()),
        });
        let mut node1 = TaskNode::new(1, "dependent task", "consume the recovered output");
        node1.depends_on = vec![zeph_orchestration::TaskId(0)];
        graph.tasks.push(node0);
        graph.tasks.push(node1);

        let config = zeph_config::OrchestrationConfig {
            task_timeout_secs: 300,
            ..zeph_config::OrchestrationConfig::default()
        };
        let mut scheduler =
            DagScheduler::new(graph, &config, Box::new(RuleBasedRouter), vec![], None).unwrap();

        let mut agent = Agent::new(provider, channel, registry, None, 5, executor);
        agent.services.orchestration.orchestration_config = config;

        let token = tokio_util::sync::CancellationToken::new();
        let status = tokio::time::timeout(
            Duration::from_secs(10),
            agent.run_scheduler_loop(&mut scheduler, 2, token),
        )
        .await
        .expect("run_scheduler_loop must not hang past the 1s override")
        .unwrap();

        assert_eq!(
            status,
            GraphStatus::Completed,
            "recovery absorbs task 0's timeout; graph continues and completes via task 1"
        );
        assert_eq!(scheduler.graph().tasks[0].status, TaskStatus::Completed);
        assert_eq!(
            scheduler.graph().tasks[0]
                .result
                .as_ref()
                .unwrap()
                .agent_def
                .as_deref(),
            Some("__recovery__")
        );
        assert_eq!(scheduler.graph().tasks[1].status, TaskStatus::Completed);
    }
}