imp-core 0.2.0

Agent engine for imp: loop, tools, sessions, hooks, context, and SDK
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
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
use std::path::Path;
use std::sync::Arc;

use glob::Pattern;
use imp_llm::{AssistantMessage, ContentBlock, Message, ToolResultMessage};
use serde::{Deserialize, Serialize};
use tokio::process::Command;

/// Reports outcomes from background non-blocking hook execution.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum HookBackgroundEvent {
    NonBlockingHookFailed {
        event: String,
        command: String,
        error: String,
    },
    NonBlockingHookPanicked {
        event: String,
        command: String,
        error: String,
    },
}

impl std::fmt::Display for HookBackgroundEvent {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::NonBlockingHookFailed {
                event,
                command,
                error,
            } => write!(
                f,
                "Non-blocking hook failed for event '{event}' while running `{command}`: {error}"
            ),
            Self::NonBlockingHookPanicked {
                event,
                command,
                error,
            } => write!(
                f,
                "Non-blocking hook panicked for event '{event}' while running `{command}`: {error}"
            ),
        }
    }
}

/// Hook definition from TOML config.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HookDef {
    pub event: String,
    #[serde(rename = "match")]
    pub match_pattern: Option<String>,
    pub action: String,
    pub command: Option<String>,
    #[serde(default)]
    pub blocking: bool,
    pub threshold: Option<f64>,
}

/// What a hook does when triggered.
#[derive(Clone)]
pub enum HookAction {
    /// Run a shell command with interpolation ({file}, {tool_name}).
    Shell { command: String },
    /// A programmatic callback (for Lua or other extensions).
    Callback(Arc<dyn Fn(&HookEvent<'_>) -> HookResult + Send + Sync>),
}

impl std::fmt::Debug for HookAction {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            HookAction::Shell { command } => {
                f.debug_struct("Shell").field("command", command).finish()
            }
            HookAction::Callback(_) => f.write_str("Callback(...)"),
        }
    }
}

/// A fully resolved hook definition ready for execution.
#[derive(Debug, Clone)]
pub struct HookDefinition {
    pub event: String,
    pub match_pattern: Option<String>,
    pub action: HookAction,
    pub blocking: bool,
    pub threshold: Option<f64>,
}

/// Runtime hook events.
#[derive(Clone)]
pub enum HookEvent<'a> {
    AfterFileWrite {
        file: &'a Path,
    },
    BeforeToolCall {
        tool_name: &'a str,
        args: &'a serde_json::Value,
    },
    AfterToolCall {
        tool_name: &'a str,
        result: &'a ToolResultMessage,
    },
    BeforeLlmCall,
    OnContextThreshold {
        ratio: f64,
    },
    OnSessionStart,
    OnSessionShutdown,
    OnAgentStart {
        prompt: &'a str,
    },
    OnAgentEnd {
        messages: &'a [Message],
    },
    OnTurnEnd {
        index: u32,
        message: &'a AssistantMessage,
    },
}

impl<'a> HookEvent<'a> {
    /// Return the canonical event name for matching against hook definitions.
    fn event_name(&self) -> &'static str {
        match self {
            HookEvent::AfterFileWrite { .. } => "after_file_write",
            HookEvent::BeforeToolCall { .. } => "before_tool_call",
            HookEvent::AfterToolCall { .. } => "after_tool_call",
            HookEvent::BeforeLlmCall => "before_llm_call",
            HookEvent::OnContextThreshold { .. } => "on_context_threshold",
            HookEvent::OnSessionStart => "on_session_start",
            HookEvent::OnSessionShutdown => "on_session_shutdown",
            HookEvent::OnAgentStart { .. } => "on_agent_start",
            HookEvent::OnAgentEnd { .. } => "on_agent_end",
            HookEvent::OnTurnEnd { .. } => "on_turn_end",
        }
    }
}

/// Result from a hook execution.
#[derive(Default, Debug)]
pub struct HookResult {
    pub block: bool,
    pub reason: Option<String>,
    pub modified_content: Option<Vec<ContentBlock>>,
}

/// Manages and executes hooks.
pub struct HookRunner {
    /// TOML-defined hooks (fire first, in config order).
    toml_hooks: Vec<HookDefinition>,
    /// Programmatically registered hooks (fire after TOML hooks, in registration order).
    programmatic_hooks: Vec<HookDefinition>,
    /// Optional observer for background non-blocking hook failures.
    background_reporter: Option<Arc<dyn Fn(HookBackgroundEvent) + Send + Sync>>,
}

impl HookRunner {
    pub fn new() -> Self {
        Self {
            toml_hooks: Vec::new(),
            programmatic_hooks: Vec::new(),
            background_reporter: None,
        }
    }

    /// Add a single TOML hook def (raw from config).
    pub fn add(&mut self, def: HookDef) {
        if let Some(resolved) = resolve_hook_def(def) {
            self.toml_hooks.push(resolved);
        }
    }

    /// Load multiple TOML hook defs from config.
    pub fn load_from_config(&mut self, defs: Vec<HookDef>) {
        for def in defs {
            self.add(def);
        }
    }

    /// Register a programmatic hook (for Lua or other extensions).
    pub fn register(&mut self, hook: HookDefinition) {
        self.programmatic_hooks.push(hook);
    }

    /// Returns the total number of registered hooks (TOML + programmatic).
    pub fn len(&self) -> usize {
        self.toml_hooks.len() + self.programmatic_hooks.len()
    }

    /// Returns true if no hooks are registered.
    pub fn is_empty(&self) -> bool {
        self.toml_hooks.is_empty() && self.programmatic_hooks.is_empty()
    }

    /// Register an observer for background non-blocking hook failures.
    pub fn set_background_reporter(
        &mut self,
        reporter: Arc<dyn Fn(HookBackgroundEvent) + Send + Sync>,
    ) {
        self.background_reporter = Some(reporter);
    }

    /// Register a callback hook for a specific event.
    pub fn register_callback(
        &mut self,
        event: &str,
        callback: Arc<dyn Fn(&HookEvent<'_>) -> HookResult + Send + Sync>,
    ) {
        self.programmatic_hooks.push(HookDefinition {
            event: event.to_string(),
            match_pattern: None,
            action: HookAction::Callback(callback),
            blocking: true,
            threshold: None,
        });
    }

    /// Fire a hook event and collect results.
    ///
    /// Execution order: TOML hooks first (config order), then programmatic hooks (registration order).
    /// Blocking hooks execute sequentially and await completion.
    /// Non-blocking hooks are spawned as background tokio tasks.
    pub async fn fire(&self, event: &HookEvent<'_>) -> Vec<HookResult> {
        let mut results = Vec::new();

        // TOML hooks first, then programmatic hooks
        let all_hooks = self.toml_hooks.iter().chain(self.programmatic_hooks.iter());

        for hook in all_hooks {
            if !matches_event(hook, event) {
                continue;
            }

            if hook.blocking {
                let result = execute_hook(hook, event).await;
                results.push(result);
            } else {
                // Keep non-blocking hooks asynchronous, but supervise failures.
                if let HookAction::Shell { command } = &hook.action {
                    let cmd = interpolate_command(command, event);
                    run_non_blocking_shell_hook(
                        hook_event_label(event),
                        cmd,
                        self.background_reporter.clone(),
                    );
                }
                // Non-blocking hooks don't contribute results
            }
        }

        results
    }
}

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

fn hook_event_label(event: &HookEvent<'_>) -> String {
    event.event_name().to_string()
}

fn report_non_blocking_hook_outcome(
    join_result: Result<std::io::Result<std::process::Output>, tokio::task::JoinError>,
    event_name: String,
    command_for_report: String,
    reporter: Arc<dyn Fn(HookBackgroundEvent) + Send + Sync>,
) {
    match join_result {
        Ok(Ok(output)) => {
            if !output.status.success() {
                let stdout = String::from_utf8_lossy(&output.stdout).trim().to_string();
                let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
                let error = if !stderr.is_empty() {
                    stderr
                } else if !stdout.is_empty() {
                    stdout
                } else {
                    format!(
                        "command exited with status {}",
                        output
                            .status
                            .code()
                            .map(|code| code.to_string())
                            .unwrap_or_else(|| "terminated by signal".into())
                    )
                };
                reporter(HookBackgroundEvent::NonBlockingHookFailed {
                    event: event_name,
                    command: command_for_report,
                    error,
                });
            }
        }
        Ok(Err(error)) => reporter(HookBackgroundEvent::NonBlockingHookFailed {
            event: event_name,
            command: command_for_report,
            error: error.to_string(),
        }),
        Err(join_error) => reporter(HookBackgroundEvent::NonBlockingHookPanicked {
            event: event_name,
            command: command_for_report,
            error: join_error.to_string(),
        }),
    }
}

fn run_non_blocking_shell_hook(
    event_name: String,
    command: String,
    reporter: Option<Arc<dyn Fn(HookBackgroundEvent) + Send + Sync>>,
) {
    tokio::spawn(async move {
        let command_for_run = command.clone();
        let command_for_report = command;
        let join_result = tokio::spawn(async move {
            Command::new("sh")
                .arg("-c")
                .arg(&command_for_run)
                .stdin(std::process::Stdio::null())
                .output()
                .await
        })
        .await;

        if let Some(reporter) = reporter {
            report_non_blocking_hook_outcome(join_result, event_name, command_for_report, reporter);
        }
    });
}

fn resolve_hook_def(def: HookDef) -> Option<HookDefinition> {
    let action = match def.action.as_str() {
        "shell" => {
            let command = def.command?;
            HookAction::Shell { command }
        }
        _ => return None,
    };

    Some(HookDefinition {
        event: def.event,
        match_pattern: def.match_pattern,
        action,
        blocking: def.blocking,
        threshold: def.threshold,
    })
}

/// Check if a hook definition matches the given event.
fn matches_event(hook: &HookDefinition, event: &HookEvent<'_>) -> bool {
    // Event name must match
    if hook.event != event.event_name() {
        return false;
    }

    // Check match_pattern if present
    if let Some(pattern) = &hook.match_pattern {
        match event {
            HookEvent::AfterFileWrite { file } => {
                let file_str = file.to_string_lossy();
                // Try glob matching against the full path and filename
                if let Ok(glob) = Pattern::new(pattern) {
                    let file_name = file
                        .file_name()
                        .map(|n| n.to_string_lossy().to_string())
                        .unwrap_or_default();
                    if !glob.matches(&file_str) && !glob.matches(&file_name) {
                        return false;
                    }
                } else {
                    return false;
                }
            }
            HookEvent::BeforeToolCall { tool_name, .. }
            | HookEvent::AfterToolCall { tool_name, .. } => {
                if pattern != *tool_name {
                    // Also try glob matching on tool name
                    if let Ok(glob) = Pattern::new(pattern) {
                        if !glob.matches(tool_name) {
                            return false;
                        }
                    } else {
                        return false;
                    }
                }
            }
            _ => {
                // Other events ignore match_pattern
            }
        }
    }

    // Check threshold for OnContextThreshold
    if let HookEvent::OnContextThreshold { ratio } = event {
        if let Some(threshold) = hook.threshold {
            if *ratio < threshold {
                return false;
            }
        }
    }

    true
}

/// Interpolate variables into a shell command string.
fn interpolate_command(command: &str, event: &HookEvent<'_>) -> String {
    let mut result = command.to_string();

    match event {
        HookEvent::AfterFileWrite { file } => {
            result = replace_placeholder(&result, "file", &file.to_string_lossy());
        }
        HookEvent::BeforeToolCall { tool_name, .. } => {
            result = replace_placeholder(&result, "tool_name", tool_name);
        }
        HookEvent::AfterToolCall {
            tool_name,
            result: tool_result,
        } => {
            result = replace_placeholder(&result, "tool_name", tool_name);
            result = replace_placeholder(
                &result,
                "is_error",
                if tool_result.is_error {
                    "true"
                } else {
                    "false"
                },
            );
            // Extract exit_code from details if present (bash tool sets this)
            let exit_code = tool_result
                .details
                .get("exit_code")
                .and_then(|v| v.as_i64())
                .map(|c| c.to_string())
                .unwrap_or_default();
            result = replace_placeholder(&result, "exit_code", &exit_code);
            // First line of output for summary
            let output_first = tool_result
                .content
                .iter()
                .filter_map(|b| match b {
                    imp_llm::ContentBlock::Text { text } => Some(text.as_str()),
                    _ => None,
                })
                .next()
                .and_then(|t| t.lines().next())
                .unwrap_or("");
            result = replace_placeholder(&result, "output_first_line", output_first);
            // Extract command from details (bash tool stores it)
            let command = tool_result
                .details
                .get("command")
                .and_then(|v| v.as_str())
                .unwrap_or("");
            result = replace_placeholder(&result, "command", command);
        }
        HookEvent::OnContextThreshold { ratio } => {
            result = replace_placeholder(&result, "ratio", &ratio.to_string());
        }
        HookEvent::OnTurnEnd { index, .. } => {
            result = replace_placeholder(&result, "index", &index.to_string());
        }
        _ => {}
    }

    result
}

fn replace_placeholder(template: &str, name: &str, value: &str) -> String {
    let raw = format!("{{{name}}}");
    let single_marker = format!("\u{0}__imp_hook_single_{name}__\u{0}");
    let double_marker = format!("\u{0}__imp_hook_double_{name}__\u{0}");

    let mut result = template.replace(&format!("'{raw}'"), &single_marker);
    result = result.replace(&format!("\"{raw}\""), &double_marker);
    result = result.replace(&raw, value);
    result = result.replace(&single_marker, &shell_single_quote(value));
    result = result.replace(&double_marker, &shell_double_quote(value));
    result
}

fn shell_single_quote(value: &str) -> String {
    format!("'{}'", value.replace('\'', "'\\''"))
}

fn shell_double_quote(value: &str) -> String {
    let mut escaped = String::with_capacity(value.len());
    for ch in value.chars() {
        match ch {
            '\\' | '"' | '$' | '`' => {
                escaped.push('\\');
                escaped.push(ch);
            }
            _ => escaped.push(ch),
        }
    }
    format!("\"{escaped}\"")
}

/// Execute a single hook and return its result.
async fn execute_hook(hook: &HookDefinition, event: &HookEvent<'_>) -> HookResult {
    match &hook.action {
        HookAction::Shell { command } => {
            let cmd = interpolate_command(command, event);
            match Command::new("sh")
                .arg("-c")
                .arg(&cmd)
                .stdin(std::process::Stdio::null())
                .output()
                .await
            {
                Ok(output) => {
                    let stdout = String::from_utf8_lossy(&output.stdout).to_string();
                    let stderr = String::from_utf8_lossy(&output.stderr).to_string();

                    // A non-zero exit code on a BeforeToolCall hook means "block"
                    let block = matches!(event, HookEvent::BeforeToolCall { .. })
                        && !output.status.success();

                    let reason = if block {
                        Some(if stderr.is_empty() {
                            stdout.clone()
                        } else {
                            stderr
                        })
                    } else {
                        None
                    };

                    // For AfterToolCall, stdout is treated as modified content
                    let modified_content = if matches!(event, HookEvent::AfterToolCall { .. })
                        && !stdout.trim().is_empty()
                        && output.status.success()
                    {
                        Some(vec![ContentBlock::Text {
                            text: stdout.trim().to_string(),
                        }])
                    } else {
                        None
                    };

                    HookResult {
                        block,
                        reason,
                        modified_content,
                    }
                }
                Err(e) => HookResult {
                    block: false,
                    reason: Some(format!("Hook command failed: {e}")),
                    modified_content: None,
                },
            }
        }
        HookAction::Callback(cb) => cb(event),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::PathBuf;
    use std::sync::Mutex;

    #[test]
    fn hook_def_toml_parsing() {
        let toml_str = r#"
[[hooks]]
event = "after_file_write"
match = "*.rs"
action = "shell"
command = "rustfmt {file}"
blocking = true

[[hooks]]
event = "on_context_threshold"
action = "shell"
command = "echo threshold"
threshold = 0.8
"#;

        #[derive(Deserialize)]
        struct Wrapper {
            hooks: Vec<HookDef>,
        }

        let parsed: Wrapper = toml::from_str(toml_str).expect("TOML parsing failed");
        assert_eq!(parsed.hooks.len(), 2);

        let h0 = &parsed.hooks[0];
        assert_eq!(h0.event, "after_file_write");
        assert_eq!(h0.match_pattern.as_deref(), Some("*.rs"));
        assert_eq!(h0.action, "shell");
        assert_eq!(h0.command.as_deref(), Some("rustfmt {file}"));
        assert!(h0.blocking);
        assert!(h0.threshold.is_none());

        let h1 = &parsed.hooks[1];
        assert_eq!(h1.event, "on_context_threshold");
        assert!(h1.match_pattern.is_none());
        assert_eq!(h1.threshold, Some(0.8));
    }

    #[test]
    fn hook_interpolation_file() {
        let event = HookEvent::AfterFileWrite {
            file: Path::new("/tmp/test.rs"),
        };
        let result = interpolate_command("rustfmt {file}", &event);
        assert_eq!(result, "rustfmt /tmp/test.rs");
    }

    #[test]
    fn hook_interpolation_tool_name() {
        let args = serde_json::json!({"path": "/tmp"});
        let event = HookEvent::BeforeToolCall {
            tool_name: "bash",
            args: &args,
        };
        let result = interpolate_command("echo {tool_name}", &event);
        assert_eq!(result, "echo bash");
    }

    #[test]
    fn hook_interpolation_quoted_placeholder() {
        let command_text = "pwd && egrep '(^|/)(README|VISION)\\.md$' && printf '$HOME'";
        let result_msg = ToolResultMessage {
            tool_call_id: "call_quoted".into(),
            tool_name: "bash".into(),
            content: vec![ContentBlock::Text { text: "ok".into() }],
            is_error: true,
            details: serde_json::json!({
                "exit_code": 2,
                "command": command_text,
            }),
            timestamp: 0,
        };
        let event = HookEvent::AfterToolCall {
            tool_name: "bash",
            result: &result_msg,
        };

        let interpolated = interpolate_command(
            "hook '{is_error}' '{exit_code}' '{command}' \"{command}\" {command}",
            &event,
        );

        assert_eq!(
            interpolated,
            format!(
                "hook 'true' '2' {} {} {}",
                shell_single_quote(command_text),
                shell_double_quote(command_text),
                command_text
            )
        );
    }

    #[test]
    fn hook_interpolation_ratio() {
        let event = HookEvent::OnContextThreshold { ratio: 0.75 };
        let result = interpolate_command("echo ratio={ratio}", &event);
        assert_eq!(result, "echo ratio=0.75");
    }

    #[test]
    fn hook_event_name_mapping() {
        let path = PathBuf::from("/tmp/test.rs");
        assert_eq!(
            HookEvent::AfterFileWrite { file: &path }.event_name(),
            "after_file_write"
        );
        assert_eq!(HookEvent::BeforeLlmCall.event_name(), "before_llm_call");
        assert_eq!(HookEvent::OnSessionStart.event_name(), "on_session_start");
        assert_eq!(
            HookEvent::OnSessionShutdown.event_name(),
            "on_session_shutdown"
        );
        assert_eq!(
            HookEvent::OnContextThreshold { ratio: 0.5 }.event_name(),
            "on_context_threshold"
        );
    }

    #[test]
    fn hook_matches_event_name() {
        let hook = HookDefinition {
            event: "after_file_write".into(),
            match_pattern: None,
            action: HookAction::Shell {
                command: "echo hi".into(),
            },
            blocking: false,
            threshold: None,
        };
        let path = PathBuf::from("/tmp/test.rs");
        let event = HookEvent::AfterFileWrite { file: &path };
        assert!(matches_event(&hook, &event));

        let wrong_event = HookEvent::BeforeLlmCall;
        assert!(!matches_event(&hook, &wrong_event));
    }

    #[test]
    fn hook_matches_file_glob() {
        let hook = HookDefinition {
            event: "after_file_write".into(),
            match_pattern: Some("*.rs".into()),
            action: HookAction::Shell {
                command: "echo hi".into(),
            },
            blocking: false,
            threshold: None,
        };

        let rs_path = PathBuf::from("/tmp/test.rs");
        let rs_event = HookEvent::AfterFileWrite { file: &rs_path };
        assert!(matches_event(&hook, &rs_event));

        let py_path = PathBuf::from("/tmp/test.py");
        let py_event = HookEvent::AfterFileWrite { file: &py_path };
        assert!(!matches_event(&hook, &py_event));
    }

    #[test]
    fn hook_matches_tool_name() {
        let hook = HookDefinition {
            event: "before_tool_call".into(),
            match_pattern: Some("bash".into()),
            action: HookAction::Shell {
                command: "echo hi".into(),
            },
            blocking: true,
            threshold: None,
        };

        let args = serde_json::json!({});
        let match_event = HookEvent::BeforeToolCall {
            tool_name: "bash",
            args: &args,
        };
        assert!(matches_event(&hook, &match_event));

        let no_match_event = HookEvent::BeforeToolCall {
            tool_name: "read",
            args: &args,
        };
        assert!(!matches_event(&hook, &no_match_event));
    }

    #[test]
    fn hook_threshold_filtering() {
        let hook = HookDefinition {
            event: "on_context_threshold".into(),
            match_pattern: None,
            action: HookAction::Shell {
                command: "echo hi".into(),
            },
            blocking: true,
            threshold: Some(0.8),
        };

        // Below threshold — should not match
        let below = HookEvent::OnContextThreshold { ratio: 0.5 };
        assert!(!matches_event(&hook, &below));

        // At threshold — should match
        let at = HookEvent::OnContextThreshold { ratio: 0.8 };
        assert!(matches_event(&hook, &at));

        // Above threshold — should match
        let above = HookEvent::OnContextThreshold { ratio: 0.95 };
        assert!(matches_event(&hook, &above));
    }

    #[test]
    fn hook_resolve_shell() {
        let def = HookDef {
            event: "after_file_write".into(),
            match_pattern: Some("*.rs".into()),
            action: "shell".into(),
            command: Some("rustfmt {file}".into()),
            blocking: true,
            threshold: None,
        };
        let resolved = resolve_hook_def(def).expect("should resolve");
        assert_eq!(resolved.event, "after_file_write");
        assert!(resolved.blocking);
        assert!(matches!(resolved.action, HookAction::Shell { .. }));
    }

    #[test]
    fn hook_resolve_missing_command_returns_none() {
        let def = HookDef {
            event: "after_file_write".into(),
            match_pattern: None,
            action: "shell".into(),
            command: None,
            blocking: false,
            threshold: None,
        };
        assert!(resolve_hook_def(def).is_none());
    }

    #[test]
    fn hook_resolve_unknown_action_returns_none() {
        let def = HookDef {
            event: "after_file_write".into(),
            match_pattern: None,
            action: "unknown".into(),
            command: Some("echo".into()),
            blocking: false,
            threshold: None,
        };
        assert!(resolve_hook_def(def).is_none());
    }

    #[tokio::test]
    async fn hook_blocking_shell_executes() {
        let mut runner = HookRunner::new();
        runner.load_from_config(vec![HookDef {
            event: "after_file_write".into(),
            match_pattern: None,
            action: "shell".into(),
            command: Some("echo hello".into()),
            blocking: true,
            threshold: None,
        }]);

        let path = PathBuf::from("/tmp/test.txt");
        let event = HookEvent::AfterFileWrite { file: &path };
        let results = runner.fire(&event).await;
        assert_eq!(results.len(), 1);
        assert!(!results[0].block);
    }

    #[tokio::test]
    async fn hook_non_blocking_fires_and_forgets() {
        let mut runner = HookRunner::new();
        runner.load_from_config(vec![HookDef {
            event: "on_session_start".into(),
            match_pattern: None,
            action: "shell".into(),
            command: Some("echo non-blocking".into()),
            blocking: false,
            threshold: None,
        }]);

        let event = HookEvent::OnSessionStart;
        let started = std::time::Instant::now();
        let results = runner.fire(&event).await;
        // Non-blocking hooks don't return results
        assert!(results.is_empty());
        assert!(started.elapsed() < std::time::Duration::from_secs(1));
    }

    #[tokio::test]
    async fn hook_non_blocking_failure_is_reported() {
        let mut runner = HookRunner::new();
        let reported = Arc::new(Mutex::new(Vec::new()));
        let reported_clone = Arc::clone(&reported);
        runner.set_background_reporter(Arc::new(move |event| {
            reported_clone.lock().unwrap().push(event);
        }));
        runner.load_from_config(vec![HookDef {
            event: "on_session_start".into(),
            match_pattern: None,
            action: "shell".into(),
            command: Some("exit 7".into()),
            blocking: false,
            threshold: None,
        }]);

        let event = HookEvent::OnSessionStart;
        let results = runner.fire(&event).await;
        assert!(results.is_empty());

        for _ in 0..20 {
            if !reported.lock().unwrap().is_empty() {
                break;
            }
            tokio::time::sleep(std::time::Duration::from_millis(25)).await;
        }

        let reported = reported.lock().unwrap();
        assert_eq!(reported.len(), 1);
        match &reported[0] {
            HookBackgroundEvent::NonBlockingHookFailed { event, command, .. } => {
                assert_eq!(event, "on_session_start");
                assert_eq!(command, "exit 7");
            }
            other => panic!("expected non-blocking hook failure, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn hook_after_tool_call_nonblocking_quoted_command() {
        let temp = tempfile::tempdir().unwrap();
        let output_path = temp.path().join("hook-args.txt");
        let script_path = temp.path().join("capture.sh");
        std::fs::write(
            &script_path,
            format!(
                "#!/bin/sh\nprintf '%s\\n%s\\n%s\\n' \"$1\" \"$2\" \"$3\" > {}\n",
                output_path.display()
            ),
        )
        .unwrap();
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mut perms = std::fs::metadata(&script_path).unwrap().permissions();
            perms.set_mode(0o755);
            std::fs::set_permissions(&script_path, perms).unwrap();
        }

        let mut runner = HookRunner::new();
        runner.load_from_config(vec![HookDef {
            event: "after_tool_call".into(),
            match_pattern: Some("bash".into()),
            action: "shell".into(),
            command: Some(format!(
                "{} '{{is_error}}' '{{exit_code}}' '{{command}}'",
                script_path.display()
            )),
            blocking: false,
            threshold: None,
        }]);

        let original_command = "pwd && egrep '(^|/)(README|VISION)\\.md$' | sort && printf '$HOME'";
        let result_msg = ToolResultMessage {
            tool_call_id: "call_1".into(),
            tool_name: "bash".into(),
            content: vec![ContentBlock::Text {
                text: "failed".into(),
            }],
            is_error: true,
            details: serde_json::json!({
                "exit_code": 2,
                "command": original_command,
            }),
            timestamp: 0,
        };
        let event = HookEvent::AfterToolCall {
            tool_name: "bash",
            result: &result_msg,
        };

        let results = runner.fire(&event).await;
        assert!(results.is_empty());

        for _ in 0..40 {
            if output_path.exists() {
                break;
            }
            tokio::time::sleep(std::time::Duration::from_millis(25)).await;
        }

        let captured = std::fs::read_to_string(&output_path).unwrap();
        let mut lines = captured.lines();
        assert_eq!(lines.next(), Some("true"));
        assert_eq!(lines.next(), Some("2"));
        assert_eq!(lines.next(), Some(original_command));
    }

    #[test]
    fn report_non_blocking_hook_outcome_maps_join_failure_to_panic_event() {
        let reported = Arc::new(Mutex::new(Vec::new()));
        let reported_clone = Arc::clone(&reported);
        let reporter: Arc<dyn Fn(HookBackgroundEvent) + Send + Sync> = Arc::new(move |event| {
            reported_clone.lock().unwrap().push(event);
        });

        let previous_hook = std::panic::take_hook();
        std::panic::set_hook(Box::new(|_| {}));

        let runtime = tokio::runtime::Runtime::new().unwrap();
        let join_error = runtime.block_on(async {
            tokio::spawn(async move {
                panic!("intentional join failure for reporting test");
            })
            .await
            .unwrap_err()
        });
        drop(runtime);

        let _ = std::panic::take_hook();
        std::panic::set_hook(previous_hook);

        report_non_blocking_hook_outcome(
            Err(join_error),
            "on_session_start".into(),
            "test command".into(),
            reporter,
        );

        let reported = reported.lock().unwrap();
        assert_eq!(reported.len(), 1);
        match &reported[0] {
            HookBackgroundEvent::NonBlockingHookPanicked {
                event,
                command,
                error,
            } => {
                assert_eq!(event, "on_session_start");
                assert_eq!(command, "test command");
                assert!(error.contains("panic") || error.contains("cancelled"));
            }
            other => panic!("expected non-blocking hook panic, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn hook_before_tool_call_blocks() {
        let mut runner = HookRunner::new();
        runner.load_from_config(vec![HookDef {
            event: "before_tool_call".into(),
            match_pattern: Some("bash".into()),
            action: "shell".into(),
            command: Some("exit 1".into()),
            blocking: true,
            threshold: None,
        }]);

        let args = serde_json::json!({"command": "rm -rf /"});
        let event = HookEvent::BeforeToolCall {
            tool_name: "bash",
            args: &args,
        };
        let results = runner.fire(&event).await;
        assert_eq!(results.len(), 1);
        assert!(results[0].block);
    }

    #[tokio::test]
    async fn hook_before_tool_call_allows() {
        let mut runner = HookRunner::new();
        runner.load_from_config(vec![HookDef {
            event: "before_tool_call".into(),
            match_pattern: Some("read".into()),
            action: "shell".into(),
            command: Some("exit 0".into()),
            blocking: true,
            threshold: None,
        }]);

        let args = serde_json::json!({});
        let event = HookEvent::BeforeToolCall {
            tool_name: "read",
            args: &args,
        };
        let results = runner.fire(&event).await;
        assert_eq!(results.len(), 1);
        assert!(!results[0].block);
    }

    #[tokio::test]
    async fn hook_after_tool_call_modifies_result() {
        let mut runner = HookRunner::new();
        runner.load_from_config(vec![HookDef {
            event: "after_tool_call".into(),
            match_pattern: None,
            action: "shell".into(),
            command: Some("echo modified output".into()),
            blocking: true,
            threshold: None,
        }]);

        let result_msg = ToolResultMessage {
            tool_call_id: "call_1".into(),
            tool_name: "test".into(),
            content: vec![ContentBlock::Text {
                text: "original".into(),
            }],
            is_error: false,
            details: serde_json::Value::Null,
            timestamp: 0,
        };
        let event = HookEvent::AfterToolCall {
            tool_name: "test",
            result: &result_msg,
        };
        let results = runner.fire(&event).await;
        assert_eq!(results.len(), 1);
        let modified = results[0]
            .modified_content
            .as_ref()
            .expect("should have modified content");
        assert_eq!(modified.len(), 1);
        if let ContentBlock::Text { text } = &modified[0] {
            assert_eq!(text, "modified output");
        } else {
            panic!("expected Text content block");
        }
    }

    #[tokio::test]
    async fn hook_context_threshold_fires_at_correct_ratio() {
        let mut runner = HookRunner::new();
        runner.load_from_config(vec![HookDef {
            event: "on_context_threshold".into(),
            match_pattern: None,
            action: "shell".into(),
            command: Some("echo threshold hit at {ratio}".into()),
            blocking: true,
            threshold: Some(0.8),
        }]);

        // Below threshold — no results
        let below = HookEvent::OnContextThreshold { ratio: 0.5 };
        let results = runner.fire(&below).await;
        assert!(results.is_empty());

        // At threshold — should fire
        let at = HookEvent::OnContextThreshold { ratio: 0.8 };
        let results = runner.fire(&at).await;
        assert_eq!(results.len(), 1);

        // Above threshold — should fire
        let above = HookEvent::OnContextThreshold { ratio: 0.95 };
        let results = runner.fire(&above).await;
        assert_eq!(results.len(), 1);
    }

    #[tokio::test]
    async fn hook_execution_order_toml_first_then_programmatic() {
        use std::sync::Mutex;

        let order = Arc::new(Mutex::new(Vec::new()));

        let mut runner = HookRunner::new();

        // TOML hook
        runner.load_from_config(vec![HookDef {
            event: "on_session_start".into(),
            match_pattern: None,
            action: "shell".into(),
            command: Some("echo toml".into()),
            blocking: true,
            threshold: None,
        }]);

        // Programmatic hook
        let order_clone = Arc::clone(&order);
        runner.register_callback(
            "on_session_start",
            Arc::new(move |_event| {
                order_clone.lock().unwrap().push("programmatic");
                HookResult::default()
            }),
        );

        let event = HookEvent::OnSessionStart;
        let results = runner.fire(&event).await;

        // Both should fire
        assert_eq!(results.len(), 2);

        // Programmatic should have recorded its execution
        let recorded = order.lock().unwrap();
        assert_eq!(recorded.len(), 1);
        assert_eq!(recorded[0], "programmatic");
    }

    #[tokio::test]
    async fn hook_callback_blocks_tool_call() {
        let mut runner = HookRunner::new();
        runner.register_callback(
            "before_tool_call",
            Arc::new(|_event| HookResult {
                block: true,
                reason: Some("blocked by callback".into()),
                modified_content: None,
            }),
        );

        let args = serde_json::json!({});
        let event = HookEvent::BeforeToolCall {
            tool_name: "bash",
            args: &args,
        };
        let results = runner.fire(&event).await;
        assert_eq!(results.len(), 1);
        assert!(results[0].block);
        assert_eq!(results[0].reason.as_deref(), Some("blocked by callback"));
    }

    #[tokio::test]
    async fn hook_shell_interpolation_in_execution() {
        let tmp = tempfile::NamedTempFile::new().unwrap();
        let tmp_path = tmp.path().to_path_buf();
        let marker_file = tempfile::NamedTempFile::new().unwrap();
        let marker_path = marker_file.path().to_string_lossy().to_string();

        let mut runner = HookRunner::new();
        runner.load_from_config(vec![HookDef {
            event: "after_file_write".into(),
            match_pattern: None,
            action: "shell".into(),
            command: Some(format!("echo {{file}} > {marker_path}")),
            blocking: true,
            threshold: None,
        }]);

        let event = HookEvent::AfterFileWrite { file: &tmp_path };
        runner.fire(&event).await;

        // Verify the marker file contains the interpolated path
        let content = std::fs::read_to_string(&marker_path).unwrap();
        assert!(
            content.contains(&tmp_path.to_string_lossy().to_string()),
            "Expected marker to contain file path, got: {content}"
        );
    }

    #[test]
    fn hook_runner_load_from_config_resolves_all() {
        let mut runner = HookRunner::new();
        runner.load_from_config(vec![
            HookDef {
                event: "after_file_write".into(),
                match_pattern: Some("*.rs".into()),
                action: "shell".into(),
                command: Some("rustfmt {file}".into()),
                blocking: true,
                threshold: None,
            },
            HookDef {
                event: "before_tool_call".into(),
                match_pattern: Some("bash".into()),
                action: "shell".into(),
                command: Some("echo checking".into()),
                blocking: true,
                threshold: None,
            },
        ]);
        assert_eq!(runner.toml_hooks.len(), 2);
    }

    #[tokio::test]
    async fn hook_unmatched_event_returns_empty() {
        let mut runner = HookRunner::new();
        runner.load_from_config(vec![HookDef {
            event: "on_session_start".into(),
            match_pattern: None,
            action: "shell".into(),
            command: Some("echo hi".into()),
            blocking: true,
            threshold: None,
        }]);

        // Fire a different event
        let event = HookEvent::BeforeLlmCall;
        let results = runner.fire(&event).await;
        assert!(results.is_empty());
    }
}