synaps-engine 0.12.0

Runtime engine — streaming, tools, MCP, skills, extensions
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
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
//! 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 std::path::Path;

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.
///
/// Each variant identifies a well-defined extension point in the agent loop.
/// Kinds are added additively within protocol version 1; an extension that
/// names a kind the host does not know fails to load on that host.
#[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,
    /// Fires after a context rollover has sealed a window into an archive
    /// file. Notify-only ([`Self::is_notification`]).
    OnContextArchived,
    /// Fires after `memory_forget` has forgotten an archive or a note.
    /// Notify-only ([`Self::is_notification`]).
    OnMemoryForgotten,
}

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,
        Self::OnContextArchived,
        Self::OnMemoryForgotten,
    ];

    /// 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",
            Self::OnContextArchived => "on_context_archived",
            Self::OnMemoryForgotten => "on_memory_forgotten",
        }
    }

    /// 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),
            "on_context_archived" => Some(Self::OnContextArchived),
            "on_memory_forgotten" => Some(Self::OnMemoryForgotten),
            _ => 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"],
            // Advisory work-phase report for the host's automatic context
            // management (same semantics as the model's own
            // `context_checkpoint` tool without a note). Never capacity or
            // permission authority.
            Self::OnMessageComplete => &["continue", "context_phase"],
            Self::OnCompaction
            | Self::OnSessionEnd
            | Self::OnContextArchived
            | Self::OnMemoryForgotten => &["continue"],
        }
    }

    /// Whether this kind is notify-only: sent with
    /// [`HookBus::notify`](crate::extensions::hooks::HookBus::notify), which
    /// does not wait for the handlers and discards whatever they answer. A
    /// slow, failing or absent handler cannot delay or change what the
    /// event reports.
    pub fn is_notification(&self) -> bool {
        matches!(self, Self::OnContextArchived | Self::OnMemoryForgotten)
    }

    /// 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 { .. })
                | (Self::OnMessageComplete, HookResult::ContextPhase { .. })
        )
    }

    /// 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,
            // `on_context_archived` carries no content, but its path leads
            // to the archived conversation.
            Self::BeforeMessage
            | Self::OnMessageComplete
            | Self::OnCompaction
            | Self::OnContextArchived => Permission::LlmContent,
            // `on_memory_forgotten` carries ids only, no content.
            Self::OnSessionStart | Self::OnSessionEnd | Self::OnMemoryForgotten => {
                Permission::SessionLifecycle
            }
        }
    }
}

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

/// `SYNAPS_HOOK_SESSION_ID=0` disables the `session_id` field on tool/message
/// hook events (they emit `null`, as before daemon-mode phase 2).
pub fn hook_session_id_enabled() -> bool {
    !matches!(
        std::env::var("SYNAPS_HOOK_SESSION_ID").as_deref(),
        Ok("0") | Ok("false") | Ok("off")
    )
}

/// The chat's working folder as extensions get it: `cwd` on hook events and
/// in `tool.call` params. The session's folder when there is one (daemon
/// chats, workers), else the host process's (in-process hosts, where the two
/// are the same). As the client gave it: not canonicalised, not walked up to
/// a repository root. `None` (JSON `null`) when that path is not valid UTF-8
/// or the process folder cannot be read. No off switch, unlike `session_id`.
pub fn hook_cwd(cwd: Option<&Path>) -> Option<String> {
    match cwd {
        Some(dir) => dir.to_str().map(str::to_string),
        None => std::env::current_dir().ok()?.to_str().map(str::to_string),
    }
}

/// 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 | cwd |
/// |-----------------------|-----------|------------|-------------|---------|------------|-----|
/// | `before_tool_call`    | ✓         | ✓          |             |         | ✓*         | ✓   |
/// | `after_tool_call`     | ✓         | ✓          | ✓           |         | ✓*         | ✓   |
/// | `before_message`      |           |            |             | ✓       | ✓*         | ✓   |
/// | `on_message_complete` |           |            |             | ✓       | ✓*         | ✓   |
/// | `on_compaction`       |           |            |             | ✓       | ✓          | ✓   |
/// | `on_session_start`    |           |            |             |         | ✓          | ✓   |
/// | `on_session_end`      |           |            |             |         | ✓          | ✓   |
/// | `on_context_archived` |           |            |             |         | ✓          | ✓   |
/// | `on_memory_forgotten` |           |            |             |         | ✓†         | ✓   |
///
/// `on_context_archived` and `on_memory_forgotten` carry their payload in
/// `data`.
///
/// `✓*` — set via [`HookEvent::with_session`] for foreground sessions; `null`
/// for workers (no conversation id) and when `SYNAPS_HOOK_SESSION_ID=0`.
///
/// `✓†` — the chat whose tool call did the forgetting; `null` when the call
/// had no chat behind it.
///
/// `cwd` is stamped by [`HookEvent::with_cwd`] where the event is emitted,
/// workers included. The constructors leave it `None`: only the emitter
/// knows which chat the event is for.
///
/// 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>,
    /// The chat's working folder ([`hook_cwd`]).
    #[serde(default)]
    pub cwd: 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 {
    /// Attach the owning conversation id to a tool/message event (builder).
    ///
    /// Additive: the JSON field already exists (`session_id`), so extensions
    /// that ignore it are unaffected. Workers pass `None` and keep emitting
    /// `null`. Kill-switch `SYNAPS_HOOK_SESSION_ID=0` forces `null` for a
    /// misbehaving plugin.
    pub fn with_session(mut self, id: Option<&str>) -> Self {
        self.session_id = if hook_session_id_enabled() {
            id.map(str::to_string)
        } else {
            None
        };
        self
    }

    /// Stamp the chat's working folder (builder). `None` = the session has
    /// no folder of its own, so the process folder; see [`hook_cwd`].
    ///
    /// Additive: extensions that ignore `cwd` are unaffected.
    pub fn with_cwd(mut self, cwd: Option<&Path>) -> Self {
        self.cwd = hook_cwd(cwd);
        self
    }

    /// 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,
            cwd: 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,
            cwd: 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,
            cwd: 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,
            cwd: 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()),
            cwd: None,
            tool_runtime_name: None,
            transcript: None,
            data,
        }
    }

    /// Construct an `on_context_archived` event: a context rollover sealed a
    /// window of chat `session_id` into the archive file at `path` (`None`
    /// when the file could not be located, or its path is not UTF-8).
    /// `window` is the window that starts after the archive.
    ///
    /// A window is one archive unless it was over a per-archive limit, so
    /// the event is built as part 1 of 1, starting at source message 0, with
    /// nothing reduced. An oversized window is sealed as several archives,
    /// one event each: [`HookEvent::with_part`] then says which one this is.
    pub fn on_context_archived(
        session_id: &str,
        archive_id: &str,
        path: Option<&Path>,
        project_key: &str,
        message_count: usize,
        source_message_count: usize,
        window: u64,
    ) -> Self {
        Self {
            kind: HookKind::OnContextArchived,
            tool_name: None,
            tool_input: None,
            tool_output: None,
            message: None,
            session_id: Some(session_id.to_string()),
            cwd: None,
            tool_runtime_name: None,
            transcript: None,
            data: serde_json::json!({
                "archive_id": archive_id,
                "path": path.and_then(Path::to_str),
                "project_key": project_key,
                "message_count": message_count,
                "source_message_count": source_message_count,
                "window": window,
                "part": 1,
                "parts": 1,
                "first_source_index": 0,
                "reduced_messages": 0,
            }),
        }
    }

    /// Say which of its window's archives an `on_context_archived` event is
    /// for (builder): archive `part` of `parts`, counting from 1, covering
    /// the window's source messages from `first_source_index`, with
    /// `reduced_messages` of them stored with an oversized payload left out.
    /// The fields are already in `data`; on any other event this does nothing.
    pub fn with_part(
        mut self,
        part: usize,
        parts: usize,
        first_source_index: usize,
        reduced_messages: usize,
    ) -> Self {
        if let (HookKind::OnContextArchived, Some(data)) = (self.kind, self.data.as_object_mut()) {
            for (field, value) in [
                ("part", part),
                ("parts", parts),
                ("first_source_index", first_source_index),
                ("reduced_messages", reduced_messages),
            ] {
                data.insert(field.to_owned(), value.into());
            }
        }
        self
    }

    /// Construct an `on_memory_forgotten` event: `memory_forget` forgot the
    /// archive or note `id` in project `project_key`. `kind` is `"archive"`
    /// or `"note"`, `scope` is `"repository"` (the tool has no other). `session_id` is
    /// the chat whose tool call it was (`None`: no chat behind the call). An
    /// archive's `id` is the bare id, as in `on_context_archived`, without
    /// the model-facing `ctx-` prefix.
    pub fn on_memory_forgotten(
        session_id: Option<&str>,
        id: &str,
        kind: &str,
        project_key: &str,
        scope: &str,
    ) -> Self {
        Self {
            kind: HookKind::OnMemoryForgotten,
            tool_name: None,
            tool_input: None,
            tool_output: None,
            message: None,
            session_id: session_id.map(str::to_string),
            cwd: None,
            tool_runtime_name: None,
            transcript: None,
            data: serde_json::json!({
                "id": id,
                "kind": kind,
                "project_key": project_key,
                "scope": scope,
            }),
        }
    }

    /// 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()),
            cwd: None,
            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()),
            cwd: None,
            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:
/// - For `before_tool_call` only `Block` stops the handler chain. `Modify`
///   rewrites the input that later handlers see; `Confirm` is merged and
///   resolved after the whole chain (a `Modify` after it is ignored).
/// - `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.
    ///
    /// `sources` / `tool` are host-stamped by `HookBus::emit` (the extension
    /// id(s) that asked, and the tool name). They are never read from or
    /// written to the extension wire format, so an extension cannot claim to
    /// be another extension. The "Allow all" latch is keyed by `sources`.
    Confirm {
        message: String,
        #[serde(skip)]
        sources: Vec<String>,
        /// Host-set load generation of each source (parallel to `sources`;
        /// missing entries mean 0). Part of the latch key, so a plugin
        /// reinstalled under the same id starts unlatched.
        #[serde(skip)]
        generations: Vec<u64>,
        #[serde(skip)]
        tool: Option<String>,
        /// Host-set: the input as rewritten by `Modify` results earlier in
        /// the chain. Approval runs THIS input (never extension-settable).
        #[serde(skip)]
        modified_input: Option<Value>,
        /// Host-set: ids of the extensions whose `Modify` produced
        /// `modified_input` (chain order, de-duplicated). Shown in the
        /// prompt so the user knows the input was rewritten, and by whom.
        #[serde(skip)]
        modified_by: Vec<String>,
    },
    /// Replace the tool **input** before execution (structured JSON args).
    /// Only valid on before_tool_call hooks. The output-side counterpart is
    /// [`HookResult::Replace`]. Does not stop the chain: later handlers see
    /// (and may block or confirm) the modified input.
    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 },
    /// Advisory work-phase report for the host's automatic context
    /// management. Only valid on `on_message_complete`, and only honoured
    /// when the extension additionally holds `session.lifecycle`. Semantics
    /// are identical to the model calling `context_checkpoint` with this
    /// phase and no note: the host may roll the context window over at the
    /// next task boundary. It is a lower-authority report — never capacity,
    /// permission, or history authority — and does not stop the handler
    /// chain (other observers still run; the first valid report wins).
    /// `phase` is parsed host-side with `WorkPhase::parse`; unknown strings
    /// are ignored with a warning.
    ContextPhase { phase: String },
}

impl HookResult {
    /// An unattributed `Confirm` (as an extension returns it, before
    /// `HookBus::emit` stamps the source).
    pub fn confirm(message: impl Into<String>) -> Self {
        Self::Confirm {
            message: message.into(),
            sources: Vec::new(),
            generations: Vec::new(),
            tool: None,
            modified_input: None,
            modified_by: vec![],
        }
    }
}

// ── 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");
    }

    /// The extension wire format `{"action":"context_phase","phase":"..."}`
    /// deserializes to HookResult::ContextPhase and round-trips back.
    #[test]
    fn context_phase_action_roundtrips_extension_wire_format() {
        let wire = json!({"action": "context_phase", "phase": "new_task"});
        let parsed: HookResult = serde_json::from_value(wire).expect("must deserialize");
        match &parsed {
            HookResult::ContextPhase { phase } => assert_eq!(phase, "new_task"),
            other => panic!("expected ContextPhase, got {other:?}"),
        }

        let out = serde_json::to_value(&parsed).unwrap();
        assert_eq!(out, json!({"action": "context_phase", "phase": "new_task"}));
        let back: HookResult = serde_json::from_value(out).unwrap();
        assert_eq!(back, parsed);

        // A missing `phase` is a malformed result, not a silent default.
        assert!(serde_json::from_value::<HookResult>(json!({"action": "context_phase"})).is_err());
    }

    /// on_message_complete may return ContextPhase; no other hook may, and
    /// on_message_complete advertises "context_phase" in its action contract.
    #[test]
    fn only_on_message_complete_allows_context_phase() {
        let report = HookResult::ContextPhase {
            phase: "execute".into(),
        };
        for kind in HookKind::ALL {
            assert_eq!(
                kind.allows_result(&report),
                *kind == HookKind::OnMessageComplete,
                "context_phase must be allowed only on on_message_complete (checked {})",
                kind.as_str()
            );
        }
        assert!(HookKind::OnMessageComplete
            .allowed_action_names()
            .contains(&"context_phase"));
        // Still observe-only for everything else.
        assert!(
            !HookKind::OnMessageComplete.allows_result(&HookResult::Block { reason: "r".into() })
        );
        assert!(
            !HookKind::OnMessageComplete.allows_result(&HookResult::Inject {
                content: "c".into()
            })
        );
    }

    // ── 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,
            HookKind::OnContextArchived,
            HookKind::OnMemoryForgotten,
        ];
        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
        );
        assert_eq!(
            HookKind::OnContextArchived.required_permission(),
            Permission::LlmContent
        );
        assert_eq!(
            HookKind::OnMemoryForgotten.required_permission(),
            Permission::SessionLifecycle
        );
    }

    /// The notify-only kinds: no tool filter, and `continue` is the only
    /// answer they accept (it is discarded anyway).
    #[test]
    fn notification_kinds_are_continue_only() {
        let notifications: Vec<HookKind> = HookKind::ALL
            .iter()
            .copied()
            .filter(HookKind::is_notification)
            .collect();
        assert_eq!(
            notifications,
            [HookKind::OnContextArchived, HookKind::OnMemoryForgotten]
        );
        for kind in notifications {
            assert_eq!(kind.allowed_action_names(), ["continue"], "{kind:?}");
            assert!(!kind.allows_tool_filter(), "{kind:?}");
            assert!(kind.allows_result(&HookResult::Continue));
            for refused in [
                HookResult::Block { reason: "r".into() },
                HookResult::Inject { content: "c".into() },
                HookResult::confirm("m"),
                HookResult::Modify { input: json!({}) },
                HookResult::Replace { output: "o".into() },
                HookResult::ContextPhase { phase: "new_task".into() },
            ] {
                assert!(!kind.allows_result(&refused), "{kind:?} {refused:?}");
            }
        }
    }

    // ── 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());
    }

    /// The wire shape of `on_context_archived`: everything new is in `data`,
    /// and a single archive is part 1 of 1.
    #[test]
    fn hook_event_on_context_archived() {
        let id = "9f2c".repeat(8);
        let file = std::env::temp_dir().join("s000001").join(format!("{id}.json"));
        let ev = HookEvent::on_context_archived(
            "chat-1",
            &id,
            Some(&file),
            "p0123456789abcdef",
            212,
            240,
            4,
        );
        assert_eq!(
            serde_json::to_value(&ev).unwrap(),
            json!({
                "kind": "on_context_archived",
                "tool_name": null,
                "tool_runtime_name": null,
                "tool_input": null,
                "tool_output": null,
                "message": null,
                "session_id": "chat-1",
                "cwd": null,
                "transcript": null,
                "data": {
                    "archive_id": id,
                    "path": file.to_str().unwrap(),
                    "project_key": "p0123456789abcdef",
                    "message_count": 212,
                    "source_message_count": 240,
                    "window": 4,
                    "part": 1,
                    "parts": 1,
                    "first_source_index": 0,
                    "reduced_messages": 0,
                },
            })
        );
        // The id is always set: the SYNAPS_HOOK_SESSION_ID switch is for the
        // tool and message hooks, whose constructors leave it unset.
        assert_eq!(ev.session_id.as_deref(), Some("chat-1"));
        // A file that could not be located is `null`, never a guessed path.
        let lost = HookEvent::on_context_archived("chat-1", &id, None, "p0", 1, 1, 2);
        assert_eq!(lost.data["path"], Value::Null);
        assert_eq!(lost.data["archive_id"], json!(id));
    }

    /// One archive of a window sealed as several: `with_part` changes the
    /// four part fields and nothing else, and the values of a whole window
    /// leave the event exactly as it was built, key order included.
    #[test]
    fn hook_event_on_context_archived_for_one_part_of_several() {
        let id = "9f2c".repeat(8);
        let whole = || HookEvent::on_context_archived("chat-1", &id, None, "p0", 212, 240, 4);
        let wire = |ev: &HookEvent| serde_json::to_string(ev).unwrap();
        assert_eq!(wire(&whole().with_part(1, 1, 0, 0)), wire(&whole()));

        let second = whole().with_part(2, 3, 240, 1);
        let mut expected = serde_json::to_value(whole()).unwrap();
        expected["data"]["part"] = json!(2);
        expected["data"]["parts"] = json!(3);
        expected["data"]["first_source_index"] = json!(240);
        expected["data"]["reduced_messages"] = json!(1);
        assert_eq!(serde_json::to_value(&second).unwrap(), expected);
        assert_eq!(
            second.data.as_object().unwrap().len(),
            whole().data.as_object().unwrap().len(),
            "no field is added"
        );

        // Not an archive event: untouched, whatever its data is.
        let other = HookEvent::on_session_start("chat-1");
        assert_eq!(wire(&other.clone().with_part(2, 3, 240, 1)), wire(&other));
    }

    /// The wire shape of `on_memory_forgotten`: ids only, in `data`.
    #[test]
    fn hook_event_on_memory_forgotten() {
        let id = "9f2c".repeat(8);
        let ev =
            HookEvent::on_memory_forgotten(Some("chat-1"), &id, "archive", "p0123456789abcdef", "repository");
        assert_eq!(
            serde_json::to_value(&ev).unwrap(),
            json!({
                "kind": "on_memory_forgotten",
                "tool_name": null,
                "tool_runtime_name": null,
                "tool_input": null,
                "tool_output": null,
                "message": null,
                "session_id": "chat-1",
                "cwd": null,
                "transcript": null,
                "data": {
                    "id": id,
                    "kind": "archive",
                    "project_key": "p0123456789abcdef",
                    "scope": "repository",
                },
            })
        );
        // A user-wide note, forgotten by a call with no chat behind it.
        let note =
            HookEvent::on_memory_forgotten(None, "mem-1", "note", "p0000000000000000", "user");
        assert_eq!(note.session_id, None);
        assert_eq!(
            note.data,
            json!({"id": "mem-1", "kind": "note", "project_key": "p0000000000000000", "scope": "user"})
        );
    }

    #[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);
    }

    // ── cwd ───────────────────────────────────────────────────────────────────

    /// A session folder is sent as given: not canonicalised, not required to
    /// exist. Built from the platform temp dir so the shape is the host's.
    #[test]
    fn with_cwd_serialises_the_session_folder_as_given() {
        let dir = std::env::temp_dir().join("hook-cwd").join("..").join("proj");
        let ev = HookEvent::before_message("hi").with_cwd(Some(&dir));
        let wire = serde_json::to_value(&ev).unwrap();
        assert_eq!(wire["cwd"], json!(dir.to_str().unwrap()));
    }

    /// No session folder (in-process hosts): the process folder.
    #[test]
    fn with_cwd_none_serialises_the_process_folder() {
        let process = std::env::current_dir().unwrap();
        let ev = HookEvent::on_session_start("s").with_cwd(None);
        let wire = serde_json::to_value(&ev).unwrap();
        assert_eq!(wire["cwd"], json!(process.to_str().unwrap()));
    }

    /// Every kind has the key on the wire, `null` until an emitter stamps it.
    #[test]
    fn cwd_key_is_always_present() {
        for ev in [
            HookEvent::before_tool_call("bash", json!({})),
            HookEvent::after_tool_call("bash", json!({}), "o".into()),
            HookEvent::before_message("m"),
            HookEvent::on_message_complete("m", json!({})),
            HookEvent::on_compaction("a", "b", "s", 1, json!({})),
            HookEvent::on_session_start("s"),
            HookEvent::on_session_end("s", None),
            HookEvent::on_context_archived("s", "a", None, "p", 1, 1, 2),
            HookEvent::on_memory_forgotten(Some("s"), "a", "archive", "p", "repository"),
        ] {
            let wire = serde_json::to_value(&ev).unwrap();
            assert_eq!(wire.get("cwd"), Some(&Value::Null), "{:?}", ev.kind);
        }
    }

    /// A folder that cannot be written as a JSON string is `null`, never a
    /// lossy rewrite and never the process folder.
    #[cfg(unix)]
    #[test]
    fn non_utf8_cwd_is_null() {
        use std::os::unix::ffi::OsStrExt;
        let dir = Path::new(std::ffi::OsStr::from_bytes(b"/tmp/hook-cwd-\xff"));
        assert_eq!(hook_cwd(Some(dir)), None);
        let ev = HookEvent::before_message("hi").with_cwd(Some(dir));
        assert_eq!(serde_json::to_value(&ev).unwrap()["cwd"], Value::Null);
    }

    /// The same rule for an archive's `path`.
    #[cfg(unix)]
    #[test]
    fn non_utf8_archive_path_is_null() {
        use std::os::unix::ffi::OsStrExt;
        let file = Path::new(std::ffi::OsStr::from_bytes(b"/tmp/archives-\xff/a.json"));
        let ev = HookEvent::on_context_archived("s", "a", Some(file), "p", 1, 1, 2);
        assert_eq!(ev.data["path"], Value::Null);
    }

    // ── 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(),
            sources: vec!["host-stamped".into()],
            generations: vec![3],
            tool: Some("bash".into()),
            modified_input: Some(serde_json::json!({"x": 1})),
            modified_by: vec![],
        };
        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?"));

        // An extension cannot name a source: wire fields are ignored.
        let spoof: HookResult = serde_json::from_str(
            r#"{"action":"confirm","message":"m","sources":["trusted"],"tool":"x"}"#,
        )
        .unwrap();
        assert!(
            matches!(&spoof, HookResult::Confirm { sources, tool: None, modified_input: None, modified_by, .. } if sources.is_empty() && modified_by.is_empty()),
            "{spoof:?}"
        );
    }

    /// 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
                | HookKind::OnContextArchived
                | HookKind::OnMemoryForgotten => {}
            }
        }
        assert_eq!(
            HookKind::ALL.len(),
            9,
            "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); 7] = [
            ("continue", HookResult::Continue),
            ("block", HookResult::Block { reason: "r".into() }),
            (
                "confirm",
                HookResult::Confirm {
                    message: "m".into(),
                    sources: vec![],
                    generations: vec![],
                    tool: None,
                    modified_input: None,
                    modified_by: vec![],
                },
            ),
            (
                "modify",
                HookResult::Modify {
                    input: serde_json::json!({}),
                },
            ),
            ("replace", HookResult::Replace { output: "o".into() }),
            (
                "inject",
                HookResult::Inject {
                    content: "c".into(),
                },
            ),
            (
                "context_phase",
                HookResult::ContextPhase {
                    phase: "new_task".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
                );
            }
        }
    }
}