zeph-core 0.22.3

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
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
// SPDX-FileCopyrightText: 2026 Andrei G <bug-ops>
// SPDX-License-Identifier: MIT OR Apache-2.0

use std::collections::{HashMap, VecDeque};
use std::time::Duration;

use zeph_common::text::truncate_to_bytes_ref;
use zeph_tools::{
    OverflowConfig, ResultCacheConfig, TafcConfig, ToolResultCache, UtilityScorer,
    UtilityScoringConfig,
};

use super::{DOOM_LOOP_WINDOW, MAX_RETRIEVE_MANDATES_PER_TURN};

pub(crate) struct ToolOrchestrator {
    pub(super) doom_loop_history: Vec<u64>,
    pub(super) max_iterations: usize,
    pub(super) summarize_tool_output_enabled: bool,
    pub(super) overflow_config: OverflowConfig,
    /// Sliding window of recent (`tool_name`, `args_hash`) pairs for repeat-detection.
    /// Only LLM-initiated calls are recorded here — retry re-executions are excluded.
    /// Window capacity = 2 * `repeat_threshold`.
    pub(super) recent_tool_calls: VecDeque<(String, u64)>,
    /// Number of identical (`tool_name`, `args_hash`) appearances in the window required
    /// to trigger repeat-detection abort. 0 = disabled.
    pub(super) repeat_threshold: usize,
    /// Max retries for transient errors per tool call. 0 = disabled.
    pub(super) max_tool_retries: usize,
    /// Maximum wall-clock time (seconds) to spend on retries for a single tool call.
    /// 0 = no wall-clock budget (only `max_tool_retries` applies).
    pub(super) max_retry_duration_secs: u64,
    /// Base delay (ms) for exponential backoff. From `[tools.retry].base_ms`.
    pub(super) retry_base_ms: u64,
    /// Maximum delay cap (ms) for exponential backoff. From `[tools.retry].max_ms`.
    pub(super) retry_max_ms: u64,
    /// Pre-execution verifiers run before every native tool call (`TrustBench` pattern,
    /// issue #1630). Stored here rather than on `SecurityState` because they are tool-layer
    /// concerns: they inspect tool arguments at dispatch time, consistent with
    /// repeat-detection, rate-limiting, and overflow controls which also live here.
    pub(super) pre_execution_verifiers: Vec<Box<dyn zeph_tools::PreExecutionVerifier>>,
    /// Audit logger for pre-execution verifier blocks. `None` when audit is disabled.
    pub(super) audit_logger: Option<std::sync::Arc<zeph_tools::AuditLogger>>,
    /// Think-Augmented Function Calling configuration.
    pub(crate) tafc: TafcConfig,
    /// Session-scoped cache for tool results. Persists across tool rounds within a session;
    /// reset only on `/clear`. Unlike repeat-detection and doom-loop state (which reset per
    /// round), the cache is intentionally long-lived — its value comes from reuse across turns.
    pub(super) result_cache: ToolResultCache,
    /// Provider name for LLM-based parameter reformatting on `InvalidParameters`/`TypeMismatch`
    /// errors. Empty string = disabled. References a `[[llm.providers]]` name from config.
    pub(super) parameter_reformat_provider: String,
    /// Utility-guided dispatch gate. Scores each tool call before execution; calls below the
    /// threshold are skipped (fail-closed on scoring errors). Per-turn state cleared at the
    /// start of each tool round.
    pub(super) utility_scorer: UtilityScorer,
    /// Running count of tool calls dispatched this session. Incremented once per logical call
    /// (before the retry loop), not per retry attempt. Reset on `/clear`.
    pub(super) session_tool_call_count: u32,
    /// Maximum tool calls allowed per session. `None` = unlimited.
    pub(super) max_tool_calls_per_session: Option<u32>,
    /// Number of `PreToolUse` hook blocks accumulated in the current turn.
    /// Reset to 0 at the start of each `process_response_native_tools` call.
    /// Incremented once per blocked tool call (not per iteration).
    pub(super) hook_block_count: usize,
    /// Maximum `PreToolUse` hook blocks per turn before the turn is ended with a warning.
    /// Matches `HooksConfig::hook_block_cap`. 0 = no cap.
    pub(super) hook_block_cap: usize,
    /// Error category of the most recent failed execution per tool name, used by the
    /// utility gate's `Retrieve` branch to detect a just-failed retryable call and avoid
    /// re-issuing a mandatory retry hint against a dependency that is still down.
    /// Cleared alongside `recent_tool_calls` at the start of each user turn.
    pub(super) last_tool_error: HashMap<String, zeph_tools::error_taxonomy::ToolErrorCategory>,
    /// Count of *consecutive* `Retrieve` mandates issued with no intervening real dispatch
    /// (incremented by [`record_retrieve_mandate`](Self::record_retrieve_mandate), reset by
    /// [`reset_retrieve_mandate_count`](Self::reset_retrieve_mandate_count) on forward
    /// progress). Defense-in-depth circuit breaker for #5774: caps any undiscovered variant
    /// of the utility-gate retry loop, independent of the memory-search-specific bypass in
    /// `has_blocked_retrieval_this_turn`. Also cleared alongside `recent_tool_calls` at the
    /// start of each user turn.
    pub(super) retrieve_mandate_count: usize,
}

/// Truncate a tool name to at most 256 bytes, respecting UTF-8 char boundaries.
///
/// Used by both `push_tool_call` and `is_repeat` to ensure stored and queried
/// names always match when the original name exceeds the limit.
fn truncate_tool_name(name: &str) -> &str {
    const MAX_TOOL_NAME_BYTES: usize = 256;
    truncate_to_bytes_ref(name, MAX_TOOL_NAME_BYTES)
}

impl ToolOrchestrator {
    #[must_use]
    pub(crate) fn new() -> Self {
        let repeat_threshold = 2_usize;
        Self {
            doom_loop_history: Vec::new(),
            max_iterations: 10,
            summarize_tool_output_enabled: false,
            overflow_config: OverflowConfig::default(),
            recent_tool_calls: VecDeque::with_capacity(2 * repeat_threshold),
            repeat_threshold,
            max_tool_retries: 2,
            max_retry_duration_secs: 30,
            retry_base_ms: 500,
            retry_max_ms: 5_000,
            pre_execution_verifiers: Vec::new(),
            audit_logger: None,
            tafc: TafcConfig::default(),
            result_cache: ToolResultCache::new(true, Some(Duration::from_mins(5))),
            parameter_reformat_provider: String::new(),
            utility_scorer: UtilityScorer::new(UtilityScoringConfig::default()),
            session_tool_call_count: 0,
            max_tool_calls_per_session: None,
            hook_block_count: 0,
            hook_block_cap: 8,
            last_tool_error: HashMap::new(),
            retrieve_mandate_count: 0,
        }
    }

    /// Initialize the result cache from config.
    pub(crate) fn set_cache_config(&mut self, config: &ResultCacheConfig) {
        let ttl = if config.ttl_secs == 0 {
            None // ttl_secs = 0 → never expire
        } else {
            Some(Duration::from_secs(config.ttl_secs))
        };
        self.result_cache = ToolResultCache::new(config.enabled, ttl);
    }

    /// Clear the result cache and reset the session quota counter. Called on `/clear`.
    pub(crate) fn clear_cache(&mut self) {
        self.result_cache.clear();
        self.session_tool_call_count = 0;
    }

    /// Configure the utility scorer from config.
    pub(crate) fn set_utility_config(&mut self, config: UtilityScoringConfig) {
        self.utility_scorer = UtilityScorer::new(config);
    }

    #[allow(clippy::too_many_arguments)] // function with many required inputs; a *Params struct would be more verbose without simplifying the call site
    pub(crate) fn apply_config(
        &mut self,
        max_iterations: usize,
        max_tool_retries: usize,
        max_retry_duration_secs: u64,
        retry_base_ms: u64,
        retry_max_ms: u64,
        parameter_reformat_provider: String,
        tool_repeat_threshold: usize,
        max_tool_calls_per_session: Option<u32>,
        tool_summarization: bool,
        overflow_config: OverflowConfig,
    ) {
        self.max_iterations = max_iterations;
        self.max_tool_retries = max_tool_retries.min(5);
        self.max_retry_duration_secs = max_retry_duration_secs;
        self.retry_base_ms = retry_base_ms;
        self.retry_max_ms = retry_max_ms;
        self.parameter_reformat_provider = parameter_reformat_provider;
        self.repeat_threshold = tool_repeat_threshold;
        self.recent_tool_calls = VecDeque::with_capacity(2 * tool_repeat_threshold.max(1));
        self.max_tool_calls_per_session = max_tool_calls_per_session;
        self.summarize_tool_output_enabled = tool_summarization;
        if overflow_config.max_per_call_override > 0
            && overflow_config.max_per_call_override <= overflow_config.threshold
        {
            tracing::warn!(
                max_per_call_override = overflow_config.max_per_call_override,
                threshold = overflow_config.threshold,
                "tools.overflow.max_per_call_override <= threshold: per-call MCP result-size \
                 override is disabled, _meta[\"zeph/maxResultSizeChars\"] hints will have no effect"
            );
        }
        self.overflow_config = overflow_config;
    }

    /// Check whether the per-session quota allows another tool call.
    /// Returns `Some(max)` when quota is exhausted, `None` when allowed.
    #[must_use]
    pub(super) fn check_quota(&self) -> Option<u32> {
        self.max_tool_calls_per_session
            .filter(|&max| self.session_tool_call_count >= max)
    }

    /// Clear per-turn utility scorer state. Called at the start of each tool round.
    pub(super) fn clear_utility_state(&mut self) {
        self.utility_scorer.clear();
    }

    /// Returns a formatted cache stats string for `/cache-stats` command.
    pub(crate) fn cache_stats(&self) -> String {
        let cache = &self.result_cache;
        let status = if cache.is_enabled() {
            "enabled"
        } else {
            "disabled"
        };
        let hits = cache.hits();
        let misses = cache.misses();
        let total = hits + misses;
        #[allow(clippy::cast_precision_loss)]
        let hit_rate = if total > 0 {
            format!("{:.1}%", (hits as f64 / total as f64) * 100.0)
        } else {
            "n/a".to_owned()
        };
        let ttl_display = if cache.ttl_secs() == 0 {
            "never".to_owned()
        } else {
            format!("{}s", cache.ttl_secs())
        };
        format!(
            "Tool result cache: {status}\nEntries: {}, Hits: {hits}, Misses: {misses}, Hit rate: {hit_rate}\nTTL: {ttl_display}",
            cache.len(),
        )
    }

    pub(super) fn push_doom_hash(&mut self, hash: u64) {
        self.doom_loop_history.push(hash);
    }

    pub(super) fn clear_doom_history(&mut self) {
        self.doom_loop_history.clear();
    }

    /// Reset the per-turn `PreToolUse` hook block counter. Called at the start of each
    /// `process_response_native_tools` call.
    pub(super) fn reset_hook_block_count(&mut self) {
        self.hook_block_count = 0;
    }

    /// Reset the repeat-detection sliding window between user turns.
    pub(super) fn clear_recent_tool_calls(&mut self) {
        self.recent_tool_calls.clear();
        self.last_tool_error.clear();
        self.retrieve_mandate_count = 0;
    }

    /// Record the outcome of a dispatched tool call for `last_tool_error` tracking.
    ///
    /// On failure, remembers the error category so the utility gate's `Retrieve` branch
    /// can detect a just-failed retryable call for the same tool. On success, clears any
    /// previously recorded failure so a subsequent unrelated failure isn't masked by a
    /// stale entry.
    pub(super) fn record_tool_outcome_for_gate(
        &mut self,
        tool_name: &str,
        error_category: Option<zeph_tools::error_taxonomy::ToolErrorCategory>,
    ) {
        match error_category {
            Some(category) => {
                self.last_tool_error.insert(tool_name.to_owned(), category);
            }
            None => {
                self.last_tool_error.remove(tool_name);
            }
        }
    }

    /// Returns `true` when `memory_search` — the retrieval tool the `Retrieve` branch's
    /// hint recommends — most recently failed this turn with an error that makes it
    /// unusable as a retrieval detour: a retryable/network-class error (e.g. a down Qdrant),
    /// or `ConfirmationRequired` (#5774 — a sanitizer/exfiltration-guard check on the query
    /// content blocks `memory_search` itself, so mandating "retrieve context, then retry"
    /// again just re-triggers the same confirmation prompt on the identical query forever).
    ///
    /// Scoped to `memory_search` specifically rather than "any tool this turn": an
    /// unrelated tool's transient failure (e.g. a `web_fetch` 503) must not suppress the
    /// `Retrieve` optimization for the rest of the turn once the actual retrieval
    /// dependency is healthy or was never involved.
    #[must_use]
    pub(super) fn has_blocked_retrieval_this_turn(&self) -> bool {
        self.last_tool_error.get("memory_search").is_some_and(|c| {
            c.is_retryable()
                || *c == zeph_tools::error_taxonomy::ToolErrorCategory::ConfirmationRequired
        })
    }

    /// Record that the `Retrieve` gate issued another "you MUST call it again" mandate,
    /// consecutively since the last real dispatch (see
    /// [`reset_retrieve_mandate_count`](Self::reset_retrieve_mandate_count)).
    pub(super) fn record_retrieve_mandate(&mut self) {
        self.retrieve_mandate_count = self.retrieve_mandate_count.saturating_add(1);
    }

    /// Resets the consecutive-mandate counter once a call *other than the retrieval detour
    /// itself* (i.e. not `memory_search`) actually reaches real dispatch
    /// (`UtilityAction::ToolCall`) instead of being gated into another `Retrieve` cycle.
    ///
    /// Critic-flagged gap (S2, #5774): counting *lifetime* mandates per turn would false-trip
    /// on a legitimate long turn containing more than `MAX_RETRIEVE_MANDATES_PER_TURN`
    /// distinct, genuinely-uncertain tool calls that each individually resolve fine — the
    /// breaker must only fire on *consecutive* stalls with no forward progress in between.
    /// Called from `handle_utility_gate`'s fallthrough arm, which is reached exactly when the
    /// call under evaluation is not being intercepted by `Respond`/`Retrieve`/`Verify`/`Stop`.
    ///
    /// Critic-flagged gap (S3, #5774): the caller must NOT reset when the dispatched call is
    /// `memory_search` itself. `memory_search` always reaches this arm (gain 0.8 takes the
    /// direct `ToolCall` branch), so an unconditional reset fired on every single cycle of the
    /// "retrieve, dispatch, decline" loop this counter exists to catch — the repeated-decline
    /// case (the issue's own "answering the dialog does not break the cycle" observation) never
    /// tripped the breaker. Only a *different* tool reaching real dispatch is genuine forward
    /// progress on the user's actual request.
    pub(super) fn reset_retrieve_mandate_count(&mut self) {
        self.retrieve_mandate_count = 0;
    }

    /// Returns `true` once `record_retrieve_mandate` has been called
    /// `MAX_RETRIEVE_MANDATES_PER_TURN` times in a row without an intervening
    /// [`reset_retrieve_mandate_count`](Self::reset_retrieve_mandate_count).
    ///
    /// Defense-in-depth circuit breaker for #5774: `has_blocked_retrieval_this_turn` fixes
    /// the specific memory-search-confirmation cycle, but this bound catches any other
    /// undiscovered variant of "utility gate keeps recommending `Retrieve` and the detour
    /// never resolves" instead of looping silently for the rest of the turn.
    #[must_use]
    pub(super) fn retrieve_mandate_limit_reached(&self) -> bool {
        self.retrieve_mandate_count >= MAX_RETRIEVE_MANDATES_PER_TURN
    }

    /// Returns `true` if the last `DOOM_LOOP_WINDOW` hashes are identical.
    pub(super) fn is_doom_loop(&self) -> bool {
        if self.doom_loop_history.len() < DOOM_LOOP_WINDOW {
            return false;
        }
        let recent = &self.doom_loop_history[self.doom_loop_history.len() - DOOM_LOOP_WINDOW..];
        recent.array_windows::<2>().all(|[a, b]| a == b)
    }

    /// Record a tool call (LLM-initiated only — not retry re-executions).
    ///
    /// Maintains a sliding window of size `2 * repeat_threshold`.
    /// Tool names are truncated to 256 bytes to prevent unbounded memory growth
    /// from adversarially long names.
    pub(super) fn push_tool_call(&mut self, name: &str, args_hash: u64) {
        if self.repeat_threshold == 0 {
            return;
        }
        let window = 2 * self.repeat_threshold;
        if self.recent_tool_calls.len() >= window {
            self.recent_tool_calls.pop_front();
        }
        self.recent_tool_calls
            .push_back((truncate_tool_name(name).to_owned(), args_hash)); // lgtm[rust/cleartext-logging]
    }

    /// Returns `true` if the same `(name, args_hash)` pair appears `>= repeat_threshold`
    /// times in the current window.
    ///
    /// Applies the same 256-byte name truncation as `push_tool_call` so that long names
    /// are correctly matched against stored (truncated) entries.
    pub(super) fn is_repeat(&self, name: &str, args_hash: u64) -> bool {
        if self.repeat_threshold == 0 {
            return false;
        }
        let name = truncate_tool_name(name);
        let count = self
            .recent_tool_calls
            .iter()
            .filter(|(n, h)| n == name && *h == args_hash)
            .count();
        count >= self.repeat_threshold
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn new_defaults() {
        let o = ToolOrchestrator::new();
        assert!(o.doom_loop_history.is_empty());
        assert_eq!(o.max_iterations, 10);
        assert!(!o.summarize_tool_output_enabled);
        assert!(o.recent_tool_calls.is_empty());
        assert_eq!(o.repeat_threshold, 2);
        assert_eq!(o.max_tool_retries, 2);
        assert_eq!(o.max_retry_duration_secs, 30);
    }

    // ── #3079 M2: apply_config misconfiguration warning ─────────────────────────
    //
    // `max_per_call_override > 0 && max_per_call_override <= threshold` means the per-call
    // override is silently inert (the clamp in `maybe_summarize_tool_output` always floors
    // at `threshold`) — apply_config must warn so an operator notices the misconfiguration.
    // `max_per_call_override == 0` is the deliberate explicit-disable value and must NOT warn.

    fn apply_overflow_config(o: &mut ToolOrchestrator, overflow_config: OverflowConfig) {
        o.apply_config(
            10,
            2,
            30,
            500,
            5_000,
            String::new(),
            2,
            None,
            false,
            overflow_config,
        );
    }

    #[test]
    #[tracing_test::traced_test]
    fn apply_config_warns_when_ceiling_below_threshold() {
        let mut o = ToolOrchestrator::new();
        apply_overflow_config(
            &mut o,
            OverflowConfig {
                threshold: 1000,
                retention_days: 7,
                max_overflow_bytes: 0,
                max_per_call_override: 500,
            },
        );
        assert!(
            logs_contain("max_per_call_override <= threshold"),
            "ceiling (500) below threshold (1000) must emit the misconfiguration warning"
        );
    }

    #[test]
    #[tracing_test::traced_test]
    fn apply_config_warns_at_exact_boundary_ceiling_equals_threshold() {
        let mut o = ToolOrchestrator::new();
        apply_overflow_config(
            &mut o,
            OverflowConfig {
                threshold: 1000,
                retention_days: 7,
                max_overflow_bytes: 0,
                max_per_call_override: 1000,
            },
        );
        assert!(
            logs_contain("max_per_call_override <= threshold"),
            "ceiling == threshold is still the inert boundary case and must warn"
        );
    }

    #[test]
    #[tracing_test::traced_test]
    fn apply_config_no_warn_when_ceiling_explicitly_disabled_zero() {
        let mut o = ToolOrchestrator::new();
        apply_overflow_config(
            &mut o,
            OverflowConfig {
                threshold: 1000,
                retention_days: 7,
                max_overflow_bytes: 0,
                max_per_call_override: 0,
            },
        );
        assert!(
            !logs_contain("max_per_call_override <= threshold"),
            "ceiling=0 is the deliberate explicit-disable value, not a misconfiguration — \
             must not warn"
        );
    }

    #[test]
    #[tracing_test::traced_test]
    fn apply_config_no_warn_when_ceiling_above_threshold() {
        let mut o = ToolOrchestrator::new();
        apply_overflow_config(
            &mut o,
            OverflowConfig {
                threshold: 1000,
                retention_days: 7,
                max_overflow_bytes: 0,
                max_per_call_override: 131_072,
            },
        );
        assert!(
            !logs_contain("max_per_call_override <= threshold"),
            "a correctly configured ceiling above the threshold must not warn"
        );
    }

    #[test]
    fn is_doom_loop_insufficient_history() {
        let mut o = ToolOrchestrator::new();
        o.push_doom_hash(42);
        o.push_doom_hash(42);
        assert!(!o.is_doom_loop());
    }

    #[test]
    fn is_doom_loop_identical_hashes() {
        let mut o = ToolOrchestrator::new();
        o.push_doom_hash(7);
        o.push_doom_hash(7);
        o.push_doom_hash(7);
        assert!(o.is_doom_loop());
    }

    #[test]
    fn is_doom_loop_mixed_hashes() {
        let mut o = ToolOrchestrator::new();
        o.push_doom_hash(1);
        o.push_doom_hash(2);
        o.push_doom_hash(3);
        assert!(!o.is_doom_loop());
    }

    #[test]
    fn is_doom_loop_only_recent_window_matters() {
        let mut o = ToolOrchestrator::new();
        o.push_doom_hash(1);
        o.push_doom_hash(2);
        o.push_doom_hash(9);
        o.push_doom_hash(9);
        o.push_doom_hash(9);
        assert!(o.is_doom_loop());
    }

    #[test]
    fn clear_doom_history_resets() {
        let mut o = ToolOrchestrator::new();
        o.push_doom_hash(5);
        o.push_doom_hash(5);
        o.push_doom_hash(5);
        assert!(o.is_doom_loop());
        o.clear_doom_history();
        assert!(!o.is_doom_loop());
        assert!(o.doom_loop_history.is_empty());
    }

    // Repeat-detection tests

    #[test]
    fn repeat_detection_no_repeat_before_threshold() {
        let mut o = ToolOrchestrator::new();
        o.push_tool_call("bash", 42);
        // Only 1 occurrence, threshold is 2 — not a repeat yet
        assert!(!o.is_repeat("bash", 42));
    }

    #[test]
    fn repeat_detection_triggers_at_threshold() {
        let mut o = ToolOrchestrator::new();
        o.push_tool_call("bash", 42);
        o.push_tool_call("bash", 42);
        // 2 occurrences >= threshold 2 → repeat
        assert!(o.is_repeat("bash", 42));
    }

    #[test]
    fn repeat_detection_different_args_no_repeat() {
        let mut o = ToolOrchestrator::new();
        o.push_tool_call("bash", 1);
        o.push_tool_call("bash", 2);
        assert!(!o.is_repeat("bash", 1));
        assert!(!o.is_repeat("bash", 2));
    }

    #[test]
    fn repeat_detection_different_tool_no_repeat() {
        let mut o = ToolOrchestrator::new();
        o.push_tool_call("bash", 42);
        o.push_tool_call("read", 42);
        assert!(!o.is_repeat("bash", 42));
        assert!(!o.is_repeat("read", 42));
    }

    #[test]
    fn repeat_detection_window_evicts_old_entries() {
        let mut o = ToolOrchestrator::new();
        // Window size = 2 * threshold = 4
        o.push_tool_call("bash", 42);
        o.push_tool_call("read", 1);
        o.push_tool_call("read", 2);
        o.push_tool_call("read", 3);
        // Now push another entry — "bash:42" should be evicted from front
        o.push_tool_call("read", 4);
        // "bash:42" was in the window once, now evicted → not a repeat
        assert!(!o.is_repeat("bash", 42));
    }

    #[test]
    fn repeat_detection_disabled_when_threshold_zero() {
        let mut o = ToolOrchestrator::new();
        o.repeat_threshold = 0;
        o.push_tool_call("bash", 42);
        o.push_tool_call("bash", 42);
        o.push_tool_call("bash", 42);
        // Threshold 0 means disabled
        assert!(!o.is_repeat("bash", 42));
    }

    // ── SEC-003: tool name truncation ─────────────────────────────────────────

    #[test]
    fn push_tool_call_long_name_truncated_to_256_bytes() {
        let mut o = ToolOrchestrator::new();
        // Name well above 256 bytes
        let long_name = "a".repeat(512);
        o.push_tool_call(&long_name, 99);
        let stored = &o.recent_tool_calls[0].0;
        assert_eq!(stored.len(), 256, "stored name must be exactly 256 bytes");
        assert!(
            stored.is_char_boundary(stored.len()),
            "truncation must land on char boundary"
        );
    }

    #[test]
    fn push_tool_call_unicode_name_truncated_at_char_boundary() {
        let mut o = ToolOrchestrator::new();
        // Each '日' is 3 bytes. 256 / 3 = 85 full chars = 255 bytes.
        // Appending one more gives 258 bytes total — must truncate to 255.
        let base: String = "".repeat(85); // 255 bytes
        let long_name = format!("{base}"); // 258 bytes — crosses 256-byte boundary
        o.push_tool_call(&long_name, 1);
        let stored = &o.recent_tool_calls[0].0;
        assert!(stored.len() <= 256, "stored name must not exceed 256 bytes");
        assert!(
            stored.is_char_boundary(stored.len()),
            "must be valid UTF-8 boundary"
        );
    }

    #[test]
    fn push_tool_call_short_name_not_truncated() {
        let mut o = ToolOrchestrator::new();
        let short_name = "shell";
        o.push_tool_call(short_name, 7);
        assert_eq!(o.recent_tool_calls[0].0, short_name);
    }

    #[test]
    fn push_tool_call_300_byte_name_truncated_to_at_most_256() {
        // SEC-003: specifically test with 300-byte name as the boundary case
        let mut o = ToolOrchestrator::new();
        let name_300 = "x".repeat(300);
        o.push_tool_call(&name_300, 42);
        let stored = &o.recent_tool_calls[0].0;
        assert!(
            stored.len() <= 256,
            "300-byte name must be stored as ≤256 bytes, got {}",
            stored.len()
        );
        assert!(stored.is_char_boundary(stored.len()));
    }

    // ── SEC-004: retry budget field and logic ─────────────────────────────────

    #[test]
    fn max_retry_duration_secs_default_is_30() {
        // SEC-004: verify the budget field is set at construction time
        let o = ToolOrchestrator::new();
        assert_eq!(o.max_retry_duration_secs, 30);
    }

    #[test]
    fn retry_budget_condition_zero_disables_check() {
        // SEC-004: when max_retry_duration_secs == 0, the budget check must be skipped.
        // This mirrors the `if max_retry_duration_secs > 0` guard in native.rs.
        let budget_secs: u64 = 0;
        // Simulate that 60 seconds have elapsed — budget check is disabled.
        let elapsed_secs: u64 = 60;
        let budget_exceeded = budget_secs > 0 && elapsed_secs >= budget_secs;
        assert!(
            !budget_exceeded,
            "budget=0 must disable the wall-clock check"
        );
    }

    #[test]
    fn retry_budget_condition_exceeded_triggers_break() {
        // SEC-004: simulate elapsed > budget with a real Instant to confirm the
        // condition that native.rs evaluates before breaking the retry loop.
        let budget_secs: u64 = 1;
        // Subtract 2 seconds to ensure elapsed >= budget without sleeping.
        let retry_start = std::time::Instant::now()
            .checked_sub(std::time::Duration::from_secs(2))
            .unwrap();
        let elapsed_secs = retry_start.elapsed().as_secs();
        let budget_exceeded = budget_secs > 0 && elapsed_secs >= budget_secs;
        assert!(
            budget_exceeded,
            "elapsed {elapsed_secs}s should exceed budget {budget_secs}s"
        );
    }

    // ── cache_stats() display ─────────────────────────────────────────────────

    #[test]
    fn cache_stats_disabled_shows_disabled_status() {
        let mut o = ToolOrchestrator::new();
        o.set_cache_config(&ResultCacheConfig {
            enabled: false,
            ttl_secs: 300,
        });
        let stats = o.cache_stats();
        assert!(
            stats.contains("disabled"),
            "expected 'disabled' in: {stats}"
        );
    }

    #[test]
    fn cache_stats_no_calls_shows_na_hit_rate() {
        let o = ToolOrchestrator::new();
        let stats = o.cache_stats();
        assert!(
            stats.contains("n/a"),
            "expected 'n/a' hit rate when total=0, got: {stats}"
        );
    }

    #[test]
    fn cache_stats_ttl_zero_shows_never() {
        let mut o = ToolOrchestrator::new();
        o.set_cache_config(&ResultCacheConfig {
            enabled: true,
            ttl_secs: 0,
        });
        let stats = o.cache_stats();
        assert!(
            stats.contains("never"),
            "expected 'never' TTL display for ttl_secs=0, got: {stats}"
        );
    }

    #[test]
    fn cache_stats_hit_rate_percentage() {
        use zeph_tools::CacheKey;
        let mut o = ToolOrchestrator::new();
        // Directly manipulate the cache to simulate 1 hit and 1 miss.
        // put() one entry, get() it (hit), then get() a missing key (miss).
        let output = zeph_tools::ToolOutput {
            tool_name: "read".into(),
            summary: "contents".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()
        };
        o.result_cache.put(CacheKey::new("read", 1), output);
        o.result_cache.get(&CacheKey::new("read", 1)); // hit
        o.result_cache.get(&CacheKey::new("read", 99)); // miss
        let stats = o.cache_stats();
        assert!(
            stats.contains("50.0%"),
            "expected 50.0% hit rate (1 hit / 2 total), got: {stats}"
        );
        assert!(
            stats.contains("Hits: 1"),
            "expected 'Hits: 1', got: {stats}"
        );
        assert!(
            stats.contains("Misses: 1"),
            "expected 'Misses: 1', got: {stats}"
        );
    }

    #[test]
    fn set_cache_config_ttl_mapping() {
        let mut o = ToolOrchestrator::new();
        // ttl_secs = 0 → None (never expire) → ttl_secs() returns 0
        o.set_cache_config(&ResultCacheConfig {
            enabled: true,
            ttl_secs: 0,
        });
        assert_eq!(o.result_cache.ttl_secs(), 0);

        // ttl_secs = 60 → Some(60s) → ttl_secs() returns 60
        o.set_cache_config(&ResultCacheConfig {
            enabled: true,
            ttl_secs: 60,
        });
        assert_eq!(o.result_cache.ttl_secs(), 60);
    }

    #[test]
    fn check_quota_unlimited() {
        let mut o = ToolOrchestrator::new();
        o.max_tool_calls_per_session = None;
        o.session_tool_call_count = 999;
        assert_eq!(o.check_quota(), None);
    }

    #[test]
    fn check_quota_below_limit() {
        let mut o = ToolOrchestrator::new();
        o.max_tool_calls_per_session = Some(10);
        o.session_tool_call_count = 5;
        assert_eq!(o.check_quota(), None);
    }

    #[test]
    fn check_quota_at_limit() {
        let mut o = ToolOrchestrator::new();
        o.max_tool_calls_per_session = Some(10);
        o.session_tool_call_count = 10;
        assert_eq!(o.check_quota(), Some(10));
    }

    #[test]
    fn hook_block_cap_defaults() {
        let o = ToolOrchestrator::new();
        assert_eq!(o.hook_block_cap, 8);
        assert_eq!(o.hook_block_count, 0);
    }

    #[test]
    fn reset_hook_block_count_clears_counter() {
        let mut o = ToolOrchestrator::new();
        o.hook_block_count = 5;
        o.reset_hook_block_count();
        assert_eq!(o.hook_block_count, 0);
    }

    #[test]
    fn check_quota_resets_on_clear() {
        let mut o = ToolOrchestrator::new();
        o.max_tool_calls_per_session = Some(5);
        o.session_tool_call_count = 5;
        assert_eq!(o.check_quota(), Some(5));
        o.clear_cache();
        assert_eq!(o.session_tool_call_count, 0);
        assert_eq!(o.check_quota(), None);
    }

    // ── retrieve-mandate circuit breaker (#5774) ─────────────────────────────

    #[test]
    fn retrieve_mandate_limit_reached_after_consecutive_mandates() {
        let mut o = ToolOrchestrator::new();
        assert!(!o.retrieve_mandate_limit_reached());
        o.record_retrieve_mandate();
        assert!(!o.retrieve_mandate_limit_reached());
        o.record_retrieve_mandate();
        assert!(!o.retrieve_mandate_limit_reached());
        o.record_retrieve_mandate();
        assert!(
            o.retrieve_mandate_limit_reached(),
            "3 consecutive mandates must trip the breaker"
        );
    }

    // Critic-flagged S2 regression: the breaker must count *consecutive* stalls, not a
    // lifetime-per-turn total — a legitimate long turn with several genuinely-uncertain
    // tool calls that each resolve fine (real dispatch in between) must not false-trip.
    #[test]
    fn reset_retrieve_mandate_count_prevents_false_trip_on_legitimate_long_turn() {
        let mut o = ToolOrchestrator::new();
        o.record_retrieve_mandate();
        o.record_retrieve_mandate();
        // Forward progress: some call reached real dispatch, breaking the stall streak.
        o.reset_retrieve_mandate_count();
        assert!(!o.retrieve_mandate_limit_reached());
        o.record_retrieve_mandate();
        o.record_retrieve_mandate();
        assert!(
            !o.retrieve_mandate_limit_reached(),
            "2 mandates after a reset must not trip a breaker requiring 3 consecutive"
        );
    }

    #[test]
    fn clear_recent_tool_calls_resets_retrieve_mandate_count() {
        let mut o = ToolOrchestrator::new();
        o.record_retrieve_mandate();
        o.record_retrieve_mandate();
        o.record_retrieve_mandate();
        assert!(o.retrieve_mandate_limit_reached());
        o.clear_recent_tool_calls();
        assert!(!o.retrieve_mandate_limit_reached());
        assert_eq!(o.retrieve_mandate_count, 0);
    }
}