xz-agent-hooks 0.1.0

Lifecycle hook contract, ordered registry, and wire parsers for agent extension hosts
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
//! Hook events, outcomes, and merge semantics.

use serde::{Deserialize, Serialize};
use serde_json::Value;

/// Lifecycle kind a handler may subscribe to.
///
/// Names align with common coding-agent ecosystems (Claude Code / Codex aliases
/// accepted by [`HookEventKind::parse`]).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub enum HookEventKind {
    /// Before the model sees the user turn / system is finalized for the turn.
    PrePrompt,
    /// Before a tool executes — may deny or mutate arguments.
    PreTool,
    /// After a tool finishes (success or error).
    PostTool,
    /// When a permission dialog would be shown.
    PermissionRequest,
    /// Session began or was resumed.
    SessionStart,
    /// Session is ending.
    SessionEnd,
    /// Context compaction is about to run or just finished (product chooses phase).
    Compact,
    /// Agent mode changed.
    ModeSwitch,
    /// Model changed.
    ModelSwitch,
    /// A recoverable or fatal error occurred.
    Error,
    /// Generic / product-defined extension point.
    Other,
}

impl HookEventKind {
    /// Parse a kind from configuration strings (Claude aliases included).
    pub fn parse(s: &str) -> Option<Self> {
        match s.trim() {
            "PrePrompt" | "pre_prompt" | "UserPromptSubmit" => Some(Self::PrePrompt),
            "PreTool" | "PreToolUse" | "pre_tool" | "preToolUse" => Some(Self::PreTool),
            "PostTool" | "PostToolUse" | "post_tool" | "postToolUse" => Some(Self::PostTool),
            "PermissionRequest" | "permission_request" => Some(Self::PermissionRequest),
            "SessionStart" | "OnSessionStart" | "session_start" | "startup" => {
                Some(Self::SessionStart)
            }
            "SessionEnd" | "OnSessionEnd" | "session_end" => Some(Self::SessionEnd),
            "Compact" | "OnCompact" | "PreCompact" | "PostCompact" | "compact" => {
                Some(Self::Compact)
            }
            "ModeSwitch" | "OnModeSwitch" | "mode_switch" => Some(Self::ModeSwitch),
            "ModelSwitch" | "OnModelSwitch" | "model_switch" => Some(Self::ModelSwitch),
            "Error" | "OnError" | "error" => Some(Self::Error),
            "Other" | "other" => Some(Self::Other),
            _ => None,
        }
    }

    /// Default merge mode for this event kind.
    pub fn default_merge_mode(self) -> MergeMode {
        match self {
            Self::PreTool => MergeMode::PreTool,
            Self::PostTool => MergeMode::PostTool,
            Self::PermissionRequest => MergeMode::PermissionRequest,
            _ => MergeMode::InjectOnly,
        }
    }
}

/// A single lifecycle event payload (product-agnostic).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct HookEvent {
    /// Event kind.
    pub kind: HookEventKind,
    /// Tool name when kind is PreTool / PostTool / PermissionRequest.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tool: Option<String>,
    /// Tool arguments as JSON (PreTool/PermissionRequest). Mutate replaces this object.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub args: Option<Value>,
    /// Tool result text or JSON (PostTool).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub result: Option<String>,
    /// Free-form extra fields (session id, mode, model, paths, …).
    #[serde(default)]
    pub meta: Value,
}

impl Default for HookEvent {
    fn default() -> Self {
        Self::unit(HookEventKind::Other)
    }
}

impl HookEvent {
    /// Build a PreTool event.
    pub fn pre_tool(tool: impl Into<String>, args: Value) -> Self {
        Self {
            kind: HookEventKind::PreTool,
            tool: Some(tool.into()),
            args: Some(args),
            result: None,
            meta: Value::Null,
        }
    }

    /// Build a PostTool event.
    pub fn post_tool(tool: impl Into<String>, result: impl Into<String>) -> Self {
        Self {
            kind: HookEventKind::PostTool,
            tool: Some(tool.into()),
            args: None,
            result: Some(result.into()),
            meta: Value::Null,
        }
    }

    /// Build a PermissionRequest event.
    pub fn permission_request(tool: impl Into<String>, args: Value) -> Self {
        Self {
            kind: HookEventKind::PermissionRequest,
            tool: Some(tool.into()),
            args: Some(args),
            result: None,
            meta: Value::Null,
        }
    }

    /// Build a unit-ish lifecycle event.
    pub fn unit(kind: HookEventKind) -> Self {
        Self {
            kind,
            tool: None,
            args: None,
            result: None,
            meta: Value::Null,
        }
    }

    /// Attach meta object (builder style).
    pub fn with_meta(mut self, meta: Value) -> Self {
        self.meta = meta;
        self
    }
}

/// Where additional context should be applied by the product host.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ContextChannel {
    /// Inject before the next LLM call.
    PrePrompt,
    /// Attach near a tool result.
    ToolPreface,
    /// UI / observer only — must not enter the model context.
    UiNotice,
}

/// Result of running one hook handler.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum HookOutcome {
    /// No decision; continue.
    Continue,
    /// Model-visible (or UI) context injection.
    AdditionalContext {
        /// Text to inject.
        text: String,
        /// Target channel.
        #[serde(default = "default_pre_prompt_channel")]
        channel: ContextChannel,
    },
    /// Block the tool (or prompt, when product maps it).
    Deny {
        /// Human-readable reason for the model / UI.
        reason: String,
    },
    /// Replace tool arguments (PreTool). Full object replacement.
    MutateArgs {
        /// New arguments JSON object.
        args: Value,
    },
    /// Auto-allow permission prompt (PermissionRequest).
    Allow,
    /// Force interactive permission (PermissionRequest).
    Ask,
    /// Replace model-visible tool result (PostTool). Does **not** undo side effects.
    ReplaceResult {
        /// Replacement text.
        text: String,
    },
}

fn default_pre_prompt_channel() -> ContextChannel {
    ContextChannel::PrePrompt
}

impl HookOutcome {
    /// Convenience: additional context on the default PrePrompt channel.
    pub fn context(text: impl Into<String>) -> Self {
        Self::AdditionalContext {
            text: text.into(),
            channel: ContextChannel::PrePrompt,
        }
    }

    /// Convenience: UI-only notice.
    pub fn ui_notice(text: impl Into<String>) -> Self {
        Self::AdditionalContext {
            text: text.into(),
            channel: ContextChannel::UiNotice,
        }
    }

    /// Convenience: deny with reason.
    pub fn deny(reason: impl Into<String>) -> Self {
        Self::Deny {
            reason: reason.into(),
        }
    }

    /// Convenience: mutate args.
    pub fn mutate_args(args: Value) -> Self {
        Self::MutateArgs { args }
    }

    /// Convenience: replace tool result text.
    pub fn replace_result(text: impl Into<String>) -> Self {
        Self::ReplaceResult { text: text.into() }
    }
}

/// How to combine a sequence of [`HookOutcome`] values.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum MergeMode {
    /// PreTool: deny short-circuits; mutate chains; contexts accumulate.
    #[default]
    PreTool,
    /// PostTool: replace-result last-wins; deny → model-visible feedback; contexts accumulate.
    PostTool,
    /// PermissionRequest: deny wins; else allow if any Allow; else ask if any Ask.
    PermissionRequest,
    /// Inject-only events: only contexts / continue.
    InjectOnly,
}

/// Aggregated effect after merging PreTool outcomes.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct PreToolEffect {
    /// If set, the tool must not run.
    pub deny: Option<String>,
    /// Final tool arguments after chained mutations (`None` = leave original).
    pub args: Option<Value>,
    /// Context injections in order.
    pub contexts: Vec<(ContextChannel, String)>,
}

impl PreToolEffect {
    /// Whether the tool is denied.
    pub fn is_denied(&self) -> bool {
        self.deny.is_some()
    }

    /// Final args to use, or `original` if no mutation.
    pub fn final_args<'a>(&'a self, original: &'a Value) -> &'a Value {
        self.args.as_ref().unwrap_or(original)
    }

    /// Owned final args.
    pub fn into_final_args(self, original: Value) -> Result<Value, String> {
        if let Some(reason) = self.deny {
            return Err(reason);
        }
        Ok(self.args.unwrap_or(original))
    }
}

/// Aggregated effect after merging PostTool outcomes.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct PostToolEffect {
    /// Last [`HookOutcome::ReplaceResult`] wins (model-visible replacement).
    pub replace_result: Option<String>,
    /// Deny-as-feedback reason (Codex-like); product may replace result with this text.
    pub block_feedback: Option<String>,
    /// Context injections in order.
    pub contexts: Vec<(ContextChannel, String)>,
}

impl PostToolEffect {
    /// Effective model-visible result given the original tool output.
    ///
    /// Priority: `replace_result` > `block_feedback` (as full replace) > `original`.
    pub fn effective_result<'a>(&'a self, original: &'a str) -> &'a str {
        if let Some(r) = self.replace_result.as_deref() {
            return r;
        }
        if let Some(b) = self.block_feedback.as_deref() {
            return b;
        }
        original
    }
}

/// Permission hook decision after merge.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum PermissionDecision {
    /// No hook decided — product uses normal UI / policy.
    #[default]
    Unspecified,
    /// Auto-approve.
    Allow,
    /// Auto-deny with reason.
    Deny(String),
    /// Force interactive ask.
    Ask,
}

/// Aggregated effect after merging PermissionRequest outcomes.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct PermissionEffect {
    /// Merged decision.
    pub decision: PermissionDecision,
    /// Context injections in order.
    pub contexts: Vec<(ContextChannel, String)>,
}

/// Aggregated inject-only effect.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct InjectEffect {
    /// Context injections in order.
    pub contexts: Vec<(ContextChannel, String)>,
}

/// Mode-specific merged result.
#[derive(Debug, Clone, PartialEq)]
pub enum MergedEffect {
    /// PreTool merge.
    PreTool(PreToolEffect),
    /// PostTool merge.
    PostTool(PostToolEffect),
    /// PermissionRequest merge.
    Permission(PermissionEffect),
    /// Inject-only merge.
    Inject(InjectEffect),
}

impl MergedEffect {
    /// Borrow contexts from any variant.
    pub fn contexts(&self) -> &[(ContextChannel, String)] {
        match self {
            Self::PreTool(e) => &e.contexts,
            Self::PostTool(e) => &e.contexts,
            Self::Permission(e) => &e.contexts,
            Self::Inject(e) => &e.contexts,
        }
    }

    /// PreTool effect if this is PreTool mode.
    pub fn as_pre_tool(&self) -> Option<&PreToolEffect> {
        match self {
            Self::PreTool(e) => Some(e),
            _ => None,
        }
    }

    /// PostTool effect if this is PostTool mode.
    pub fn as_post_tool(&self) -> Option<&PostToolEffect> {
        match self {
            Self::PostTool(e) => Some(e),
            _ => None,
        }
    }

    /// Permission effect if this is PermissionRequest mode.
    pub fn as_permission(&self) -> Option<&PermissionEffect> {
        match self {
            Self::Permission(e) => Some(e),
            _ => None,
        }
    }
}

/// Merge a list of outcomes for the given mode into a typed [`MergedEffect`].
///
/// # PreTool
/// - First [`HookOutcome::Deny`] wins and **stops** further outcomes in this list.
/// - [`HookOutcome::MutateArgs`] applies left-to-right.
/// - Contexts append in order.
///
/// # PostTool
/// - Last [`HookOutcome::ReplaceResult`] wins.
/// - [`HookOutcome::Deny`] becomes `block_feedback` (does not undo side effects).
///
/// # PermissionRequest
/// - Any Deny wins (first).
/// - Else any Allow → Allow.
/// - Else any Ask → Ask.
/// - Else Unspecified.
pub fn merge_outcomes(mode: MergeMode, outcomes: &[HookOutcome]) -> MergedEffect {
    match mode {
        MergeMode::PreTool => MergedEffect::PreTool(merge_pre_tool(outcomes)),
        MergeMode::PostTool => MergedEffect::PostTool(merge_post_tool(outcomes)),
        MergeMode::PermissionRequest => MergedEffect::Permission(merge_permission(outcomes)),
        MergeMode::InjectOnly => MergedEffect::Inject(merge_inject(outcomes)),
    }
}

/// Merge PreTool outcomes only.
pub fn merge_pre_tool(outcomes: &[HookOutcome]) -> PreToolEffect {
    let mut effect = PreToolEffect::default();
    for o in outcomes {
        match o {
            HookOutcome::Deny { reason } => {
                effect.deny = Some(reason.clone());
                break;
            }
            HookOutcome::MutateArgs { args } => {
                effect.args = Some(args.clone());
            }
            HookOutcome::AdditionalContext { text, channel } => {
                effect.contexts.push((*channel, text.clone()));
            }
            HookOutcome::Continue
            | HookOutcome::Allow
            | HookOutcome::Ask
            | HookOutcome::ReplaceResult { .. } => {}
        }
    }
    effect
}

/// Merge PostTool outcomes only.
pub fn merge_post_tool(outcomes: &[HookOutcome]) -> PostToolEffect {
    let mut effect = PostToolEffect::default();
    for o in outcomes {
        match o {
            HookOutcome::Deny { reason } => {
                effect.block_feedback = Some(reason.clone());
            }
            HookOutcome::ReplaceResult { text } => {
                effect.replace_result = Some(text.clone());
            }
            HookOutcome::AdditionalContext { text, channel } => {
                effect.contexts.push((*channel, text.clone()));
            }
            HookOutcome::Continue
            | HookOutcome::MutateArgs { .. }
            | HookOutcome::Allow
            | HookOutcome::Ask => {}
        }
    }
    effect
}

/// Merge PermissionRequest outcomes only.
///
/// Priority: Deny > Allow > Ask > Unspecified.
pub fn merge_permission(outcomes: &[HookOutcome]) -> PermissionEffect {
    let mut effect = PermissionEffect::default();
    let mut saw_allow = false;
    let mut saw_ask = false;
    for o in outcomes {
        match o {
            HookOutcome::Deny { reason } => {
                effect.decision = PermissionDecision::Deny(reason.clone());
                // still collect remaining contexts after? stop like PreTool
                break;
            }
            HookOutcome::Allow => saw_allow = true,
            HookOutcome::Ask => saw_ask = true,
            HookOutcome::AdditionalContext { text, channel } => {
                effect.contexts.push((*channel, text.clone()));
            }
            _ => {}
        }
    }
    if matches!(effect.decision, PermissionDecision::Unspecified) {
        if saw_allow {
            effect.decision = PermissionDecision::Allow;
        } else if saw_ask {
            effect.decision = PermissionDecision::Ask;
        }
    }
    effect
}

/// Merge inject-only outcomes.
pub fn merge_inject(outcomes: &[HookOutcome]) -> InjectEffect {
    let mut effect = InjectEffect::default();
    for o in outcomes {
        if let HookOutcome::AdditionalContext { text, channel } = o {
            effect.contexts.push((*channel, text.clone()));
        }
    }
    effect
}

/// Apply chained PreTool mutations to a starting args object.
pub fn apply_pre_tool_args(original: &Value, effect: &PreToolEffect) -> Value {
    effect
        .args
        .clone()
        .unwrap_or_else(|| original.clone())
}

/// Collect context texts for a channel.
pub fn contexts_for_channel(
    contexts: &[(ContextChannel, String)],
    channel: ContextChannel,
) -> Vec<&str> {
    contexts
        .iter()
        .filter(|(c, _)| *c == channel)
        .map(|(_, t)| t.as_str())
        .collect()
}

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

    #[test]
    fn parse_claude_aliases() {
        assert_eq!(
            HookEventKind::parse("PreToolUse"),
            Some(HookEventKind::PreTool)
        );
        assert_eq!(
            HookEventKind::parse("PostToolUse"),
            Some(HookEventKind::PostTool)
        );
        assert_eq!(
            HookEventKind::parse("SessionStart"),
            Some(HookEventKind::SessionStart)
        );
        assert_eq!(HookEventKind::parse("UserPromptSubmit"), Some(HookEventKind::PrePrompt));
        assert_eq!(HookEventKind::parse("nope"), None);
    }

    #[test]
    fn default_merge_mode_mapping() {
        assert_eq!(
            HookEventKind::PreTool.default_merge_mode(),
            MergeMode::PreTool
        );
        assert_eq!(
            HookEventKind::SessionStart.default_merge_mode(),
            MergeMode::InjectOnly
        );
    }

    #[test]
    fn pre_tool_deny_short_circuits() {
        let outcomes = [
            HookOutcome::mutate_args(json!({"command": "echo a"})),
            HookOutcome::deny("nope"),
            HookOutcome::mutate_args(json!({"command": "echo b"})),
        ];
        let e = merge_pre_tool(&outcomes);
        assert_eq!(e.deny.as_deref(), Some("nope"));
        assert_eq!(e.args, Some(json!({"command": "echo a"})));
        assert!(e.is_denied());
        assert!(e.into_final_args(json!({})).is_err());
    }

    #[test]
    fn pre_tool_mutate_chains() {
        let outcomes = [
            HookOutcome::mutate_args(json!({"command": "git status"})),
            HookOutcome::mutate_args(json!({"command": "rtk git status"})),
            HookOutcome::context("note"),
        ];
        let e = merge_pre_tool(&outcomes);
        assert!(!e.is_denied());
        assert_eq!(e.args, Some(json!({"command": "rtk git status"})));
        assert_eq!(e.contexts.len(), 1);
        assert_eq!(
            apply_pre_tool_args(&json!({"command": "raw"}), &e),
            json!({"command": "rtk git status"})
        );
        let owned = e
            .clone()
            .into_final_args(json!({"command": "raw"}));
        assert!(matches!(owned, Ok(v) if v == json!({"command": "rtk git status"})));
    }

    #[test]
    fn pre_tool_no_mutate_keeps_original_ref() {
        let e = PreToolEffect::default();
        let original = json!({"a": 1});
        assert_eq!(e.final_args(&original), &original);
    }

    #[test]
    fn post_tool_replace_last_wins() {
        let outcomes = [
            HookOutcome::replace_result("first"),
            HookOutcome::replace_result("second"),
            HookOutcome::context("ctx"),
        ];
        let e = merge_post_tool(&outcomes);
        assert_eq!(e.replace_result.as_deref(), Some("second"));
        assert_eq!(e.effective_result("orig"), "second");
        assert_eq!(e.contexts.len(), 1);
    }

    #[test]
    fn post_tool_deny_becomes_block_feedback() {
        let outcomes = [HookOutcome::deny("needs review")];
        let e = merge_post_tool(&outcomes);
        assert_eq!(e.block_feedback.as_deref(), Some("needs review"));
        assert_eq!(e.effective_result("orig"), "needs review");
    }

    #[test]
    fn post_tool_replace_beats_block_feedback() {
        let outcomes = [
            HookOutcome::deny("block"),
            HookOutcome::replace_result("replaced"),
        ];
        let e = merge_post_tool(&outcomes);
        assert_eq!(e.effective_result("orig"), "replaced");
    }

    #[test]
    fn permission_deny_beats_allow() {
        let outcomes = [
            HookOutcome::Allow,
            HookOutcome::deny("policy"),
            HookOutcome::Ask,
        ];
        let e = merge_permission(&outcomes);
        assert_eq!(e.decision, PermissionDecision::Deny("policy".into()));
    }

    #[test]
    fn permission_allow_over_ask() {
        let outcomes = [HookOutcome::Ask, HookOutcome::Allow];
        let e = merge_permission(&outcomes);
        assert_eq!(e.decision, PermissionDecision::Allow);
    }

    #[test]
    fn permission_ask_only() {
        let e = merge_permission(&[HookOutcome::Ask]);
        assert_eq!(e.decision, PermissionDecision::Ask);
    }

    #[test]
    fn permission_unspecified() {
        let e = merge_permission(&[HookOutcome::Continue]);
        assert_eq!(e.decision, PermissionDecision::Unspecified);
    }

    #[test]
    fn inject_filters_non_context() {
        let e = merge_inject(&[
            HookOutcome::Continue,
            HookOutcome::deny("x"),
            HookOutcome::ui_notice("ui"),
            HookOutcome::context("model"),
        ]);
        assert_eq!(e.contexts.len(), 2);
        assert_eq!(
            contexts_for_channel(&e.contexts, ContextChannel::UiNotice),
            vec!["ui"]
        );
        assert_eq!(
            contexts_for_channel(&e.contexts, ContextChannel::PrePrompt),
            vec!["model"]
        );
    }

    #[test]
    fn merge_outcomes_dispatch() {
        let m = merge_outcomes(MergeMode::PreTool, &[HookOutcome::deny("d")]);
        assert!(m.as_pre_tool().is_some_and(|e| e.is_denied()));
        let m = merge_outcomes(MergeMode::PostTool, &[HookOutcome::replace_result("r")]);
        assert!(m.as_post_tool().is_some_and(|e| e.replace_result.as_deref() == Some("r")));
        let m = merge_outcomes(MergeMode::PermissionRequest, &[HookOutcome::Allow]);
        assert!(m
            .as_permission()
            .is_some_and(|e| e.decision == PermissionDecision::Allow));
    }

    #[test]
    fn event_builders_and_serde() {
        let ev = HookEvent::pre_tool("shell", json!({"command": "ls"}))
            .with_meta(json!({"session": "s1"}));
        let Ok(s) = serde_json::to_string(&ev) else {
            panic!("serialize failed");
        };
        let Ok(back) = serde_json::from_str::<HookEvent>(&s) else {
            panic!("deserialize failed");
        };
        assert_eq!(back.kind, HookEventKind::PreTool);
        assert_eq!(back.tool.as_deref(), Some("shell"));
        assert_eq!(back.meta.get("session").and_then(|v| v.as_str()), Some("s1"));

        let p = HookEvent::permission_request("shell", json!({}));
        assert_eq!(p.kind, HookEventKind::PermissionRequest);

        let post = HookEvent::post_tool("shell", "ok");
        assert_eq!(post.result.as_deref(), Some("ok"));
    }

    #[test]
    fn outcome_serde_roundtrip() {
        let outcomes = [
            HookOutcome::Continue,
            HookOutcome::context("c"),
            HookOutcome::deny("d"),
            HookOutcome::mutate_args(json!({"x": 1})),
            HookOutcome::Allow,
            HookOutcome::Ask,
            HookOutcome::replace_result("r"),
        ];
        for o in &outcomes {
            let Ok(s) = serde_json::to_string(o) else {
                panic!("ser");
            };
            let Ok(back) = serde_json::from_str::<HookOutcome>(&s) else {
                panic!("de {s}");
            };
            assert_eq!(&back, o);
        }
    }
}