loopctl 0.1.0

A trait-based framework for building agent loops with pluggable LLM clients, tools, and memory
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
//! Hook executor — manages an ordered list of hooks and dispatches events.
//!
//! The executor has two modes:
//!
//! - **Check** (for pre-hooks) — returns [`HookAction`] or [`CompactResult`],
//!   short-circuits on first non-default result.
//! - **Notify** (for post-hooks) — fire-and-forget, all hooks run.
//!
//! # Pre-hook Execution Model
//!
//! For `on_pre_*` hooks, the executor iterates through hooks and returns
//! the **first non-Allow result**. Explicit `Allow` results are skipped so
//! that later safety-critical hooks are still evaluated. This ensures that
//! safety-critical hooks (registered first or last) take precedence.
//!
//! ```text
//! check_pre_tool_use(ctx)
//!   → hook_1.on_pre_tool_use(ctx) → Some(Allow) ← skip, continue
//!   → hook_2.on_pre_tool_use(ctx) → Some(Block{...}) ← short-circuit!
//!   → return Block{...}
//!   // hook_3 is never called
//! ```
//!
//! # Post-hook Execution Model
//!
//! For `on_post_*` and session hooks, the executor calls **all** hooks.
//! There's no short-circuit because post-hooks are notification-only.
//!
//! # Thread Safety
//!
//! [`HookExecutor`] is `Send + Sync` because hooks are `Arc<dyn Hook>`.
//! The executor itself has no mutable state after construction.

use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;

use crate::hooks::Hook;
use crate::hooks::HookAction;
use crate::hooks::Interactivity;
use crate::hooks::context::{
    CompactResult, PostCompactContext, PostToolUseContext, PreCompactContext, PreToolUseContext,
    SessionEndContext, SessionStartContext,
};

/// Executes hooks in registration order with short-circuit semantics.
///
/// # Interactivity
///
/// The executor carries an [`Interactivity`] mode that controls how
/// [`HookAction::Ask`] is handled:
///
/// - [`Interactivity::Headless`] (the default) — `Ask` is automatically
///   downgraded to `Block`, because there is no user to interact with.
/// - [`Interactivity::Interactive`] — `Ask` passes through unchanged,
///   allowing the agent to present a prompt to the user.
pub struct HookExecutor {
    hooks: Vec<Arc<dyn Hook>>,
    interactivity: Interactivity,
}

impl Default for HookExecutor {
    fn default() -> Self {
        Self::new()
    }
}

impl HookExecutor {
    /// Create an executor in [`Interactivity::Headless`] mode with no hooks.
    ///
    /// Use [`with_hook`](Self::with_hook) to add hooks via builder pattern,
    /// or [`register`](Self::register) for mutable registration.
    #[must_use]
    pub fn new() -> Self {
        Self {
            hooks: Vec::new(),
            interactivity: Interactivity::Headless,
        }
    }

    /// Set the interactivity mode.
    ///
    /// Use this builder method to change the mode after construction, or
    /// [`with_hook`](Self::with_hook) to add hooks via the builder pattern.
    #[must_use]
    pub fn with_interactivity(mut self, interactivity: Interactivity) -> Self {
        self.interactivity = interactivity;
        self
    }

    /// Register a hook (builder pattern).
    ///
    /// Hooks are called in registration order. Returns `self`
    /// for chaining: `HookExecutor::new().with_hook(a).with_hook(b)`.
    #[must_use]
    pub fn with_hook(mut self, hook: Arc<dyn Hook>) -> Self {
        self.hooks.push(hook);
        self
    }

    /// Register a hook (mutating).
    ///
    /// Appends a hook to the end of the execution list.
    /// Unlike [`with_hook`](Self::with_hook), this takes `&mut self`.
    pub fn register(&mut self, hook: Arc<dyn Hook>) {
        self.hooks.push(hook);
    }

    /// Downgrade [`HookAction::Ask`] to [`HookAction::Block`] in headless mode.
    ///
    /// In [`Interactivity::Headless`] mode, `Ask` is converted to `Block`
    /// with a reason that includes the original message. All other actions
    /// (including `Allow` and `Block`) pass through unchanged.
    fn apply_interactivity(&self, action: HookAction) -> HookAction {
        match (&self.interactivity, action) {
            (Interactivity::Headless, HookAction::Ask { message }) => HookAction::block(format!(
                "Hook requested confirmation ({message}) but the session is not interactive"
            )),
            (_, action) => action,
        }
    }

    /// Number of registered hooks.
    ///
    /// Returns 0 for a freshly constructed executor.
    #[must_use]
    pub fn hook_count(&self) -> usize {
        self.hooks.len()
    }

    // ==================================================
    // Pre-hook checks (short-circuit on first non-None)
    // ==================================================

    /// Check pre-tool-use hooks.
    ///
    /// Returns the first non-Allow action (e.g., `Block`, `Ask`), continuing
    /// past explicit `Allow` results so that later safety-critical hooks are
    /// still evaluated. Returns [`HookAction::Allow`] if no hook produced a
    /// non-Allow action.
    ///
    /// In [`Interactivity::Headless`] mode, [`HookAction::Ask`] is
    /// automatically downgraded to [`HookAction::Block`].
    #[must_use]
    pub fn check_pre_tool_use(&self, ctx: &PreToolUseContext) -> HookAction {
        for hook in &self.hooks {
            if let Some(action) = hook.on_pre_tool_use(ctx) {
                match action {
                    HookAction::Allow => {}
                    other => return self.apply_interactivity(other),
                }
            }
        }
        HookAction::Allow
    }

    /// Async wrapper for [`check_pre_tool_use`](Self::check_pre_tool_use).
    ///
    /// Runs the synchronous check and wraps the result in a `Pin<Box<Future>>`
    /// for use in async contexts without spawning a separate task.
    #[must_use]
    pub fn check_pre_tool_use_async(
        &self,
        ctx: &PreToolUseContext,
    ) -> Pin<Box<dyn Future<Output = HookAction> + Send + '_>> {
        let action = self.check_pre_tool_use(ctx);
        Box::pin(async move { action })
    }

    /// Check pre-compact hooks. Merges results from all hooks:
    /// - If any hook aborts, returns immediately with abort.
    /// - Instructions from later hooks override earlier ones.
    /// - Additional contexts accumulate.
    #[must_use]
    pub fn check_pre_compact(&self, ctx: &PreCompactContext) -> CompactResult {
        let mut result = CompactResult::allow();
        for hook in &self.hooks {
            if let Some(hook_result) = hook.on_pre_compact(ctx) {
                if hook_result.abort {
                    return hook_result;
                }
                if let Some(instr) = hook_result.new_instructions {
                    result.new_instructions = Some(instr);
                }
                result
                    .additional_context
                    .extend(hook_result.additional_context);
            }
        }
        result
    }

    /// Async wrapper for [`check_pre_compact`](Self::check_pre_compact).
    ///
    /// Runs the synchronous check and wraps the result in a `Pin<Box<Future>>`
    /// for use in async contexts without spawning a separate task.
    #[must_use]
    pub fn check_pre_compact_async(
        &self,
        ctx: &PreCompactContext,
    ) -> Pin<Box<dyn Future<Output = CompactResult> + Send + '_>> {
        let result = self.check_pre_compact(ctx);
        Box::pin(async move { result })
    }

    // ==================================================
    // Post-hook notifications (all hooks run)
    // ==================================================

    /// Notify all post-tool-use hooks.
    ///
    /// All registered hooks are called regardless of return value.
    pub fn notify_post_tool_use(&self, ctx: &PostToolUseContext) {
        for hook in &self.hooks {
            hook.on_post_tool_use(ctx);
        }
    }

    /// Async wrapper for [`notify_post_tool_use`](Self::notify_post_tool_use).
    ///
    /// Runs all post-tool-use hooks synchronously and wraps completion
    /// in a `Pin<Box<Future>>` for async compatibility.
    #[must_use]
    pub fn notify_post_tool_use_async(
        &self,
        ctx: &PostToolUseContext,
    ) -> Pin<Box<dyn Future<Output = ()> + Send + '_>> {
        self.notify_post_tool_use(ctx);
        Box::pin(async {})
    }

    /// Notify all post-compact hooks.
    ///
    /// All registered hooks are called regardless of return value.
    pub fn notify_post_compact(&self, ctx: &PostCompactContext) {
        for hook in &self.hooks {
            hook.on_post_compact(ctx);
        }
    }

    /// Notify all session-start hooks.
    ///
    /// All registered hooks are called regardless of return value.
    pub fn notify_session_start(&self, ctx: &SessionStartContext) {
        for hook in &self.hooks {
            hook.on_session_start(ctx);
        }
    }

    /// Notify all session-end hooks.
    ///
    /// All registered hooks are called regardless of return value.
    pub fn notify_session_end(&self, ctx: &SessionEndContext) {
        for hook in &self.hooks {
            hook.on_session_end(ctx);
        }
    }

    /// Async wrapper for [`notify_post_compact`](Self::notify_post_compact).
    ///
    /// Runs all post-compact hooks synchronously and wraps completion
    /// in a `Pin<Box<Future>>` for async compatibility.
    #[must_use]
    pub fn notify_post_compact_async(
        &self,
        ctx: &PostCompactContext,
    ) -> Pin<Box<dyn Future<Output = ()> + Send + '_>> {
        self.notify_post_compact(ctx);
        Box::pin(async {})
    }

    /// Async wrapper for [`notify_session_start`](Self::notify_session_start).
    ///
    /// Runs all session-start hooks synchronously and wraps completion
    /// in a `Pin<Box<Future>>` for async compatibility.
    #[must_use]
    pub fn notify_session_start_async(
        &self,
        ctx: &SessionStartContext,
    ) -> Pin<Box<dyn Future<Output = ()> + Send + '_>> {
        self.notify_session_start(ctx);
        Box::pin(async {})
    }

    /// Async wrapper for [`notify_session_end`](Self::notify_session_end).
    ///
    /// Runs all session-end hooks synchronously and wraps completion
    /// in a `Pin<Box<Future>>` for async compatibility.
    #[must_use]
    pub fn notify_session_end_async(
        &self,
        ctx: &SessionEndContext,
    ) -> Pin<Box<dyn Future<Output = ()> + Send + '_>> {
        self.notify_session_end(ctx);
        Box::pin(async {})
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::hooks::context::{CompactTrigger, SessionEndReason};
    use serde_json::json;

    struct AllowHook;
    impl Hook for AllowHook {
        fn name(&self) -> &'static str {
            "allow"
        }
        fn on_pre_tool_use(&self, _ctx: &PreToolUseContext) -> Option<HookAction> {
            None
        }
    }

    struct BlockHook {
        reason: String,
    }
    impl Hook for BlockHook {
        fn name(&self) -> &'static str {
            "block"
        }
        fn on_pre_tool_use(&self, _ctx: &PreToolUseContext) -> Option<HookAction> {
            Some(HookAction::block(&self.reason))
        }
    }

    struct PostRecorder {
        called: std::sync::atomic::AtomicBool,
    }
    impl PostRecorder {
        fn new() -> Self {
            Self {
                called: std::sync::atomic::AtomicBool::new(false),
            }
        }
        fn was_called(&self) -> bool {
            self.called.load(std::sync::atomic::Ordering::Relaxed)
        }
    }
    impl Hook for PostRecorder {
        fn name(&self) -> &'static str {
            "post_recorder"
        }
        fn on_post_tool_use(&self, _ctx: &PostToolUseContext) {
            self.called
                .store(true, std::sync::atomic::Ordering::Relaxed);
        }
    }

    fn dummy_pre_ctx() -> PreToolUseContext {
        PreToolUseContext {
            tool_name: "test_tool".to_string(),
            input: json!({}),
            session_id: uuid::Uuid::nil(),
            turn_number: 0,
        }
    }

    #[test]
    fn empty_executor_allows() {
        let executor = HookExecutor::new();
        let ctx = dummy_pre_ctx();
        assert!(matches!(
            executor.check_pre_tool_use(&ctx),
            HookAction::Allow
        ));
    }

    #[test]
    fn allow_hook_passes_through() {
        let executor = HookExecutor::new().with_hook(Arc::new(AllowHook));
        let ctx = dummy_pre_ctx();
        assert!(matches!(
            executor.check_pre_tool_use(&ctx),
            HookAction::Allow
        ));
    }

    #[test]
    fn block_hook_short_circuits() {
        let executor = HookExecutor::new().with_hook(Arc::new(BlockHook {
            reason: "blocked".to_string(),
        }));
        let ctx = dummy_pre_ctx();
        let action = executor.check_pre_tool_use(&ctx);
        match action {
            HookAction::Block { reason } => assert_eq!(reason, "blocked"),
            other => panic!("expected Block, got {other:?}"),
        }
    }

    #[test]
    fn first_block_wins() {
        let executor = HookExecutor::new()
            .with_hook(Arc::new(BlockHook {
                reason: "first".to_string(),
            }))
            .with_hook(Arc::new(BlockHook {
                reason: "second".to_string(),
            }));
        let ctx = dummy_pre_ctx();
        let action = executor.check_pre_tool_use(&ctx);
        match action {
            HookAction::Block { reason } => assert_eq!(reason, "first"),
            other => panic!("expected first Block, got {other:?}"),
        }
    }

    #[test]
    fn post_hooks_all_run() {
        let recorder = Arc::new(PostRecorder::new());
        let executor = HookExecutor::new()
            .with_hook(recorder.clone())
            .with_hook(recorder.clone());
        let ctx = PostToolUseContext {
            tool_name: "test".to_string(),
            input: json!({}),
            output: "ok".to_string(),
            is_error: false,
            duration_ms: 10,
            session_id: uuid::Uuid::nil(),
            turn_number: 0,
        };
        executor.notify_post_tool_use(&ctx);
        assert!(recorder.was_called());
    }

    #[test]
    fn hook_count_tracks_registrations() {
        let executor = HookExecutor::new();
        assert_eq!(executor.hook_count(), 0);
        let executor = executor.with_hook(Arc::new(AllowHook));
        assert_eq!(executor.hook_count(), 1);
    }

    #[test]
    fn check_pre_compact_merges_instructions() {
        struct InstructionHook;
        impl Hook for InstructionHook {
            fn name(&self) -> &'static str {
                "instruction"
            }
            fn on_pre_compact(&self, _ctx: &PreCompactContext) -> Option<CompactResult> {
                Some(
                    CompactResult::allow()
                        .with_instructions("focus on tests")
                        .with_context("keep test suite"),
                )
            }
        }
        let executor = HookExecutor::new().with_hook(Arc::new(InstructionHook));
        let ctx = PreCompactContext {
            trigger: CompactTrigger::Auto,
            custom_instructions: None,
            message_count: 10,
            tokens_before: 5000,
            context_window: 200_000,
            session_id: uuid::Uuid::nil(),
        };
        let result = executor.check_pre_compact(&ctx);
        assert!(!result.abort);
        assert_eq!(result.new_instructions.as_deref(), Some("focus on tests"));
        assert_eq!(result.additional_context.len(), 1);
    }

    #[test]
    fn check_pre_compact_abort_takes_priority() {
        struct AbortHook;
        impl Hook for AbortHook {
            fn name(&self) -> &'static str {
                "abort"
            }
            fn on_pre_compact(&self, _ctx: &PreCompactContext) -> Option<CompactResult> {
                Some(CompactResult::abort("too risky"))
            }
        }
        struct InstructionHook;
        impl Hook for InstructionHook {
            fn name(&self) -> &'static str {
                "instruction"
            }
            fn on_pre_compact(&self, _ctx: &PreCompactContext) -> Option<CompactResult> {
                Some(CompactResult::allow().with_instructions("override"))
            }
        }
        let executor = HookExecutor::new()
            .with_hook(Arc::new(AbortHook))
            .with_hook(Arc::new(InstructionHook));
        let ctx = PreCompactContext {
            trigger: CompactTrigger::Auto,
            custom_instructions: None,
            message_count: 10,
            tokens_before: 5000,
            context_window: 200_000,
            session_id: uuid::Uuid::nil(),
        };
        let result = executor.check_pre_compact(&ctx);
        assert!(result.abort);
        assert_eq!(result.abort_reason.as_deref(), Some("too risky"));
        assert!(result.new_instructions.is_none());
    }

    #[test]
    fn session_start_end_notify_all() {
        use std::sync::atomic::{AtomicUsize, Ordering};
        struct CounterHook {
            starts: AtomicUsize,
            ends: AtomicUsize,
        }
        impl Hook for CounterHook {
            fn name(&self) -> &'static str {
                "counter"
            }
            fn on_session_start(&self, _ctx: &SessionStartContext) {
                self.starts.fetch_add(1, Ordering::Relaxed);
            }
            fn on_session_end(&self, _ctx: &SessionEndContext) {
                self.ends.fetch_add(1, Ordering::Relaxed);
            }
        }
        let counter = Arc::new(CounterHook {
            starts: AtomicUsize::new(0),
            ends: AtomicUsize::new(0),
        });
        let executor = HookExecutor::new()
            .with_hook(counter.clone())
            .with_hook(counter.clone());
        executor.notify_session_start(&SessionStartContext {
            session_id: uuid::Uuid::nil(),
            model: "test".to_string(),
            working_directory: "/tmp".to_string(),
        });
        assert_eq!(counter.starts.load(Ordering::Relaxed), 2);
        executor.notify_session_end(&SessionEndContext {
            session_id: uuid::Uuid::nil(),
            reason: SessionEndReason::Complete,
            total_turns: 5,
            total_tokens: 1000,
            duration_secs: 30,
        });
        assert_eq!(counter.ends.load(Ordering::Relaxed), 2);
    }

    #[test]
    fn register_adds_hook() {
        let mut executor = HookExecutor::new();
        assert_eq!(executor.hook_count(), 0);
        executor.register(Arc::new(AllowHook));
        assert_eq!(executor.hook_count(), 1);
        executor.register(Arc::new(BlockHook {
            reason: "x".to_string(),
        }));
        assert_eq!(executor.hook_count(), 2);
    }

    #[test]
    fn notify_post_tool_use_empty_executor() {
        let executor = HookExecutor::new();
        let ctx = PostToolUseContext {
            tool_name: "test".to_string(),
            input: json!({}),
            output: "ok".to_string(),
            is_error: false,
            duration_ms: 10,
            session_id: uuid::Uuid::nil(),
            turn_number: 0,
        };
        executor.notify_post_tool_use(&ctx);
    }

    #[test]
    fn notify_post_compact_runs_all_hooks() {
        use std::sync::atomic::{AtomicUsize, Ordering};
        struct CompactRecorder {
            count: AtomicUsize,
        }
        impl Hook for CompactRecorder {
            fn name(&self) -> &'static str {
                "compact_recorder"
            }
            fn on_post_compact(&self, _ctx: &PostCompactContext) {
                self.count.fetch_add(1, Ordering::Relaxed);
            }
        }
        let recorder = Arc::new(CompactRecorder {
            count: AtomicUsize::new(0),
        });
        let executor = HookExecutor::new()
            .with_hook(recorder.clone())
            .with_hook(recorder.clone());
        let ctx = PostCompactContext {
            trigger: CompactTrigger::Auto,
            messages_compacted: 5,
            tokens_saved: 3000,
            tokens_after: 2000,
            duration_ms: 100,
            session_id: uuid::Uuid::nil(),
        };
        executor.notify_post_compact(&ctx);
        assert_eq!(recorder.count.load(Ordering::Relaxed), 2);
    }

    #[test]
    fn notify_session_start_empty_executor() {
        let executor = HookExecutor::new();
        executor.notify_session_start(&SessionStartContext {
            session_id: uuid::Uuid::nil(),
            model: "test".to_string(),
            working_directory: "/tmp".to_string(),
        });
    }

    #[test]
    fn notify_session_end_empty_executor() {
        let executor = HookExecutor::new();
        executor.notify_session_end(&SessionEndContext {
            session_id: uuid::Uuid::nil(),
            reason: SessionEndReason::Complete,
            total_turns: 0,
            total_tokens: 0,
            duration_secs: 0,
        });
    }

    #[test]
    fn check_pre_tool_use_headless_downgrades_ask_to_block() {
        struct AskHook;
        impl Hook for AskHook {
            fn name(&self) -> &'static str {
                "ask"
            }
            fn on_pre_tool_use(&self, _ctx: &PreToolUseContext) -> Option<HookAction> {
                Some(HookAction::ask("confirm?"))
            }
        }

        // Default (Headless) executor downgrades Ask → Block.
        let executor = HookExecutor::new().with_hook(Arc::new(AskHook));
        let ctx = dummy_pre_ctx();
        let action = executor.check_pre_tool_use(&ctx);
        assert!(
            action.is_block(),
            "expected Block in Headless mode, got {action:?}"
        );
    }

    #[test]
    fn check_pre_tool_use_interactive_passes_ask_through() {
        struct AskHook;
        impl Hook for AskHook {
            fn name(&self) -> &'static str {
                "ask"
            }
            fn on_pre_tool_use(&self, _ctx: &PreToolUseContext) -> Option<HookAction> {
                Some(HookAction::ask("confirm?"))
            }
        }

        // Interactive executor passes Ask through unchanged.
        let executor = HookExecutor::new()
            .with_interactivity(Interactivity::Interactive)
            .with_hook(Arc::new(AskHook));
        let ctx = dummy_pre_ctx();
        let action = executor.check_pre_tool_use(&ctx);
        match action {
            HookAction::Ask { message } => assert_eq!(message, "confirm?"),
            other => panic!("expected Ask, got {other:?}"),
        }
    }

    #[test]
    fn check_pre_tool_use_interactivity_builder() {
        struct AskHook;
        impl Hook for AskHook {
            fn name(&self) -> &'static str {
                "ask"
            }
            fn on_pre_tool_use(&self, _ctx: &PreToolUseContext) -> Option<HookAction> {
                Some(HookAction::ask("ok?"))
            }
        }

        // Builder style: start Headless, switch to Interactive.
        let executor = HookExecutor::new()
            .with_interactivity(Interactivity::Interactive)
            .with_hook(Arc::new(AskHook));
        let ctx = dummy_pre_ctx();
        let action = executor.check_pre_tool_use(&ctx);
        assert!(
            action.is_ask(),
            "expected Ask in Interactive mode, got {action:?}"
        );
    }

    #[test]
    fn default_is_same_as_new() {
        let default_exec = HookExecutor::default();
        let new_exec = HookExecutor::new();
        assert_eq!(default_exec.hook_count(), 0);
        assert_eq!(new_exec.hook_count(), 0);
        assert_eq!(default_exec.hook_count(), new_exec.hook_count());
    }

    #[test]
    fn headless_block_passes_through_unchanged() {
        struct BlockOnlyHook;
        impl Hook for BlockOnlyHook {
            fn name(&self) -> &'static str {
                "block_only"
            }
            fn on_pre_tool_use(&self, _ctx: &PreToolUseContext) -> Option<HookAction> {
                Some(HookAction::block("forbidden"))
            }
        }

        // Headless mode does NOT alter Block actions.
        let executor = HookExecutor::new().with_hook(Arc::new(BlockOnlyHook));
        let ctx = dummy_pre_ctx();
        let action = executor.check_pre_tool_use(&ctx);
        assert!(action.is_block());
        assert_eq!(action.block_reason(), Some("forbidden"));
    }

    #[test]
    fn headless_downgrade_preserves_original_message() {
        struct AskHook;
        impl Hook for AskHook {
            fn name(&self) -> &'static str {
                "ask"
            }
            fn on_pre_tool_use(&self, _ctx: &PreToolUseContext) -> Option<HookAction> {
                Some(HookAction::ask("please confirm deployment"))
            }
        }

        let executor = HookExecutor::new().with_hook(Arc::new(AskHook));
        let ctx = dummy_pre_ctx();
        let action = executor.check_pre_tool_use(&ctx);
        let reason = action
            .block_reason()
            .expect("downgraded action should be a Block with a reason");
        assert!(
            reason.contains("please confirm deployment"),
            "Block reason should contain the original Ask message, got: {reason}"
        );
        assert!(
            reason.contains("not interactive"),
            "Block reason should explain the downgrade, got: {reason}"
        );
    }

    #[test]
    fn with_interactivity_constructor_sets_mode() {
        struct AskHook;
        impl Hook for AskHook {
            fn name(&self) -> &'static str {
                "ask"
            }
            fn on_pre_tool_use(&self, _ctx: &PreToolUseContext) -> Option<HookAction> {
                Some(HookAction::ask("ok?"))
            }
        }

        // with_interactivity(Headless) should downgrade.
        let headless = HookExecutor::new()
            .with_interactivity(Interactivity::Headless)
            .with_hook(Arc::new(AskHook));
        assert!(
            headless.check_pre_tool_use(&dummy_pre_ctx()).is_block(),
            "Headless via with_interactivity should downgrade Ask"
        );
    }

    #[test]
    fn interactive_block_passes_through_unchanged() {
        struct BlockOnlyHook;
        impl Hook for BlockOnlyHook {
            fn name(&self) -> &'static str {
                "block_only"
            }
            fn on_pre_tool_use(&self, _ctx: &PreToolUseContext) -> Option<HookAction> {
                Some(HookAction::block("forbidden"))
            }
        }

        // Interactive mode does NOT alter Block actions.
        let executor = HookExecutor::new()
            .with_interactivity(Interactivity::Interactive)
            .with_hook(Arc::new(BlockOnlyHook));
        let ctx = dummy_pre_ctx();
        let action = executor.check_pre_tool_use(&ctx);
        assert!(action.is_block());
        assert_eq!(action.block_reason(), Some("forbidden"));
    }

    #[test]
    fn no_hooks_returns_allow_in_headless() {
        let executor = HookExecutor::new();
        let ctx = dummy_pre_ctx();
        assert!(executor.check_pre_tool_use(&ctx).is_allow());
    }

    #[test]
    fn no_hooks_returns_allow_in_interactive() {
        let executor = HookExecutor::new().with_interactivity(Interactivity::Interactive);
        let ctx = dummy_pre_ctx();
        assert!(executor.check_pre_tool_use(&ctx).is_allow());
    }
}