eggsact 1.2.7

Deterministic MCP and in-process utility tools for coding agents
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
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
use crate::calc::EvalContext;
use crate::mcp::registry::ToolCost;
use crate::mcp::response::ToolResponse;
use std::cell::RefCell;
use std::sync::atomic::AtomicBool;
use std::sync::Arc;
use std::time::{Duration, Instant};

thread_local! {
    static CURRENT_CANCEL_FLAG: RefCell<Option<Arc<AtomicBool>>> = const { RefCell::new(None) };
    static CURRENT_EVAL_CONTEXT: RefCell<Option<*mut EvalContext>> = const { RefCell::new(None) };
    static EVAL_CONTEXT_MUTABLY_BORROWED: RefCell<bool> = const { RefCell::new(false) };
}

/// RAII guard that restores the previous cancellation flag on drop.
///
/// Each guard owns the value it must restore, so nested scopes do not
/// overwrite each other's restoration state. Panic/unwind via `Drop`
/// ensures the thread-local reverts to its prior value.
struct CancelFlagGuard {
    previous: Option<Arc<AtomicBool>>,
}

impl Drop for CancelFlagGuard {
    fn drop(&mut self) {
        CURRENT_CANCEL_FLAG.with(|cell| {
            *cell.borrow_mut() = self.previous.take();
        });
    }
}

/// RAII guard that restores the previous eval context on drop.
///
/// Each guard owns the raw pointer it must restore, so nested scopes
/// do not overwrite each other's restoration state.
struct EvalContextGuard {
    previous: Option<*mut EvalContext>,
}

impl Drop for EvalContextGuard {
    fn drop(&mut self) {
        CURRENT_EVAL_CONTEXT.with(|cell| {
            *cell.borrow_mut() = self.previous.take();
        });
    }
}

/// RAII guard that clears the mutable-borrow flag on drop.
///
/// While this guard is alive, [`with_current_eval_context`] refuses to
/// produce another `&mut EvalContext`. Drop restores the flag even on
/// unwind.
struct EvalBorrowGuard;

impl Drop for EvalBorrowGuard {
    fn drop(&mut self) {
        EVAL_CONTEXT_MUTABLY_BORROWED.with(|cell| {
            *cell.borrow_mut() = false;
        });
    }
}

/// Set the current thread's cancellation flag for the duration of `f`.
///
/// Nested calls properly restore the previous flag when `f` returns.
/// Panic/unwind also restores the previous flag via RAII guard `Drop`.
pub fn with_cancel_flag<F, R>(flag: Option<Arc<AtomicBool>>, f: F) -> R
where
    F: FnOnce() -> R,
{
    CURRENT_CANCEL_FLAG.with(|cell| {
        let prev = std::mem::replace(&mut *cell.borrow_mut(), flag);
        let _guard = CancelFlagGuard { previous: prev };
        f()
    })
}

/// Retrieve the current thread's cancellation flag, if any.
pub fn current_cancel_flag() -> Option<Arc<AtomicBool>> {
    CURRENT_CANCEL_FLAG.with(|cell| cell.borrow().clone())
}

/// Set the current thread's [`EvalContext`] for the duration of `f`.
///
/// The `EvalContext` is passed as a raw pointer to avoid lifetime issues
/// with the thread-local. The caller must ensure `ctx` outlives `f`.
///
/// Nested calls properly restore the previous context when `f` returns.
/// Panic/unwind also restores the previous context via RAII guard `Drop`.
pub fn with_eval_context<F, R>(ctx: &mut EvalContext, f: F) -> R
where
    F: FnOnce() -> R,
{
    CURRENT_EVAL_CONTEXT.with(|cell| {
        let prev = cell.borrow_mut().replace(ctx as *mut EvalContext);
        let _guard = EvalContextGuard { previous: prev };
        f()
    })
}

/// Access the current thread's [`EvalContext`] through a closure.
///
/// The closure receives `Option<&mut EvalContext>` — `Some` if an eval context
/// is installed via [`with_eval_context`], `None` otherwise. The mutable borrow
/// exists only for the duration of the closure, preventing escaping references.
///
/// While the closure is running, a thread-local guard prevents any other call
/// to `with_current_eval_context` from producing a second `&mut EvalContext`.
/// Re-entrant access is treated as an internal invariant violation and
/// panics. The guard is restored on normal return and during unwind, so the
/// mutable-borrow state never leaks across calls.
pub fn with_current_eval_context<R>(f: impl FnOnce(Option<&mut EvalContext>) -> R) -> R {
    {
        let already_borrowed = EVAL_CONTEXT_MUTABLY_BORROWED.with(|cell| *cell.borrow());
        assert!(
            !already_borrowed,
            "with_current_eval_context: re-entrant mutable access to the installed EvalContext is not allowed; do not nest with_eval_context/with_current_eval_context"
        );
        EVAL_CONTEXT_MUTABLY_BORROWED.with(|cell| {
            *cell.borrow_mut() = true;
        });
    }
    let _borrow_guard = EvalBorrowGuard;

    CURRENT_EVAL_CONTEXT.with(|cell| {
        let ptr_opt: Option<*mut EvalContext> = *cell.borrow();
        match ptr_opt {
            Some(ptr) => {
                // SAFETY: the pointer was derived from a valid &mut EvalContext
                // in with_eval_context and is valid for the enclosing scope.
                // The borrow does not escape this callback. The mutable-borrow
                // guard above prevents a second `&mut EvalContext` from being
                // handed out while this one is live.
                f(Some(unsafe { &mut *ptr }))
            }
            None => f(None),
        }
    })
}

/// Create a `BudgetContext` suitable for a tool handler, automatically
/// picking up the thread-local cancellation flag if one is set.
///
/// This is the recommended way for handler functions (which have signature
/// `fn(&Value) -> ToolResponse` and cannot receive context directly) to
/// create a `BudgetContext` with cancellation support.
pub fn for_handler(budget: ToolBudget) -> BudgetContext {
    let mut ctx = BudgetContext::new(budget);
    if let Some(flag) = current_cancel_flag() {
        ctx = ctx.with_cancellation(flag);
    }
    ctx
}

/// Budget tier classification for MCP tools.
///
/// `BudgetTier` is the lightweight label that maps a tool's cost class to an
/// enforceable `ToolBudget`. The tiers are intentionally coarse so that tool
/// authors can declare cost once (via `ToolCost`) and the runtime can resolve
/// concrete limits at dispatch time.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum BudgetTier {
    Cheap,
    Moderate,
    Heavy,
}

/// Enforceable resource budget for an MCP tool invocation.
///
/// Unlike `ToolCost` which is a *descriptive* metadata annotation on a
/// `ToolSpec`, `ToolBudget` carries the *enforceable* numeric limits that the
/// runtime applies during tool execution. This separation keeps tool
/// declarations ergonomic while giving the runtime precise control.
///
/// Three canonical budget tiers are provided as `const` values:
/// - `CHEAP` – fast, lightweight tools (unit conversion, text compare, …)
/// - `MODERATE` – tools that may do heavier text/regex work
/// - `HEAVY` – composite tools that spawn sub-tools (edit_preflight, …)
///
/// Use the builder methods (`with_max_elapsed_ms`, `with_max_findings`) to
/// derive per-tool overrides from these base budgets.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ToolBudget {
    pub max_input_bytes: usize,
    pub max_output_bytes: usize,
    pub max_text_bytes: usize,
    pub max_list_items: usize,
    pub max_regex_pattern_chars: usize,
    pub max_regex_samples: usize,
    pub max_elapsed_ms: u64,
    pub max_spawned_workers: usize,
    pub max_findings: usize,
}

impl ToolBudget {
    /// Budget for cheap / low-cost tools.
    pub const CHEAP: Self = Self {
        max_input_bytes: 1_000_000,
        max_output_bytes: 1_000_000,
        max_text_bytes: 100_000,
        max_list_items: 10_000,
        max_regex_pattern_chars: 1_000,
        max_regex_samples: 100,
        max_elapsed_ms: 10_000,
        max_spawned_workers: 16,
        max_findings: 100,
    };

    /// Budget for moderate-cost tools (30 s elapsed budget).
    pub const MODERATE: Self = Self {
        max_input_bytes: Self::CHEAP.max_input_bytes,
        max_output_bytes: Self::CHEAP.max_output_bytes,
        max_text_bytes: Self::CHEAP.max_text_bytes,
        max_list_items: Self::CHEAP.max_list_items,
        max_regex_pattern_chars: Self::CHEAP.max_regex_pattern_chars,
        max_regex_samples: Self::CHEAP.max_regex_samples,
        max_elapsed_ms: 30_000,
        max_spawned_workers: Self::CHEAP.max_spawned_workers,
        max_findings: Self::CHEAP.max_findings,
    };

    /// Budget for heavy / composite tools (30 s elapsed, 2 MB output).
    pub const HEAVY: Self = Self {
        max_input_bytes: Self::MODERATE.max_input_bytes,
        max_output_bytes: 2_000_000,
        max_text_bytes: Self::MODERATE.max_text_bytes,
        max_list_items: Self::MODERATE.max_list_items,
        max_regex_pattern_chars: Self::MODERATE.max_regex_pattern_chars,
        max_regex_samples: Self::MODERATE.max_regex_samples,
        max_elapsed_ms: Self::MODERATE.max_elapsed_ms,
        max_spawned_workers: Self::MODERATE.max_spawned_workers,
        max_findings: Self::MODERATE.max_findings,
    };

    /// Returns the budget tier that best matches this budget instance.
    ///
    /// Tier is inferred from the canonical discriminants (`max_output_bytes`
    /// for Heavy vs others, then `max_elapsed_ms` for Cheap vs Moderate) so
    /// that builder overrides like `CHEAP.with_max_elapsed_ms(5000)` still
    /// report the original tier instead of falling back to Moderate.
    pub fn tier(&self) -> BudgetTier {
        if self.max_output_bytes >= Self::HEAVY.max_output_bytes {
            BudgetTier::Heavy
        } else if self.max_elapsed_ms <= Self::CHEAP.max_elapsed_ms {
            BudgetTier::Cheap
        } else {
            BudgetTier::Moderate
        }
    }

    /// Derive a new budget with a custom `max_elapsed_ms` override.
    pub fn with_max_elapsed_ms(self, ms: u64) -> Self {
        Self {
            max_elapsed_ms: ms,
            ..self
        }
    }

    /// Derive a new budget with a custom `max_findings` override.
    pub fn with_max_findings(self, n: usize) -> Self {
        Self {
            max_findings: n,
            ..self
        }
    }

    /// Derive a new budget with a custom `max_output_bytes` override.
    /// Used by tests and by tools that need a tighter per-call output cap.
    pub fn with_max_output_bytes(self, n: usize) -> Self {
        Self {
            max_output_bytes: n,
            ..self
        }
    }

    /// Derive a new budget with a custom `max_input_bytes` override.
    pub fn with_max_input_bytes(self, n: usize) -> Self {
        Self {
            max_input_bytes: n,
            ..self
        }
    }

    /// Derive a new budget with a custom `max_text_bytes` override.
    ///
    /// The field was renamed from `max_text_chars` to `max_text_bytes` in
    /// 1.1.4 because enforcement is byte-based (`str::len()` returns UTF-8
    /// bytes, not Unicode scalar values). This builder is the supported
    /// way to customise the limit. Direct struct literals remain valid
    /// but break ABI; prefer builders when feasible.
    pub fn with_max_text_bytes(self, n: usize) -> Self {
        Self {
            max_text_bytes: n,
            ..self
        }
    }
}

/// Map a tool's declared `ToolCost` to an enforceable `ToolBudget`.
///
/// Composite / heavy tools that spawn sub-tools receive explicit overrides
/// regardless of their declared cost, because their actual resource usage
/// can exceed what the cost label alone would suggest.
pub fn budget_for_tool(tool_name: &str, cost: ToolCost) -> ToolBudget {
    // Heavy composite tools always get HEAVY budgets.
    match tool_name {
        "edit_preflight" | "command_preflight" | "config_preflight" => ToolBudget::HEAVY,
        "text_security_inspect" | "patch_apply_check" => ToolBudget::HEAVY,
        _ => budget_for_tier(cost.into()),
    }
}

/// Resolve a `BudgetTier` into its canonical `ToolBudget`.
pub fn budget_for_tier(tier: BudgetTier) -> ToolBudget {
    match tier {
        BudgetTier::Cheap => ToolBudget::CHEAP,
        BudgetTier::Moderate => ToolBudget::MODERATE,
        BudgetTier::Heavy => ToolBudget::HEAVY,
    }
}

/// Implicit conversion from `ToolCost` to `BudgetTier`.
impl From<ToolCost> for BudgetTier {
    fn from(cost: ToolCost) -> Self {
        match cost {
            ToolCost::Cheap => BudgetTier::Cheap,
            ToolCost::Moderate => BudgetTier::Moderate,
            ToolCost::Heavy => BudgetTier::Heavy,
        }
    }
}

/// Runtime context that carries an active budget alongside a deadline and
/// an optional cancellation flag.
///
/// Create a `BudgetContext` at the start of a tool invocation and pass it
/// through the execution path. Long-running loops should periodically
/// check `should_stop()` to honour both the time budget and external
/// cancellation.
pub struct BudgetContext {
    pub deadline: Option<Instant>,
    pub budget: ToolBudget,
    pub cancelled: Option<Arc<AtomicBool>>,
}

impl BudgetContext {
    /// Create a fresh context whose deadline is `now + budget.max_elapsed_ms`.
    pub fn new(budget: ToolBudget) -> Self {
        let deadline = Instant::now() + Duration::from_millis(budget.max_elapsed_ms);
        Self {
            deadline: Some(deadline),
            budget,
            cancelled: None,
        }
    }

    /// Attach an external cancellation flag.
    pub fn with_cancellation(self, cancelled: Arc<AtomicBool>) -> Self {
        Self {
            cancelled: Some(cancelled),
            ..self
        }
    }

    /// Returns `true` when the deadline has passed.
    pub fn is_expired(&self) -> bool {
        match self.deadline {
            Some(d) => Instant::now() >= d,
            None => false,
        }
    }

    /// Returns `true` when the cancellation flag has been set.
    pub fn is_cancelled(&self) -> bool {
        self.cancelled
            .as_ref()
            .is_some_and(|flag| flag.load(std::sync::atomic::Ordering::Acquire))
    }

    /// Returns `true` when the context should stop (expired or cancelled).
    pub fn should_stop(&self) -> bool {
        self.is_expired() || self.is_cancelled()
    }

    /// Returns `Err(TOOL_RESPONSE)` if the context has been cancelled.
    ///
    /// Use this at the top of long-running handlers or loops to bail out
    /// early when the caller has signalled cancellation.
    #[allow(clippy::result_large_err)]
    pub fn check_not_cancelled(&self, tool_name: &str) -> Result<(), ToolResponse> {
        if self.is_cancelled() {
            Err(ToolResponse::error_with_code(
                "cancelled",
                crate::mcp::machine_codes::CANCELLED,
                &format!("Tool '{}' was cancelled", tool_name),
                None,
                Some(tool_name),
            ))
        } else {
            Ok(())
        }
    }

    /// Returns `Err(TOOL_RESPONSE)` if the deadline has been exceeded.
    ///
    /// Use this inside loops that may run long to produce a clean timeout
    /// error instead of relying on the outer `tokio::time::timeout`.
    #[allow(clippy::result_large_err)]
    pub fn check_deadline(&self, tool_name: &str) -> Result<(), ToolResponse> {
        if self.is_expired() {
            Err(ToolResponse::error_with_code(
                "timeout",
                crate::mcp::machine_codes::TIMEOUT,
                &format!("Tool '{}' exceeded its time budget", tool_name),
                Some(vec!["Try a simpler input or shorter text".to_string()]),
                Some(tool_name),
            ))
        } else {
            Ok(())
        }
    }

    /// Returns `Err(TOOL_RESPONSE)` if the text exceeds `max_text_bytes`.
    ///
    /// Enforcement is byte-based: `str::len()` returns the number of UTF-8
    /// bytes, not Unicode scalar values.
    #[allow(clippy::result_large_err)]
    pub fn check_text_bytes(
        &self,
        field_name: &str,
        text: &str,
        tool_name: &str,
    ) -> Result<(), ToolResponse> {
        if text.len() > self.budget.max_text_bytes {
            Err(ToolResponse::error_with_code(
                "input_too_large",
                crate::mcp::machine_codes::INPUT_TOO_LARGE,
                &format!(
                    "Field '{}' length {} bytes exceeds limit {} bytes",
                    field_name,
                    text.len(),
                    self.budget.max_text_bytes
                ),
                None,
                Some(tool_name),
            ))
        } else {
            Ok(())
        }
    }

    /// Deprecated alias for [`BudgetContext::check_text_bytes`].
    ///
    /// The method was renamed in 1.1.4 because the enforcement unit is
    /// UTF-8 bytes (`str::len()`), not Unicode characters. This shim is
    /// retained for backward compatibility with downstream callers that
    /// referenced the old name. It forwards to `check_text_bytes` and
    /// emits a deprecation note; remove calls in new code.
    #[deprecated(
        since = "1.1.4",
        note = "use check_text_bytes (the limit is bytes, not characters)"
    )]
    #[allow(clippy::result_large_err)]
    pub fn check_text_len(
        &self,
        field_name: &str,
        text: &str,
        tool_name: &str,
    ) -> Result<(), ToolResponse> {
        self.check_text_bytes(field_name, text, tool_name)
    }

    /// Returns `Err(TOOL_RESPONSE)` if the list length exceeds `max_list_items`.
    #[allow(clippy::result_large_err)]
    pub fn check_list_len(
        &self,
        field_name: &str,
        len: usize,
        tool_name: &str,
    ) -> Result<(), ToolResponse> {
        if len > self.budget.max_list_items {
            Err(ToolResponse::error_with_code(
                "input_too_large",
                crate::mcp::machine_codes::INPUT_TOO_LARGE,
                &format!(
                    "Field '{}' length {} exceeds limit {}",
                    field_name, len, self.budget.max_list_items
                ),
                None,
                Some(tool_name),
            ))
        } else {
            Ok(())
        }
    }

    /// Returns `Err(TOOL_RESPONSE)` if the context should stop.
    ///
    /// Checks cancellation first, then deadline. Use this in handler
    /// cooldown checks where `should_stop()` is true but the reason
    /// could be either cancellation or expiry.
    #[allow(clippy::result_large_err)]
    pub fn check_should_stop(&self, tool_name: &str) -> Result<(), ToolResponse> {
        if self.is_cancelled() {
            return self.check_not_cancelled(tool_name);
        }
        if self.is_expired() {
            return self.check_deadline(tool_name);
        }
        Ok(())
    }

    /// Returns the remaining time before deadline, or `None` if no deadline.
    pub fn remaining_time_ms(&self) -> Option<u64> {
        self.deadline.map(|d| {
            let now = Instant::now();
            if now >= d {
                0
            } else {
                d.duration_since(now).as_millis() as u64
            }
        })
    }
}

/// Budget allocation for a sub-tool within a composite tool invocation.
///
/// Composite tools (edit_preflight, config_preflight, etc.) call multiple
/// sub-tools internally. `SubBudget` provides a fraction of the parent's
/// budget to each sub-tool, preventing any single sub-tool from consuming
/// the entire composite budget.
///
/// The primary constraint is a shared deadline derived from the parent's
/// `BudgetContext`. Input/output caps are proportional fractions.
#[derive(Clone, Copy, Debug)]
pub struct SubBudget {
    pub deadline: Option<Instant>,
    pub max_input_bytes: usize,
    pub max_output_bytes: usize,
    pub max_text_bytes: usize,
    pub max_list_items: usize,
    pub max_findings: usize,
}

impl SubBudget {
    pub fn should_stop(&self) -> bool {
        match self.deadline {
            Some(d) => Instant::now() >= d,
            None => false,
        }
    }
}

/// Manages sub-tool budget allocation for a composite tool.
///
/// Create one per composite tool invocation. Call `allocate()` before
/// each sub-tool invocation to get a `SubBudget` for that sub-tool.
/// The allocator tracks how many sub-tools have been called and
/// ensures the shared deadline is respected.
pub struct CompositeBudgetAllocator {
    deadline: Option<Instant>,
    parent_budget: ToolBudget,
    sub_tool_count: usize,
    total_sub_tools: usize,
}

impl CompositeBudgetAllocator {
    pub fn new(parent: &BudgetContext, total_sub_tools: usize) -> Self {
        Self {
            deadline: parent.deadline,
            parent_budget: parent.budget,
            sub_tool_count: 0,
            total_sub_tools,
        }
    }

    pub fn allocate(&mut self) -> SubBudget {
        let divisor = self.total_sub_tools.max(1);
        self.sub_tool_count += 1;
        SubBudget {
            deadline: self.deadline,
            max_input_bytes: (self.parent_budget.max_input_bytes / divisor).max(1),
            max_output_bytes: (self.parent_budget.max_output_bytes / divisor).max(1),
            max_text_bytes: (self.parent_budget.max_text_bytes / divisor).max(1),
            max_list_items: (self.parent_budget.max_list_items / divisor).max(1),
            max_findings: (self.parent_budget.max_findings / divisor).max(1),
        }
    }

    pub fn remaining(&self) -> usize {
        self.total_sub_tools.saturating_sub(self.sub_tool_count)
    }
}

/// Create a `BudgetContext` suitable for a composite tool's sub-tool.
///
/// Shares the parent's deadline and cancellation flag but applies
/// reduced input/output limits proportional to the sub-tool's share.
pub fn sub_budget_context(parent: &BudgetContext, sub: &SubBudget) -> BudgetContext {
    BudgetContext {
        deadline: sub.deadline,
        budget: ToolBudget {
            max_input_bytes: sub.max_input_bytes,
            max_output_bytes: sub.max_output_bytes,
            max_text_bytes: sub.max_text_bytes,
            max_list_items: sub.max_list_items,
            max_regex_pattern_chars: parent.budget.max_regex_pattern_chars,
            max_regex_samples: parent.budget.max_regex_samples,
            max_elapsed_ms: 0,
            max_spawned_workers: parent.budget.max_spawned_workers,
            max_findings: sub.max_findings,
        },
        cancelled: parent.cancelled.clone(),
    }
}

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

    #[test]
    fn budget_for_tier_returns_correct_budgets() {
        assert_eq!(budget_for_tier(BudgetTier::Cheap), ToolBudget::CHEAP);
        assert_eq!(budget_for_tier(BudgetTier::Moderate), ToolBudget::MODERATE);
        assert_eq!(budget_for_tier(BudgetTier::Heavy), ToolBudget::HEAVY);
    }

    #[test]
    fn budget_for_tier_tier_roundtrip() {
        assert_eq!(ToolBudget::CHEAP.tier(), BudgetTier::Cheap);
        assert_eq!(ToolBudget::MODERATE.tier(), BudgetTier::Moderate);
        assert_eq!(ToolBudget::HEAVY.tier(), BudgetTier::Heavy);
    }

    #[test]
    fn budget_for_tool_heavy_composite_overrides() {
        let edit = budget_for_tool("edit_preflight", ToolCost::Cheap);
        assert_eq!(edit, ToolBudget::HEAVY);

        let cmd = budget_for_tool("command_preflight", ToolCost::Cheap);
        assert_eq!(cmd, ToolBudget::HEAVY);

        let cfg = budget_for_tool("config_preflight", ToolCost::Cheap);
        assert_eq!(cfg, ToolBudget::HEAVY);

        let sec = budget_for_tool("text_security_inspect", ToolCost::Cheap);
        assert_eq!(sec, ToolBudget::HEAVY);

        let patch = budget_for_tool("patch_apply_check", ToolCost::Cheap);
        assert_eq!(patch, ToolBudget::HEAVY);
    }

    #[test]
    fn budget_for_tool_regular_tool_uses_cost() {
        let b = budget_for_tool("math_eval", ToolCost::Cheap);
        assert_eq!(b, ToolBudget::CHEAP);

        let b = budget_for_tool("text_diff_explain", ToolCost::Moderate);
        assert_eq!(b, ToolBudget::MODERATE);

        let b = budget_for_tool("json_extract", ToolCost::Heavy);
        assert_eq!(b, ToolBudget::HEAVY);
    }

    #[test]
    fn with_max_elapsed_ms_overrides() {
        let b = ToolBudget::CHEAP.with_max_elapsed_ms(5_000);
        assert_eq!(b.max_elapsed_ms, 5_000);
        assert_eq!(b.max_output_bytes, ToolBudget::CHEAP.max_output_bytes);
    }

    #[test]
    fn with_max_findings_overrides() {
        let b = ToolBudget::MODERATE.with_max_findings(50);
        assert_eq!(b.max_findings, 50);
        assert_eq!(b.max_elapsed_ms, ToolBudget::MODERATE.max_elapsed_ms);
    }

    #[test]
    fn budget_context_fresh_is_not_expired() {
        let ctx = BudgetContext::new(ToolBudget::CHEAP);
        assert!(!ctx.is_expired());
        assert!(!ctx.should_stop());
    }

    #[test]
    fn budget_context_not_cancelled_when_none() {
        let ctx = BudgetContext::new(ToolBudget::CHEAP);
        assert!(!ctx.is_cancelled());
    }

    #[test]
    fn budget_context_cancelled_flag() {
        let flag = Arc::new(AtomicBool::new(true));
        let ctx = BudgetContext::new(ToolBudget::CHEAP).with_cancellation(flag);
        assert!(ctx.is_cancelled());
        assert!(ctx.should_stop());
    }

    #[test]
    fn budget_context_not_cancelled_when_flag_false() {
        let flag = Arc::new(AtomicBool::new(false));
        let ctx = BudgetContext::new(ToolBudget::CHEAP).with_cancellation(flag);
        assert!(!ctx.is_cancelled());
        assert!(!ctx.should_stop());
    }

    #[test]
    fn custom_budget_tier_fallback() {
        let custom = ToolBudget {
            max_input_bytes: 999,
            ..ToolBudget::CHEAP
        };
        // Tier is inferred from output/elapsed discriminants, so input-only
        // customizations preserve the original tier (Cheap). A truly
        // unrecognizable budget (e.g. weird output) falls back to Moderate.
        assert_eq!(custom.tier(), BudgetTier::Cheap);
        let weird = ToolBudget {
            max_output_bytes: 999,
            max_elapsed_ms: 999_999,
            ..ToolBudget::CHEAP
        };
        assert_eq!(weird.tier(), BudgetTier::Moderate);
    }

    #[test]
    fn composite_allocator_even_split() {
        let parent = BudgetContext::new(ToolBudget::HEAVY);
        let mut alloc = CompositeBudgetAllocator::new(&parent, 3);

        let sub1 = alloc.allocate();
        let sub2 = alloc.allocate();
        let sub3 = alloc.allocate();

        let expected_output = ToolBudget::HEAVY.max_output_bytes / 3;
        assert_eq!(sub1.max_output_bytes, expected_output);
        assert_eq!(sub2.max_output_bytes, expected_output);
        assert_eq!(sub3.max_output_bytes, expected_output);

        let expected_text = ToolBudget::HEAVY.max_text_bytes / 3;
        assert_eq!(sub1.max_text_bytes, expected_text);
        assert_eq!(sub2.max_text_bytes, expected_text);
        assert_eq!(sub3.max_text_bytes, expected_text);
    }

    #[test]
    fn composite_allocator_deadline_propagated() {
        let parent = BudgetContext::new(ToolBudget::HEAVY);
        let mut alloc = CompositeBudgetAllocator::new(&parent, 2);

        let sub = alloc.allocate();
        assert_eq!(sub.deadline, parent.deadline);
    }

    #[test]
    fn composite_allocator_remaining_decrements() {
        let parent = BudgetContext::new(ToolBudget::HEAVY);
        let mut alloc = CompositeBudgetAllocator::new(&parent, 3);

        assert_eq!(alloc.remaining(), 3);
        alloc.allocate();
        assert_eq!(alloc.remaining(), 2);
        alloc.allocate();
        assert_eq!(alloc.remaining(), 1);
        alloc.allocate();
        assert_eq!(alloc.remaining(), 0);
    }

    #[test]
    fn sub_budget_should_stop_expired() {
        let sub = SubBudget {
            deadline: Some(Instant::now() - Duration::from_millis(100)),
            max_input_bytes: 1000,
            max_output_bytes: 1000,
            max_text_bytes: 1000,
            max_list_items: 100,
            max_findings: 10,
        };
        assert!(sub.should_stop());
    }

    #[test]
    fn sub_budget_context_inherits_cancellation() {
        let flag = Arc::new(AtomicBool::new(true));
        let parent = BudgetContext::new(ToolBudget::HEAVY).with_cancellation(flag);
        let mut alloc = CompositeBudgetAllocator::new(&parent, 2);
        let sub = alloc.allocate();

        let ctx = sub_budget_context(&parent, &sub);
        assert!(ctx.is_cancelled());
        assert!(ctx.should_stop());
    }

    #[test]
    fn check_not_cancelled_ok_when_not_cancelled() {
        let ctx = BudgetContext::new(ToolBudget::CHEAP);
        assert!(ctx.check_not_cancelled("test").is_ok());
    }

    #[test]
    fn check_not_cancelled_err_when_cancelled() {
        let flag = Arc::new(AtomicBool::new(true));
        let ctx = BudgetContext::new(ToolBudget::CHEAP).with_cancellation(flag);
        let err = ctx.check_not_cancelled("my_tool").unwrap_err();
        assert!(err.error.as_deref().unwrap_or("").contains("cancelled"));
    }

    #[test]
    fn check_deadline_ok_when_not_expired() {
        let ctx = BudgetContext::new(ToolBudget::CHEAP);
        assert!(ctx.check_deadline("test").is_ok());
    }

    #[test]
    fn check_deadline_err_when_expired() {
        let ctx = BudgetContext {
            deadline: Some(Instant::now() - Duration::from_millis(100)),
            budget: ToolBudget::CHEAP,
            cancelled: None,
        };
        let err = ctx.check_deadline("my_tool").unwrap_err();
        assert!(err.error.as_deref().unwrap_or("").contains("time budget"));
    }

    #[test]
    fn check_text_bytes_ok_when_within_limit() {
        let ctx = BudgetContext::new(ToolBudget::CHEAP);
        assert!(ctx.check_text_bytes("text", "hello", "test").is_ok());
    }

    #[test]
    fn check_text_bytes_err_when_exceeds_limit() {
        let ctx = BudgetContext::new(ToolBudget::CHEAP);
        let long_text = "x".repeat(ToolBudget::CHEAP.max_text_bytes + 1);
        let err = ctx
            .check_text_bytes("text", &long_text, "my_tool")
            .unwrap_err();
        assert!(err.error.as_deref().unwrap_or("").contains("exceeds limit"));
    }

    #[test]
    fn with_max_text_bytes_overrides_limit() {
        let b = ToolBudget::CHEAP.with_max_text_bytes(7);
        assert_eq!(b.max_text_bytes, 7);
        assert_eq!(b.max_elapsed_ms, ToolBudget::CHEAP.max_elapsed_ms);
        assert_eq!(b.max_output_bytes, ToolBudget::CHEAP.max_output_bytes);
    }

    #[test]
    #[allow(deprecated)]
    fn check_text_len_shim_forwards_to_check_text_bytes() {
        // The deprecated shim must produce identical behaviour to the new
        // method so downstream callers that referenced the old name keep
        // working until they migrate.
        let ctx = BudgetContext::new(ToolBudget::CHEAP);

        assert!(ctx.check_text_len("text", "hello", "test").is_ok());

        let long_text = "x".repeat(ToolBudget::CHEAP.max_text_bytes + 1);
        let err_shim = ctx
            .check_text_len("text", &long_text, "my_tool")
            .unwrap_err();
        let err_new = ctx
            .check_text_bytes("text", &long_text, "my_tool")
            .unwrap_err();
        assert_eq!(
            err_shim.error, err_new.error,
            "deprecated shim must produce identical error"
        );
    }

    #[test]
    fn check_list_len_ok_when_within_limit() {
        let ctx = BudgetContext::new(ToolBudget::CHEAP);
        assert!(ctx.check_list_len("items", 5, "test").is_ok());
    }

    #[test]
    fn check_list_len_err_when_exceeds_limit() {
        let ctx = BudgetContext::new(ToolBudget::CHEAP);
        let err = ctx
            .check_list_len("items", ToolBudget::CHEAP.max_list_items + 1, "my_tool")
            .unwrap_err();
        assert!(err.error.as_deref().unwrap_or("").contains("exceeds limit"));
    }

    #[test]
    fn remaining_time_ms_some_when_deadline_set() {
        let ctx = BudgetContext::new(ToolBudget::CHEAP);
        let remaining = ctx.remaining_time_ms();
        assert!(remaining.is_some());
        assert!(remaining.unwrap() > 0);
        assert!(remaining.unwrap() <= ToolBudget::CHEAP.max_elapsed_ms);
    }

    #[test]
    fn remaining_time_ms_none_when_no_deadline() {
        let ctx = BudgetContext {
            deadline: None,
            budget: ToolBudget::CHEAP,
            cancelled: None,
        };
        assert_eq!(ctx.remaining_time_ms(), None);
    }

    #[test]
    fn remaining_time_ms_zero_when_expired() {
        let ctx = BudgetContext {
            deadline: Some(Instant::now() - Duration::from_millis(100)),
            budget: ToolBudget::CHEAP,
            cancelled: None,
        };
        assert_eq!(ctx.remaining_time_ms(), Some(0));
    }

    // ── Thread-local cancellation flag tests ────────────────────────────

    #[test]
    fn with_cancel_flag_sets_and_restores() {
        assert!(current_cancel_flag().is_none());
        let flag = Arc::new(AtomicBool::new(true));
        let captured = with_cancel_flag(Some(flag.clone()), || current_cancel_flag().unwrap());
        assert!(Arc::ptr_eq(&captured, &flag));
        // Previous flag restored
        assert!(current_cancel_flag().is_none());
    }

    #[test]
    fn with_cancel_flag_nested_calls_restore_previous() {
        let outer = Arc::new(AtomicBool::new(false));
        let inner = Arc::new(AtomicBool::new(true));
        with_cancel_flag(Some(outer.clone()), || {
            assert!(current_cancel_flag().is_some());
            with_cancel_flag(Some(inner.clone()), || {
                assert!(Arc::ptr_eq(&current_cancel_flag().unwrap(), &inner));
            });
            // Inner scope finished — outer flag restored
            assert!(Arc::ptr_eq(&current_cancel_flag().unwrap(), &outer));
        });
        assert!(current_cancel_flag().is_none());
    }

    #[test]
    fn with_cancel_flag_none_restores_none() {
        let flag = Arc::new(AtomicBool::new(false));
        with_cancel_flag(Some(flag.clone()), || {
            assert!(current_cancel_flag().is_some());
        });
        assert!(current_cancel_flag().is_none());
    }

    #[test]
    fn for_handler_picks_up_cancel_flag() {
        let flag = Arc::new(AtomicBool::new(true));
        let ctx = with_cancel_flag(Some(flag.clone()), || for_handler(ToolBudget::CHEAP));
        assert!(ctx.is_cancelled());
        assert!(ctx.should_stop());
    }

    #[test]
    fn for_handler_without_flag_has_no_cancellation() {
        let ctx = for_handler(ToolBudget::MODERATE);
        assert!(!ctx.is_cancelled());
        assert!(!ctx.should_stop());
        assert_eq!(ctx.budget, ToolBudget::MODERATE);
    }

    #[test]
    fn for_handler_budget_is_set() {
        let ctx = for_handler(ToolBudget::HEAVY);
        assert_eq!(ctx.budget, ToolBudget::HEAVY);
        assert!(ctx.deadline.is_some());
    }
}