synaps-engine 0.8.0

Runtime engine — streaming, tools, MCP, skills, extensions, sidecar
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
//! Hook events — typed payloads for each extension point.
//!
//! Each [`HookKind`] maps to a discrete phase of SynapsCLI's execution loop.
//! [`HookEvent`] is the concrete payload dispatched to subscribers at that
//! phase; [`HookResult`] is what a handler returns to control execution flow.
//!
//! Permission enforcement lives in [`crate::extensions::permissions`]:
//! every `HookKind` declares a [`required_permission`][HookKind::required_permission]
//! so the runtime can gate subscriptions before any payload is delivered.

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

use crate::extensions::permissions::Permission;

/// Maximum hook output size (bytes) before truncation on the JSON-RPC path.
/// Matches `max_tool_buffer` (256 KB) — keeps the payload bounded while still
/// giving transform extensions the full buffered output to work with.
/// Exported so tests can build payloads that derive from the real cap and
/// won't rot when the constant changes.
pub const MAX_HOOK_OUTPUT: usize = 256 * 1024; // 256 KB

// ── HookKind ──────────────────────────────────────────────────────────────────

/// All hook event kinds in the phase-1 catalog.
///
/// Each variant identifies a well-defined extension point in the agent loop.
/// The set is intentionally closed; new kinds are added via a breaking version
/// bump so existing permission grants stay coherent.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum HookKind {
    /// Fires immediately before a tool is invoked. Handlers may block the call.
    BeforeToolCall,
    /// Fires immediately after a tool returns. Handlers receive the output.
    AfterToolCall,
    /// Fires before an LLM message is sent. Handlers may inspect or block.
    BeforeMessage,
    /// Fires after an assistant response is completed and added to history.
    OnMessageComplete,
    /// Fires after conversation compaction creates a replacement session.
    OnCompaction,
    /// Fires when a new session is created.
    OnSessionStart,
    /// Fires when a session is torn down.
    OnSessionEnd,
}

impl HookKind {
    /// Every hook kind, in declaration order.
    ///
    /// Exhaustiveness is enforced by `all_covers_every_variant` in this
    /// module's tests. This list is what `docs/extensions/contract.json` is
    /// drift-checked against (see
    /// `crates/agent-tui/tests/extensions_contract.rs`).
    pub const ALL: &'static [HookKind] = &[
        Self::BeforeToolCall,
        Self::AfterToolCall,
        Self::BeforeMessage,
        Self::OnMessageComplete,
        Self::OnCompaction,
        Self::OnSessionStart,
        Self::OnSessionEnd,
    ];

    /// Canonical string identifier for this kind, suitable for serialization
    /// keys, log output, and manifest declarations.
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::BeforeToolCall => "before_tool_call",
            Self::AfterToolCall => "after_tool_call",
            Self::BeforeMessage => "before_message",
            Self::OnMessageComplete => "on_message_complete",
            Self::OnCompaction => "on_compaction",
            Self::OnSessionStart => "on_session_start",
            Self::OnSessionEnd => "on_session_end",
        }
    }

    /// Parse from the canonical string representation.
    ///
    /// Returns `None` for unrecognised strings so callers can surface
    /// a manifest validation error rather than silently dropping hooks.
    #[allow(clippy::should_implement_trait)]
    pub fn from_str(s: &str) -> Option<Self> {
        match s {
            "before_tool_call" => Some(Self::BeforeToolCall),
            "after_tool_call" => Some(Self::AfterToolCall),
            "before_message" => Some(Self::BeforeMessage),
            "on_message_complete" => Some(Self::OnMessageComplete),
            "on_compaction" => Some(Self::OnCompaction),
            "on_session_start" => Some(Self::OnSessionStart),
            "on_session_end" => Some(Self::OnSessionEnd),
            _ => None,
        }
    }

    /// Supported action names for this hook in the extension contract.
    pub fn allowed_action_names(&self) -> &'static [&'static str] {
        match self {
            Self::BeforeToolCall => &["continue", "block", "confirm", "modify"],
            Self::AfterToolCall => &["continue", "replace"],
            Self::BeforeMessage => &["continue", "inject"],
            // Session-scoped context. Injected ONCE when the session starts
            // and carried on the system prompt for the rest of it, rather
            // than re-appended on every message the way `before_message`
            // injection is.
            Self::OnSessionStart => &["continue", "inject"],
            Self::OnMessageComplete | Self::OnCompaction | Self::OnSessionEnd => &["continue"],
        }
    }

    /// Whether this hook can be filtered by tool name in a manifest.
    pub fn allows_tool_filter(&self) -> bool {
        matches!(self, Self::BeforeToolCall | Self::AfterToolCall)
    }

    /// Whether this hook accepts a handler result action.
    pub fn allows_result(&self, result: &HookResult) -> bool {
        matches!(
            (self, result),
            (_, HookResult::Continue)
                | (Self::BeforeToolCall, HookResult::Block { .. })
                | (Self::BeforeToolCall, HookResult::Confirm { .. })
                | (Self::BeforeToolCall, HookResult::Modify { .. })
                | (Self::AfterToolCall, HookResult::Replace { .. })
                | (Self::BeforeMessage, HookResult::Inject { .. })
                | (Self::OnSessionStart, HookResult::Inject { .. })
        )
    }

    /// The [`Permission`] an extension must hold to subscribe to this hook.
    ///
    /// Called by the permission gate before delivering any event; if the
    /// extension's [`PermissionSet`][crate::extensions::permissions::PermissionSet]
    /// does not include this permission, `HookBus::subscribe()` returns an error.
    pub fn required_permission(&self) -> Permission {
        match self {
            Self::BeforeToolCall | Self::AfterToolCall => Permission::ToolsIntercept,
            Self::BeforeMessage | Self::OnMessageComplete | Self::OnCompaction => {
                Permission::LlmContent
            }
            Self::OnSessionStart | Self::OnSessionEnd => Permission::SessionLifecycle,
        }
    }
}

// ── HookEvent ─────────────────────────────────────────────────────────────────

/// A hook event payload dispatched to extension handlers.
///
/// Fields are optional and populated only when relevant to the hook kind:
///
/// | Kind                  | tool_name | tool_input | tool_output | message | session_id |
/// |-----------------------|-----------|------------|-------------|---------|------------|
/// | `before_tool_call`    | ✓         | ✓          |             |         |            |
/// | `after_tool_call`     | ✓         | ✓          | ✓           |         |            |
/// | `before_message`      |           |            |             | ✓       |            |
/// | `on_message_complete` |           |            |             | ✓       |            |
/// | `on_compaction`       |           |            |             | ✓       | ✓          |
/// | `on_session_start`    |           |            |             |         | ✓          |
/// | `on_session_end`      |           |            |             |         | ✓          |
///
/// The `data` field is available on all events for extensions that need to
/// attach arbitrary structured context when constructing synthetic events.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HookEvent {
    /// Which hook fired.
    pub kind: HookKind,
    /// Tool name for tool-specific hooks; `None` for general hooks.
    /// This is the API-safe name (sanitized for the LLM).
    pub tool_name: Option<String>,
    /// Original runtime name of the tool (before API sanitization).
    /// Extension authors typically write runtime names in their manifests.
    #[serde(default)]
    pub tool_runtime_name: Option<String>,
    /// Tool input arguments for `before_tool_call` and `after_tool_call`.
    pub tool_input: Option<Value>,
    /// Tool output for `after_tool_call`.
    pub tool_output: Option<String>,
    /// LLM message content for `before_message`.
    pub message: Option<String>,
    /// Session identifier for session lifecycle hooks.
    pub session_id: Option<String>,
    /// Session message history for `on_session_end`.
    /// Contains the conversation transcript so extensions (like Stelline)
    /// can extract memories without reaching into runtime internals.
    #[serde(default)]
    pub transcript: Option<Vec<crate::SharedMessage>>,
    /// Arbitrary extension-defined data, passed through without inspection.
    pub data: Value,
}

impl HookEvent {
    /// Construct a `before_tool_call` event.
    pub fn before_tool_call(tool_name: &str, input: Value) -> Self {
        Self {
            kind: HookKind::BeforeToolCall,
            tool_name: Some(tool_name.to_string()),
            tool_input: Some(input),
            tool_output: None,
            message: None,
            session_id: None,
            tool_runtime_name: None,
            transcript: None,
            data: Value::Null,
        }
    }

    /// Construct an `after_tool_call` event carrying both input and output.
    /// Output is truncated to MAX_HOOK_OUTPUT to bound the JSON-RPC payload
    /// to extensions. This cap matches the runtime's `max_tool_buffer`
    /// (the OOM safety net) so transform extensions see the FULL buffered
    /// tool output and can decide what to keep — the final context-budget
    /// truncation to `max_tool_output` happens AFTER the hook in
    /// `emit_after_tool_call` (compress-then-truncate).
    pub fn after_tool_call(tool_name: &str, input: Value, output: String) -> Self {
        let bounded = agent_core::BoundedText::new(&output, MAX_HOOK_OUTPUT);
        let truncated_output = if bounded.truncated {
            format!(
                "{}…[truncated, {} total bytes]",
                bounded.text, bounded.original_bytes
            )
        } else {
            output
        };
        Self {
            kind: HookKind::AfterToolCall,
            tool_name: Some(tool_name.to_string()),
            tool_input: Some(input),
            tool_output: Some(truncated_output),
            message: None,
            session_id: None,
            tool_runtime_name: None,
            transcript: None,
            data: Value::Null,
        }
    }

    /// Construct a `before_message` event.
    pub fn before_message(message: &str) -> Self {
        Self {
            kind: HookKind::BeforeMessage,
            tool_name: None,
            tool_input: None,
            tool_output: None,
            message: Some(message.to_string()),
            session_id: None,
            tool_runtime_name: None,
            transcript: None,
            data: Value::Null,
        }
    }

    /// Construct an `on_message_complete` event.
    pub fn on_message_complete(message: &str, data: Value) -> Self {
        Self {
            kind: HookKind::OnMessageComplete,
            tool_name: None,
            tool_input: None,
            tool_output: None,
            message: Some(message.to_string()),
            session_id: None,
            tool_runtime_name: None,
            transcript: None,
            data,
        }
    }

    /// Construct an `on_compaction` event.
    pub fn on_compaction(
        old_session_id: &str,
        new_session_id: &str,
        summary: &str,
        message_count: usize,
        mut data: Value,
    ) -> Self {
        if !data.is_object() {
            data = Value::Object(Default::default());
        }
        if let Some(object) = data.as_object_mut() {
            object.insert(
                "old_session_id".to_string(),
                Value::String(old_session_id.to_string()),
            );
            object.insert(
                "new_session_id".to_string(),
                Value::String(new_session_id.to_string()),
            );
            object.insert(
                "message_count".to_string(),
                Value::Number(message_count.into()),
            );
        }
        Self {
            kind: HookKind::OnCompaction,
            tool_name: None,
            tool_input: None,
            tool_output: None,
            message: Some(summary.to_string()),
            session_id: Some(new_session_id.to_string()),
            tool_runtime_name: None,
            transcript: None,
            data,
        }
    }

    /// Construct an `on_session_start` event.
    pub fn on_session_start(session_id: &str) -> Self {
        Self {
            kind: HookKind::OnSessionStart,
            tool_name: None,
            tool_input: None,
            tool_output: None,
            message: None,
            session_id: Some(session_id.to_string()),
            tool_runtime_name: None,
            transcript: None,
            data: Value::Null,
        }
    }

    /// Construct an `on_session_end` event.
    pub fn on_session_end(session_id: &str, transcript: Option<Vec<crate::SharedMessage>>) -> Self {
        Self {
            kind: HookKind::OnSessionEnd,
            tool_name: None,
            tool_input: None,
            tool_output: None,
            message: None,
            session_id: Some(session_id.to_string()),
            tool_runtime_name: None,
            transcript,
            data: Value::Null,
        }
    }
}

// ── HookResult ────────────────────────────────────────────────────────────────

/// What an extension handler returns after processing a hook event.
///
/// The runtime resolves multiple handlers by precedence:
/// - `Block`, `Confirm`, and `Modify` stop the handler chain for `before_tool_call`.
/// - `Inject` results are accumulated for `before_message`.
/// - `Continue` is the no-op default — processing continues normally.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(tag = "action", rename_all = "snake_case")]
pub enum HookResult {
    /// Allow execution to proceed unchanged.
    #[default]
    Continue,
    /// Prevent the hooked operation. The `reason` is surfaced to the user.
    Block { reason: String },
    /// Inject context — the extension provides text for the current request.
    /// Placement depends on the hook (#297): `on_session_start` content is
    /// appended to the system prompt (session-stable, cache-safe);
    /// `before_message` content is attached to the newest user message on the
    /// outgoing request as an ephemeral trailing block positioned AFTER the
    /// conversational cache marker (per-turn, uncached tail, cache-neutral).
    Inject { content: String },
    /// Ask the runtime to get explicit user confirmation before proceeding.
    /// Only valid on before_tool_call hooks.
    Confirm { message: String },
    /// Replace the tool **input** before execution (structured JSON args).
    /// Only valid on before_tool_call hooks. The output-side counterpart is
    /// [`HookResult::Replace`]. The first modifier stops the handler chain.
    Modify { input: Value },
    /// Replace the tool **output** after execution (flat string), before it
    /// enters history. Only valid on after_tool_call hooks. The input-side
    /// counterpart is [`HookResult::Modify`] — distinct name because the payload
    /// is an unstructured `String`, not structured `Value`. Enables native
    /// output transforms (compression, redaction, summarization) by extensions.
    /// The first transform stops the handler chain.
    Replace { output: String },
}

// ── Tests ─────────────────────────────────────────────────────────────────────

impl HookEvent {
    /// Set the runtime name for tool-related events.
    pub fn with_runtime_name(mut self, name: &str) -> Self {
        self.tool_runtime_name = Some(name.to_string());
        self
    }
}

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

    /// The extension wire format `{"action":"replace","output":"..."}`
    /// deserializes to HookResult::Replace via the serde action tag — and
    /// round-trips back. This locks the contract a transform extension speaks.
    #[test]
    fn replace_action_roundtrips_extension_wire_format() {
        // Inbound: what a process extension sends on hook.handle.
        let wire = json!({"action": "replace", "output": "compressed"});
        let parsed: HookResult = serde_json::from_value(wire).expect("must deserialize");
        match parsed {
            HookResult::Replace { output } => assert_eq!(output, "compressed"),
            other => panic!("expected Replace, got {other:?}"),
        }

        // Outbound: the action tag is exactly "replace".
        let out = serde_json::to_value(HookResult::Replace { output: "x".into() }).unwrap();
        assert_eq!(out["action"], "replace");
        assert_eq!(out["output"], "x");
    }

    // ── HookKind ──────────────────────────────────────────────────────────────

    /// after_tool_call may return Replace; other hooks may not, and
    /// after_tool_call advertises "replace" in its action contract.
    #[test]
    fn after_tool_call_allows_replace_output() {
        let replace = HookResult::Replace {
            output: "compressed".into(),
        };

        // The transform seam: after_tool_call accepts Replace.
        assert!(
            HookKind::AfterToolCall.allows_result(&replace),
            "after_tool_call must permit Replace to enable output transforms"
        );

        // Replace is scoped strictly to after_tool_call.
        assert!(
            !HookKind::BeforeToolCall.allows_result(&replace),
            "before_tool_call must not permit Replace (input-only)"
        );
        assert!(
            !HookKind::BeforeMessage.allows_result(&replace),
            "before_message must not permit Replace"
        );

        // The extension-facing action contract advertises "replace".
        assert!(
            HookKind::AfterToolCall
                .allowed_action_names()
                .contains(&"replace"),
            "after_tool_call must advertise the 'replace' action"
        );
    }

    /// Every variant's as_str round-trips through from_str.
    #[test]
    fn hook_kind_as_str_roundtrip() {
        let all = [
            HookKind::BeforeToolCall,
            HookKind::AfterToolCall,
            HookKind::BeforeMessage,
            HookKind::OnMessageComplete,
            HookKind::OnCompaction,
            HookKind::OnSessionStart,
            HookKind::OnSessionEnd,
        ];
        for kind in all {
            let s = kind.as_str();
            assert_eq!(
                HookKind::from_str(s),
                Some(kind),
                "round-trip failed for {s}"
            );
        }
    }

    /// Unknown strings return None, not a panic or a default.
    #[test]
    fn hook_kind_from_str_unknown_returns_none() {
        assert_eq!(HookKind::from_str(""), None);
        assert_eq!(HookKind::from_str("BeforeToolCall"), None); // wrong case
        assert_eq!(HookKind::from_str("on_crash"), None);
    }

    /// Serde uses snake_case via the attribute — spot-check two variants.
    #[test]
    fn hook_kind_serde_snake_case() {
        let serialized = serde_json::to_string(&HookKind::BeforeToolCall).unwrap();
        assert_eq!(serialized, r#""before_tool_call""#);

        let back: HookKind = serde_json::from_str(r#""on_session_end""#).unwrap();
        assert_eq!(back, HookKind::OnSessionEnd);
    }

    /// Each kind maps to the expected permission.
    #[test]
    fn hook_kind_required_permission() {
        assert_eq!(
            HookKind::BeforeToolCall.required_permission(),
            Permission::ToolsIntercept
        );
        assert_eq!(
            HookKind::AfterToolCall.required_permission(),
            Permission::ToolsIntercept
        );
        assert_eq!(
            HookKind::BeforeMessage.required_permission(),
            Permission::LlmContent
        );
        assert_eq!(
            HookKind::OnMessageComplete.required_permission(),
            Permission::LlmContent
        );
        assert_eq!(
            HookKind::OnCompaction.required_permission(),
            Permission::LlmContent
        );
        assert_eq!(
            HookKind::OnSessionStart.required_permission(),
            Permission::SessionLifecycle
        );
        assert_eq!(
            HookKind::OnSessionEnd.required_permission(),
            Permission::SessionLifecycle
        );
    }

    // ── HookEvent constructors ────────────────────────────────────────────────

    #[test]
    fn hook_event_before_tool_call() {
        let input = json!({"path": "/tmp/foo"});
        let ev = HookEvent::before_tool_call("read_file", input.clone());

        assert_eq!(ev.kind, HookKind::BeforeToolCall);
        assert_eq!(ev.tool_name.as_deref(), Some("read_file"));
        assert_eq!(ev.tool_input.as_ref(), Some(&input));
        assert!(ev.tool_output.is_none());
        assert!(ev.message.is_none());
        assert!(ev.session_id.is_none());
        assert_eq!(ev.data, Value::Null);
    }

    #[test]
    fn hook_event_after_tool_call() {
        let input = json!({"query": "select 1"});
        let ev = HookEvent::after_tool_call("sql_query", input.clone(), "1 row".to_string());

        assert_eq!(ev.kind, HookKind::AfterToolCall);
        assert_eq!(ev.tool_name.as_deref(), Some("sql_query"));
        assert_eq!(ev.tool_input.as_ref(), Some(&input));
        assert_eq!(ev.tool_output.as_deref(), Some("1 row"));
        assert!(ev.message.is_none());
        assert!(ev.session_id.is_none());
    }

    #[test]
    fn hook_event_before_message() {
        let ev = HookEvent::before_message("Hello, LLM");

        assert_eq!(ev.kind, HookKind::BeforeMessage);
        assert!(ev.tool_name.is_none());
        assert!(ev.tool_input.is_none());
        assert!(ev.tool_output.is_none());
        assert_eq!(ev.message.as_deref(), Some("Hello, LLM"));
        assert!(ev.session_id.is_none());
    }

    #[test]
    fn hook_event_on_message_complete() {
        let ev = HookEvent::on_message_complete("Done", json!({"content_block_count": 1}));

        assert_eq!(ev.kind, HookKind::OnMessageComplete);
        assert!(ev.tool_name.is_none());
        assert!(ev.tool_input.is_none());
        assert!(ev.tool_output.is_none());
        assert_eq!(ev.message.as_deref(), Some("Done"));
        assert_eq!(ev.data["content_block_count"], 1);
        assert!(ev.session_id.is_none());
    }

    #[test]
    fn hook_event_on_compaction() {
        let ev = HookEvent::on_compaction(
            "old-session",
            "new-session",
            "Summary",
            7,
            json!({"source": "manual"}),
        );

        assert_eq!(ev.kind, HookKind::OnCompaction);
        assert_eq!(ev.message.as_deref(), Some("Summary"));
        assert_eq!(ev.session_id.as_deref(), Some("new-session"));
        assert_eq!(ev.data["old_session_id"], "old-session");
        assert_eq!(ev.data["new_session_id"], "new-session");
        assert_eq!(ev.data["message_count"], 7);
        assert_eq!(ev.data["source"], "manual");
        assert!(ev.transcript.is_none());
    }

    #[test]
    fn hook_event_on_session_start() {
        let ev = HookEvent::on_session_start("sess-abc-123");

        assert_eq!(ev.kind, HookKind::OnSessionStart);
        assert_eq!(ev.session_id.as_deref(), Some("sess-abc-123"));
        assert!(ev.tool_name.is_none());
        assert!(ev.message.is_none());
    }

    #[test]
    fn hook_event_on_session_end() {
        let ev = HookEvent::on_session_end("sess-abc-123", None);

        assert_eq!(ev.kind, HookKind::OnSessionEnd);
        assert_eq!(ev.session_id.as_deref(), Some("sess-abc-123"));
        assert!(ev.tool_name.is_none());
        assert!(ev.message.is_none());
    }

    /// HookEvent is round-trippable through JSON without loss.
    #[test]
    fn hook_event_serde_roundtrip() {
        let ev = HookEvent::before_tool_call("bash", json!({"cmd": "ls"}));
        let json = serde_json::to_string(&ev).unwrap();
        let back: HookEvent = serde_json::from_str(&json).unwrap();

        assert_eq!(back.kind, ev.kind);
        assert_eq!(back.tool_name, ev.tool_name);
        assert_eq!(back.tool_input, ev.tool_input);
    }

    // ── HookResult ────────────────────────────────────────────────────────────

    /// Default is Continue.
    #[test]
    fn hook_result_default_is_continue() {
        assert!(matches!(HookResult::default(), HookResult::Continue));
    }

    /// Block carries its reason through serialization.
    #[test]
    fn hook_result_block_serde() {
        let r = HookResult::Block {
            reason: "denied by policy".to_string(),
        };
        let json = serde_json::to_string(&r).unwrap();
        // `tag = "action"` means the JSON object has {"action":"block","reason":"..."}
        assert!(json.contains(r#""action":"block""#));
        assert!(json.contains("denied by policy"));

        let back: HookResult = serde_json::from_str(&json).unwrap();
        assert!(matches!(back, HookResult::Block { reason } if reason == "denied by policy"));
    }

    /// Confirm carries its message through serialization.
    #[test]
    fn hook_result_confirm_serde() {
        let r = HookResult::Confirm {
            message: "Run this command?".to_string(),
        };
        let json = serde_json::to_string(&r).unwrap();
        assert_eq!(
            json,
            r#"{"action":"confirm","message":"Run this command?"}"#
        );

        let back: HookResult = serde_json::from_str(&json).unwrap();
        assert!(matches!(back, HookResult::Confirm { message } if message == "Run this command?"));
    }

    /// Modify carries replacement input through serialization.
    #[test]
    fn hook_result_modify_serde() {
        let r = HookResult::Modify {
            input: json!({"command": "echo safe"}),
        };
        let json = serde_json::to_string(&r).unwrap();
        assert_eq!(
            json,
            r#"{"action":"modify","input":{"command":"echo safe"}}"#
        );

        let back: HookResult = serde_json::from_str(&json).unwrap();
        assert!(
            matches!(back, HookResult::Modify { input } if input == json!({"command": "echo safe"}))
        );
    }

    /// Continue serialises as {"action":"continue"}.
    #[test]
    fn hook_result_continue_serde() {
        let json = serde_json::to_string(&HookResult::Continue).unwrap();
        assert_eq!(json, r#"{"action":"continue"}"#);
    }

    /// `HookKind::ALL` must list every variant exactly once. Adding a variant
    /// makes the match below non-exhaustive => compile error => the author is
    /// forced to update `ALL` and, via the contract test, contract.json.
    #[test]
    fn all_covers_every_variant() {
        for kind in HookKind::ALL {
            match kind {
                HookKind::BeforeToolCall
                | HookKind::AfterToolCall
                | HookKind::BeforeMessage
                | HookKind::OnMessageComplete
                | HookKind::OnCompaction
                | HookKind::OnSessionStart
                | HookKind::OnSessionEnd => {}
            }
        }
        assert_eq!(
            HookKind::ALL.len(),
            7,
            "a HookKind variant was added or removed -- update HookKind::ALL \
             and docs/extensions/contract.json to match"
        );
        let unique: std::collections::HashSet<HookKind> = HookKind::ALL.iter().copied().collect();
        assert_eq!(
            unique.len(),
            HookKind::ALL.len(),
            "HookKind::ALL has a duplicate"
        );
    }

    /// Every hook kind must round-trip through its canonical wire string.
    #[test]
    fn all_hook_kinds_round_trip_through_wire_format() {
        for kind in HookKind::ALL {
            assert_eq!(
                HookKind::from_str(kind.as_str()),
                Some(*kind),
                "{} does not round-trip",
                kind.as_str()
            );
        }
    }

    /// `allowed_action_names` is the contract's action list, and
    /// `allows_result` is what the hook bus actually enforces. They must
    /// agree, or the documented action set is a lie in one direction or the
    /// other. (#291: on_session_start advertised only "continue" while Axel
    /// returned "inject" -- caught here now.)
    #[test]
    fn advertised_actions_match_enforced_actions() {
        let samples: [(&str, HookResult); 6] = [
            ("continue", HookResult::Continue),
            ("block", HookResult::Block { reason: "r".into() }),
            (
                "confirm",
                HookResult::Confirm {
                    message: "m".into(),
                },
            ),
            (
                "modify",
                HookResult::Modify {
                    input: serde_json::json!({}),
                },
            ),
            ("replace", HookResult::Replace { output: "o".into() }),
            (
                "inject",
                HookResult::Inject {
                    content: "c".into(),
                },
            ),
        ];
        for kind in HookKind::ALL {
            for (name, result) in &samples {
                let advertised = kind.allowed_action_names().contains(name);
                let enforced = kind.allows_result(result);
                assert_eq!(
                    advertised,
                    enforced,
                    "hook {} disagrees about action {:?}: advertised={} enforced={}",
                    kind.as_str(),
                    name,
                    advertised,
                    enforced
                );
            }
        }
    }
}