Skip to main content

kian_plugin/hooks/
ids.rs

1//! The closed hook vocabulary (PLUGIN-SPEC §3.1, §3.6).
2//!
3//! `HookId` is an enum over §3.1's closed catalog plus a `Harness`
4//! arm whose registry is **empty** in v1 (§3.6 / ADR-028 D27): a
5//! `harness/<name>/<point>` id *parses* but is a registry miss, so a
6//! manifest subscribing one is refused `unknown_hook` at boot (validation
7//! rule 8) and the bus never dispatches it.
8//!
9//! `HookMode` mirrors the tier-0 dispatch mode that also fixes the legal
10//! sidecar reply (§3.3); `HookClass` groups hooks for grants (§5.1) and is
11//! the single source of the §7.2 epoch rule through
12//! [`HookClass::is_drain_phase`].
13
14use std::borrow::Cow;
15use std::fmt;
16
17/// Which payload of the §3.2 catalog a hook dispatches.
18///
19/// Kept as a column of the [`CATALOG`] table so "mode / class / payload
20/// agree" is checkable in one place (PLUGIN-SPEC §18: a hook id without
21/// all six registrations is not part of the contract).
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub enum PayloadKind {
24    AdmitPre,
25    AdmitPost,
26    TurnRequest,
27    TurnResponse,
28    ToolPre,
29    ToolPost,
30    RecoverDecided,
31    SettlePre,
32    /// `plugin/*` lifecycle payloads (§3.2.9) — owned by the sidecar
33    /// machinery (P3); the tier-0 bus never dispatches them in P1.
34    PluginLifecycle,
35    /// `harness/<name>/<point>` payloads — declared by the owning harness
36    /// together with its registry entry (§3.6); the v1 registry is empty.
37    Harness,
38}
39
40/// The tier-0 dispatch mode of a hook, which also fixes the legal reply
41/// (§3.3). Tier-0 handlers are ordinary async functions; the mode is what
42/// the bus enforces when it classifies a reply.
43#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
44pub enum HookMode {
45    /// Observe only; legal reply `ack` (§3.3 `emit`).
46    Emit,
47    /// `admit/pre` only; legal replies `flow:"next"` / `flow:"stop"` (§3.3).
48    Flow,
49    /// `tool/pre`, `settle/pre`; legal replies `bail:null` / `bail:{deny}`
50    /// (§3.3).
51    Bail,
52}
53
54/// The grant class a hook belongs to (§5.1). A `veto:*` grant is keyed by
55/// this class, and the §7.2 epoch rule hangs off
56/// [`HookClass::is_drain_phase`].
57#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
58pub enum HookClass {
59    Admit,
60    Turn,
61    Tool,
62    Recover,
63    Settle,
64    /// The `harness/<name>/*` namespace (§3.6); empty registry in v1.
65    Harness,
66    /// Bus lifecycle (`plugin/load|refuse|quarantine`, §3.2.9); tier-0
67    /// only, never sidecar-subscribable.
68    Plugin,
69}
70
71impl HookClass {
72    /// The §7.2 epoch rule's single source: frames for drain-phase hooks
73    /// (`turn/*`, `tool/*`, `recover/decided`, `settle/pre`) carry the
74    /// fencing epoch; `admit/*` and `plugin/*` run before a drain exists
75    /// (or are bus lifecycle) and their frames omit the key entirely.
76    ///
77    /// Harness points are declared by their owning harness together with
78    /// the registry entry; the v1 registry is empty, so no dispatch can
79    /// ever consult this arm.
80    pub fn is_drain_phase(self) -> bool {
81        match self {
82            HookClass::Turn | HookClass::Tool | HookClass::Recover | HookClass::Settle => true,
83            HookClass::Admit | HookClass::Plugin | HookClass::Harness => false,
84        }
85    }
86}
87
88/// One declared harness point: `harness/<harness>/<point>`, both segments
89/// `^[a-z0-9][a-z0-9_-]*$` (§3.6). No wildcard subscriptions exist.
90#[derive(Debug, Clone, PartialEq, Eq, Hash)]
91pub struct HarnessPoint {
92    pub harness: String,
93    pub point: String,
94}
95
96impl HarnessPoint {
97    /// Parses `harness/<h>/<p>` with both segments validated against
98    /// `^[a-z0-9][a-z0-9_-]*$`. A parse success is *not* a registry hit —
99    /// the v1 registry is empty (§3.6).
100    pub fn parse(id: &str) -> Option<Self> {
101        let rest = id.strip_prefix("harness/")?;
102        let (harness, point) = rest.split_once('/')?;
103        // Exactly two segments: a second '/' in the point is not a point.
104        if point.contains('/') {
105            return None;
106        }
107        if !valid_segment(harness) || !valid_segment(point) {
108            return None;
109        }
110        Some(Self {
111            harness: harness.to_string(),
112            point: point.to_string(),
113        })
114    }
115
116    /// The wire spelling `harness/<harness>/<point>`.
117    pub fn as_str(&self) -> String {
118        format!("harness/{}/{}", self.harness, self.point)
119    }
120}
121
122fn valid_segment(s: &str) -> bool {
123    let mut chars = s.chars();
124    match chars.next() {
125        Some(c) if c.is_ascii_lowercase() || c.is_ascii_digit() => {}
126        _ => return false,
127    }
128    chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_' || c == '-')
129}
130
131/// The closed hook id catalog (§3.1).
132#[derive(Debug, Clone, PartialEq, Eq, Hash)]
133pub enum HookId {
134    AdmitPre,
135    AdmitPost,
136    TurnRequest,
137    TurnResponse,
138    ToolPre,
139    ToolPost,
140    RecoverDecided,
141    SettlePre,
142    PluginLoad,
143    PluginRefuse,
144    PluginQuarantine,
145    /// `harness/<name>/<point>` (§3.6); parseable, registry-empty in v1.
146    Harness(HarnessPoint),
147}
148
149impl HookId {
150    /// Canonical wire spelling (§3.1 / §3.6). Borrowed for the closed
151    /// catalog, owned for the harness namespace.
152    pub fn as_str(&self) -> Cow<'_, str> {
153        match self {
154            HookId::AdmitPre => Cow::Borrowed("admit/pre"),
155            HookId::AdmitPost => Cow::Borrowed("admit/post"),
156            HookId::TurnRequest => Cow::Borrowed("turn/request"),
157            HookId::TurnResponse => Cow::Borrowed("turn/response"),
158            HookId::ToolPre => Cow::Borrowed("tool/pre"),
159            HookId::ToolPost => Cow::Borrowed("tool/post"),
160            HookId::RecoverDecided => Cow::Borrowed("recover/decided"),
161            HookId::SettlePre => Cow::Borrowed("settle/pre"),
162            HookId::PluginLoad => Cow::Borrowed("plugin/load"),
163            HookId::PluginRefuse => Cow::Borrowed("plugin/refuse"),
164            HookId::PluginQuarantine => Cow::Borrowed("plugin/quarantine"),
165            HookId::Harness(point) => Cow::Owned(point.as_str()),
166        }
167    }
168
169    /// Parses a hook id. `harness/…` ids parse (segments validated) but are
170    /// registry misses — see [`HARNESS_REGISTRY`].
171    pub fn parse(id: &str) -> Option<Self> {
172        match id {
173            "admit/pre" => Some(HookId::AdmitPre),
174            "admit/post" => Some(HookId::AdmitPost),
175            "turn/request" => Some(HookId::TurnRequest),
176            "turn/response" => Some(HookId::TurnResponse),
177            "tool/pre" => Some(HookId::ToolPre),
178            "tool/post" => Some(HookId::ToolPost),
179            "recover/decided" => Some(HookId::RecoverDecided),
180            "settle/pre" => Some(HookId::SettlePre),
181            "plugin/load" => Some(HookId::PluginLoad),
182            "plugin/refuse" => Some(HookId::PluginRefuse),
183            "plugin/quarantine" => Some(HookId::PluginQuarantine),
184            _ => HarnessPoint::parse(id).map(HookId::Harness),
185        }
186    }
187
188    /// The catalog row's mode (§3.1 "Mode" column; §3.3 fixes it per id).
189    pub fn mode(&self) -> HookMode {
190        match self {
191            HookId::AdmitPre => HookMode::Flow,
192            HookId::ToolPre | HookId::SettlePre => HookMode::Bail,
193            HookId::Harness(point) => harness_declared(point).unwrap_or(HookMode::Emit),
194            _ => HookMode::Emit,
195        }
196    }
197
198    /// The catalog row's grant class (§5.1).
199    pub fn class(&self) -> HookClass {
200        match self {
201            HookId::AdmitPre | HookId::AdmitPost => HookClass::Admit,
202            HookId::TurnRequest | HookId::TurnResponse => HookClass::Turn,
203            HookId::ToolPre | HookId::ToolPost => HookClass::Tool,
204            HookId::RecoverDecided => HookClass::Recover,
205            HookId::SettlePre => HookClass::Settle,
206            HookId::PluginLoad | HookId::PluginRefuse | HookId::PluginQuarantine => {
207                HookClass::Plugin
208            }
209            HookId::Harness(_) => HookClass::Harness,
210        }
211    }
212
213    /// The catalog row's payload (§3.2).
214    pub fn payload_kind(&self) -> PayloadKind {
215        match self {
216            HookId::AdmitPre => PayloadKind::AdmitPre,
217            HookId::AdmitPost => PayloadKind::AdmitPost,
218            HookId::TurnRequest => PayloadKind::TurnRequest,
219            HookId::TurnResponse => PayloadKind::TurnResponse,
220            HookId::ToolPre => PayloadKind::ToolPre,
221            HookId::ToolPost => PayloadKind::ToolPost,
222            HookId::RecoverDecided => PayloadKind::RecoverDecided,
223            HookId::SettlePre => PayloadKind::SettlePre,
224            HookId::PluginLoad | HookId::PluginRefuse | HookId::PluginQuarantine => {
225                PayloadKind::PluginLifecycle
226            }
227            HookId::Harness(_) => PayloadKind::Harness,
228        }
229    }
230
231    /// Whether a sidecar may subscribe this hook in v1 (§3.1 "Sidecar"
232    /// column; `plugin/*` is bus-owned, tier-0 only).
233    pub fn sidecar_subscribable(&self) -> bool {
234        !matches!(
235            self,
236            HookId::PluginLoad | HookId::PluginRefuse | HookId::PluginQuarantine
237        )
238    }
239}
240
241impl fmt::Display for HookId {
242    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
243        f.write_str(&self.as_str())
244    }
245}
246
247/// The closed catalog as one table (§3.1):
248/// `(hook id, mode, class, payload, sidecar-subscribable)`. The test module
249/// asserts this table against the accessor methods so the two cannot drift.
250type CatalogEntry = (&'static str, HookMode, HookClass, PayloadKind, bool);
251
252static CATALOG: &[CatalogEntry] = &[
253    (
254        "admit/pre",
255        HookMode::Flow,
256        HookClass::Admit,
257        PayloadKind::AdmitPre,
258        true,
259    ),
260    (
261        "admit/post",
262        HookMode::Emit,
263        HookClass::Admit,
264        PayloadKind::AdmitPost,
265        true,
266    ),
267    (
268        "turn/request",
269        HookMode::Emit,
270        HookClass::Turn,
271        PayloadKind::TurnRequest,
272        true,
273    ),
274    (
275        "turn/response",
276        HookMode::Emit,
277        HookClass::Turn,
278        PayloadKind::TurnResponse,
279        true,
280    ),
281    (
282        "tool/pre",
283        HookMode::Bail,
284        HookClass::Tool,
285        PayloadKind::ToolPre,
286        true,
287    ),
288    (
289        "tool/post",
290        HookMode::Emit,
291        HookClass::Tool,
292        PayloadKind::ToolPost,
293        true,
294    ),
295    (
296        "recover/decided",
297        HookMode::Emit,
298        HookClass::Recover,
299        PayloadKind::RecoverDecided,
300        true,
301    ),
302    (
303        "settle/pre",
304        HookMode::Bail,
305        HookClass::Settle,
306        PayloadKind::SettlePre,
307        true,
308    ),
309    (
310        "plugin/load",
311        HookMode::Emit,
312        HookClass::Plugin,
313        PayloadKind::PluginLifecycle,
314        false,
315    ),
316    (
317        "plugin/refuse",
318        HookMode::Emit,
319        HookClass::Plugin,
320        PayloadKind::PluginLifecycle,
321        false,
322    ),
323    (
324        "plugin/quarantine",
325        HookMode::Emit,
326        HookClass::Plugin,
327        PayloadKind::PluginLifecycle,
328        false,
329    ),
330];
331
332/// The catalog table itself (for tests and boot-time validation).
333pub fn catalog() -> &'static [CatalogEntry] {
334    CATALOG
335}
336
337/// The harness point registry (§3.6): an array of
338/// `(harness, point, mode)` triples, contract only when the owning harness
339/// ships the entry — which must then also appear in §3.1, §3.4.1 and §3.2
340/// in the same change. **The v1 registry is empty** (ADR-028 D27).
341pub static HARNESS_REGISTRY: &[(&str, &str, HookMode)] = &[];
342
343/// Whether a harness id is declared in [`HARNESS_REGISTRY`] — the check
344/// validation rule 8 performs for `harness/…` subscriptions.
345pub fn harness_declared(point: &HarnessPoint) -> Option<HookMode> {
346    HARNESS_REGISTRY
347        .iter()
348        .find(|(h, p, _)| *h == point.harness && *p == point.point)
349        .map(|(_, _, mode)| *mode)
350}
351
352#[cfg(test)]
353mod tests {
354    use super::*;
355
356    #[test]
357    fn catalog_is_closed_and_each_row_has_mode_and_class() {
358        // §3.1's eleven rows, with mode/class/payload exactly as the
359        // contract states them (§3.3 fixes the mode per hook id).
360        let expected: &[(&str, HookMode, HookClass, PayloadKind, bool)] = &[
361            (
362                "admit/pre",
363                HookMode::Flow,
364                HookClass::Admit,
365                PayloadKind::AdmitPre,
366                true,
367            ),
368            (
369                "admit/post",
370                HookMode::Emit,
371                HookClass::Admit,
372                PayloadKind::AdmitPost,
373                true,
374            ),
375            (
376                "turn/request",
377                HookMode::Emit,
378                HookClass::Turn,
379                PayloadKind::TurnRequest,
380                true,
381            ),
382            (
383                "turn/response",
384                HookMode::Emit,
385                HookClass::Turn,
386                PayloadKind::TurnResponse,
387                true,
388            ),
389            (
390                "tool/pre",
391                HookMode::Bail,
392                HookClass::Tool,
393                PayloadKind::ToolPre,
394                true,
395            ),
396            (
397                "tool/post",
398                HookMode::Emit,
399                HookClass::Tool,
400                PayloadKind::ToolPost,
401                true,
402            ),
403            (
404                "recover/decided",
405                HookMode::Emit,
406                HookClass::Recover,
407                PayloadKind::RecoverDecided,
408                true,
409            ),
410            (
411                "settle/pre",
412                HookMode::Bail,
413                HookClass::Settle,
414                PayloadKind::SettlePre,
415                true,
416            ),
417            (
418                "plugin/load",
419                HookMode::Emit,
420                HookClass::Plugin,
421                PayloadKind::PluginLifecycle,
422                false,
423            ),
424            (
425                "plugin/refuse",
426                HookMode::Emit,
427                HookClass::Plugin,
428                PayloadKind::PluginLifecycle,
429                false,
430            ),
431            (
432                "plugin/quarantine",
433                HookMode::Emit,
434                HookClass::Plugin,
435                PayloadKind::PluginLifecycle,
436                false,
437            ),
438        ];
439        assert_eq!(CATALOG.len(), expected.len());
440        assert_eq!(CATALOG, expected, "the catalog table is §3.1, verbatim");
441
442        for (id, mode, class, payload, sidecar) in CATALOG {
443            let hook = HookId::parse(id).expect("every catalog id parses");
444            // Round-trip: as_str/parse agree for every closed row.
445            assert_eq!(hook.as_str(), Cow::Borrowed(*id));
446            assert_eq!(hook.mode(), *mode, "mode of {id}");
447            assert_eq!(hook.class(), *class, "class of {id}");
448            assert_eq!(hook.payload_kind(), *payload, "payload of {id}");
449            assert_eq!(
450                hook.sidecar_subscribable(),
451                *sidecar,
452                "sidecar availability of {id}"
453            );
454        }
455
456        // The catalog is closed: a made-up id does not parse.
457        assert!(HookId::parse("tool/pre-flight").is_none());
458        assert!(HookId::parse("admit").is_none());
459        assert!(HookId::parse("").is_none());
460    }
461
462    #[test]
463    fn admission_hooks_are_not_drain_phase() {
464        // §7.2: epoch rides only drain-phase frames. Both directions.
465        for id in [
466            "admit/pre",
467            "admit/post",
468            "plugin/load",
469            "plugin/refuse",
470            "plugin/quarantine",
471        ] {
472            let hook = HookId::parse(id).unwrap();
473            assert!(!hook.class().is_drain_phase(), "{id} is not drain-phase");
474        }
475        for id in [
476            "turn/request",
477            "turn/response",
478            "tool/pre",
479            "tool/post",
480            "recover/decided",
481            "settle/pre",
482        ] {
483            let hook = HookId::parse(id).unwrap();
484            assert!(hook.class().is_drain_phase(), "{id} is drain-phase");
485        }
486    }
487
488    #[test]
489    fn harness_namespace_is_empty() {
490        // §3.6/D27: `harness/x/y` is a parse success and a registry miss.
491        let id = HookId::parse("harness/dsh/start").expect("harness id parses");
492        match &id {
493            HookId::Harness(point) => {
494                assert_eq!(point.harness, "dsh");
495                assert_eq!(point.point, "start");
496            }
497            other => panic!("expected Harness arm, got {other:?}"),
498        }
499        assert_eq!(
500            id.as_str(),
501            Cow::<str>::Owned("harness/dsh/start".to_string())
502        );
503        let point = match &id {
504            HookId::Harness(p) => p.clone(),
505            _ => unreachable!(),
506        };
507        assert!(
508            harness_declared(&point).is_none(),
509            "the v1 harness registry is empty — every harness id is a miss"
510        );
511
512        // Segment grammar (§3.6): both segments ^[a-z0-9][a-z0-9_-]*$.
513        for bad in [
514            "harness//start",
515            "harness/dsh/",
516            "harness/Dsh/start",
517            "harness/dsh/start/extra",
518            "harness/ds h/start",
519        ] {
520            assert!(HookId::parse(bad).is_none(), "{bad} must not parse");
521        }
522        for good in ["harness/dsh/start", "harness/kian_loop/pre-render_2"] {
523            assert!(HookId::parse(good).is_some(), "{good} must parse");
524        }
525    }
526}