tuff-hooks-spec 0.16.0

Canonical hook event and compatibility types for Tuff-managed hooks.
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
//! Canonical hook metadata for Tuff-standard hooks.
//!
//! This crate models the stable vocabulary Tuff uses when a hook is authored in
//! Tuff's manifest format and then rendered by an adapter into a native harness
//! format. It does not model native harness hook fragments; those remain
//! adapter-owned passthrough data.

use serde::{Deserialize, Serialize};

/// Current version of the Tuff hook specification.
pub const SPEC_VERSION: &str = "0.2.0";

/// The spec version that introduced the seven events of the first
/// published vocabulary. Kept apart from [`SPEC_VERSION`] so that moving
/// the spec forward does not rewrite when an existing event arrived.
const FIRST_SPEC_VERSION: &str = "0.1.0";

/// Canonical Tuff hook events.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum HookEvent {
    /// A session or subagent starts.
    SessionStart,
    /// A main session ends.
    SessionEnd,
    /// A harness is about to execute a tool.
    PreToolUse,
    /// A harness has finished executing a tool.
    PostToolUse,
    /// A harness is about to finish the current turn or task.
    BeforeFinish,
    /// A harness saved a file.
    AfterSave,
    /// A harness stop/continuation point.
    Stop,
}

impl HookEvent {
    /// Returns the canonical snake_case event name.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::SessionStart => "session_start",
            Self::SessionEnd => "session_end",
            Self::PreToolUse => "pre_tool_use",
            Self::PostToolUse => "post_tool_use",
            Self::BeforeFinish => "before_finish",
            Self::AfterSave => "after_save",
            Self::Stop => "stop",
        }
    }
}

impl std::fmt::Display for HookEvent {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

/// Payload type names used by [`PayloadField`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PayloadValueType {
    /// String value.
    String,
    /// Boolean value.
    Boolean,
    /// Number value.
    Number,
    /// Structured JSON object.
    Object,
    /// JSON array.
    Array,
}

/// A field expected in a hook payload.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct PayloadField {
    /// Field name as it appears in the canonical payload descriptor.
    pub name: &'static str,
    /// Field value type.
    pub value_type: PayloadValueType,
    /// Whether the field is required for the canonical event.
    pub required: bool,
    /// Human-facing field description.
    pub description: &'static str,
}

/// A structured descriptor for a canonical event payload.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct PayloadSchema {
    /// Common and event-specific fields.
    pub fields: &'static [PayloadField],
}

impl PayloadSchema {
    /// Returns true when the descriptor contains no declared fields.
    pub fn is_empty(&self) -> bool {
        self.fields.is_empty()
    }
}

/// What a hook can block when a handler returns a blocking result.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum BlockingScope {
    /// The event is not blocking.
    NotBlocking,
    /// The hook can block the action that has not yet run.
    BlocksAction,
    /// The hook can block continuation after an action or turn.
    BlocksContinuation,
    /// Harness-specific blocking semantics documented by the adapter.
    Custom(&'static str),
}

/// Canonical event metadata.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct HookEventSpec {
    /// Canonical typed event.
    pub event: HookEvent,
    /// Event name used in Tuff-standard manifests.
    pub canonical_name: &'static str,
    /// Blocking behavior exposed by the canonical event.
    pub blocking: BlockingScope,
    /// First Tuff hook spec version that includes this event.
    pub since_spec_version: &'static str,
    /// Structured payload descriptor.
    pub payload_schema: PayloadSchema,
}

/// Adapter support level for a canonical event.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum CoverageLevel {
    /// The adapter supports the event for the declared scope.
    Full,
    /// The adapter supports the event only for the declared scope.
    Partial,
    /// The adapter does not support the event.
    Unsupported,
}

impl CoverageLevel {
    /// Returns whether this coverage level can render/run a hook.
    pub const fn is_supported(self) -> bool {
        !matches!(self, Self::Unsupported)
    }
}

/// Compatibility for one canonical event on one adapter.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct CompatibilityEntry {
    /// Canonical Tuff hook event.
    pub event: HookEvent,
    /// Native harness event name emitted by the adapter, when supported.
    pub native_event: Option<&'static str>,
    /// Legacy or native names accepted as aliases in Tuff manifests.
    pub aliases: &'static [&'static str],
    /// Support level for this event.
    pub coverage: CoverageLevel,
    /// Scope labels that explain partial coverage.
    pub scope: &'static [&'static str],
    /// Adapter or harness caveat, if any.
    pub caveat: Option<&'static str>,
    /// Source note or URL for the compatibility row.
    pub source: Option<&'static str>,
    /// First harness version known to have this behavior.
    pub since_harness_version: Option<&'static str>,
    /// Last harness version known to have this behavior.
    pub until_harness_version: Option<&'static str>,
}

impl CompatibilityEntry {
    /// Returns true when this row matches a manifest event name.
    pub fn matches_name(&self, raw_event: &str) -> bool {
        self.event.as_str() == raw_event || self.aliases.contains(&raw_event)
    }

    /// Returns the native event to emit when this row is supported.
    pub fn native_event_name(&self) -> Option<&'static str> {
        self.coverage
            .is_supported()
            .then_some(self.native_event)
            .flatten()
    }
}

/// Static adapter compatibility data.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct CompatibilityMatrix {
    /// Tuff hook spec version this matrix targets.
    pub spec_version: &'static str,
    /// Adapter id, such as `open-agents` or `claude`.
    pub adapter: &'static str,
    /// Matrix rows.
    pub events: &'static [CompatibilityEntry],
}

impl CompatibilityMatrix {
    /// Finds the compatibility row for a manifest event name or alias.
    pub fn find_event(&self, raw_event: &str) -> Option<&CompatibilityEntry> {
        self.events
            .iter()
            .find(|entry| entry.event.as_str() == raw_event)
            .or_else(|| {
                self.events
                    .iter()
                    .find(|entry| entry.aliases.contains(&raw_event))
            })
    }

    /// Returns supported native event names, each once, in matrix order.
    ///
    /// Two canonical events can render to the same native event (Cursor
    /// maps both `before_finish` and `stop` to `stop`), so the list is
    /// de-duplicated.
    pub fn supported_native_events(&self) -> Vec<&'static str> {
        let mut names: Vec<&'static str> = Vec::new();
        for name in self
            .events
            .iter()
            .filter_map(CompatibilityEntry::native_event_name)
        {
            if !names.contains(&name) {
                names.push(name);
            }
        }
        names
    }

    /// The event names a manifest may use for this adapter, for messages:
    /// each supported canonical event, then any alias its row accepts, then
    /// the native event it renders to when that is a different name.
    ///
    /// A refusal used to list only native names, which read as though a
    /// manifest could write them; a manifest names the canonical event,
    /// and a native name works only where the matrix lists it as an alias.
    pub fn accepted_events_summary(&self) -> String {
        let mut parts = Vec::new();
        for entry in self
            .events
            .iter()
            .filter(|entry| entry.coverage.is_supported())
        {
            let canonical = entry.event.as_str();
            let mut seen: Vec<&str> = vec![canonical];
            let mut notes: Vec<String> = Vec::new();
            for alias in entry.aliases {
                if !seen.contains(alias) {
                    seen.push(alias);
                    notes.push((*alias).to_string());
                }
            }
            if let Some(native) = entry.native_event
                && !seen.contains(&native)
            {
                notes.push(format!("renders as {native}"));
            }
            parts.push(if notes.is_empty() {
                canonical.to_string()
            } else {
                format!("{canonical} ({})", notes.join(", "))
            });
        }
        parts.join(", ")
    }
}

/// Common payload fields available to most Tuff-standard hooks.
pub const COMMON_PAYLOAD_FIELDS: &[PayloadField] = &[
    PayloadField {
        name: "session_id",
        value_type: PayloadValueType::String,
        required: false,
        description: "Harness session identifier, when available.",
    },
    PayloadField {
        name: "cwd",
        value_type: PayloadValueType::String,
        required: false,
        description: "Working directory for the hook invocation.",
    },
];

/// Current canonical event metadata.
pub const EVENT_SPECS: &[HookEventSpec] = &[
    HookEventSpec {
        event: HookEvent::SessionStart,
        canonical_name: "session_start",
        blocking: BlockingScope::NotBlocking,
        since_spec_version: FIRST_SPEC_VERSION,
        payload_schema: PayloadSchema {
            fields: COMMON_PAYLOAD_FIELDS,
        },
    },
    HookEventSpec {
        event: HookEvent::SessionEnd,
        canonical_name: "session_end",
        blocking: BlockingScope::NotBlocking,
        since_spec_version: FIRST_SPEC_VERSION,
        payload_schema: PayloadSchema {
            fields: COMMON_PAYLOAD_FIELDS,
        },
    },
    HookEventSpec {
        event: HookEvent::PreToolUse,
        canonical_name: "pre_tool_use",
        blocking: BlockingScope::BlocksAction,
        since_spec_version: FIRST_SPEC_VERSION,
        payload_schema: PayloadSchema {
            fields: COMMON_PAYLOAD_FIELDS,
        },
    },
    HookEventSpec {
        event: HookEvent::PostToolUse,
        canonical_name: "post_tool_use",
        blocking: BlockingScope::BlocksContinuation,
        since_spec_version: FIRST_SPEC_VERSION,
        payload_schema: PayloadSchema {
            fields: COMMON_PAYLOAD_FIELDS,
        },
    },
    HookEventSpec {
        event: HookEvent::BeforeFinish,
        canonical_name: "before_finish",
        blocking: BlockingScope::BlocksContinuation,
        since_spec_version: FIRST_SPEC_VERSION,
        payload_schema: PayloadSchema {
            fields: COMMON_PAYLOAD_FIELDS,
        },
    },
    HookEventSpec {
        event: HookEvent::AfterSave,
        canonical_name: "after_save",
        blocking: BlockingScope::NotBlocking,
        since_spec_version: FIRST_SPEC_VERSION,
        payload_schema: PayloadSchema {
            fields: COMMON_PAYLOAD_FIELDS,
        },
    },
    HookEventSpec {
        event: HookEvent::Stop,
        canonical_name: "stop",
        blocking: BlockingScope::BlocksContinuation,
        since_spec_version: FIRST_SPEC_VERSION,
        payload_schema: PayloadSchema {
            fields: COMMON_PAYLOAD_FIELDS,
        },
    },
];

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

    const ENTRY: CompatibilityEntry = CompatibilityEntry {
        event: HookEvent::PreToolUse,
        native_event: Some("PreToolUse"),
        aliases: &["pre_tool_execution"],
        coverage: CoverageLevel::Full,
        scope: &["Bash"],
        caveat: None,
        source: None,
        since_harness_version: None,
        until_harness_version: None,
    };

    #[test]
    fn supported_native_events_lists_each_name_once() {
        const EVENTS: &[CompatibilityEntry] = &[
            CompatibilityEntry {
                event: HookEvent::BeforeFinish,
                native_event: Some("stop"),
                aliases: &[],
                coverage: CoverageLevel::Partial,
                scope: &[],
                caveat: None,
                source: None,
                since_harness_version: None,
                until_harness_version: None,
            },
            CompatibilityEntry {
                event: HookEvent::Stop,
                native_event: Some("stop"),
                aliases: &[],
                coverage: CoverageLevel::Full,
                scope: &[],
                caveat: None,
                source: None,
                since_harness_version: None,
                until_harness_version: None,
            },
        ];
        let matrix = CompatibilityMatrix {
            spec_version: SPEC_VERSION,
            adapter: "test",
            events: EVENTS,
        };
        assert_eq!(matrix.supported_native_events(), vec!["stop"]);
    }

    #[test]
    fn accepted_events_summary_leads_with_the_names_a_manifest_can_write() {
        const EVENTS: &[CompatibilityEntry] = &[
            CompatibilityEntry {
                event: HookEvent::PreToolUse,
                native_event: Some("preToolUse"),
                aliases: &[],
                coverage: CoverageLevel::Full,
                scope: &[],
                caveat: None,
                source: None,
                since_harness_version: None,
                until_harness_version: None,
            },
            CompatibilityEntry {
                event: HookEvent::PostToolUse,
                native_event: Some("PostToolUse"),
                aliases: &["PostToolUse"],
                coverage: CoverageLevel::Full,
                scope: &[],
                caveat: None,
                source: None,
                since_harness_version: None,
                until_harness_version: None,
            },
            CompatibilityEntry {
                event: HookEvent::Stop,
                native_event: Some("stop"),
                aliases: &[],
                coverage: CoverageLevel::Full,
                scope: &[],
                caveat: None,
                source: None,
                since_harness_version: None,
                until_harness_version: None,
            },
            CompatibilityEntry {
                event: HookEvent::AfterSave,
                native_event: None,
                aliases: &["FileChanged"],
                coverage: CoverageLevel::Unsupported,
                scope: &[],
                caveat: None,
                source: None,
                since_harness_version: None,
                until_harness_version: None,
            },
        ];
        let matrix = CompatibilityMatrix {
            spec_version: SPEC_VERSION,
            adapter: "test",
            events: EVENTS,
        };
        assert_eq!(
            matrix.accepted_events_summary(),
            "pre_tool_use (renders as preToolUse), post_tool_use (PostToolUse), stop"
        );
    }

    #[test]
    fn hook_event_display_uses_canonical_name() {
        assert_eq!(HookEvent::PreToolUse.to_string(), "pre_tool_use");
    }

    #[test]
    fn compatibility_entry_matches_canonical_name_and_alias() {
        assert!(ENTRY.matches_name("pre_tool_use"));
        assert!(ENTRY.matches_name("pre_tool_execution"));
        assert!(!ENTRY.matches_name("before_finish"));
    }

    #[test]
    fn unsupported_entries_have_no_native_event_name() {
        let entry = CompatibilityEntry {
            coverage: CoverageLevel::Unsupported,
            ..ENTRY
        };

        assert_eq!(entry.native_event_name(), None);
    }

    #[test]
    fn canonical_name_takes_precedence_over_an_earlier_alias() {
        const EVENTS: &[CompatibilityEntry] = &[
            CompatibilityEntry {
                event: HookEvent::BeforeFinish,
                native_event: Some("stop"),
                aliases: &["stop"],
                coverage: CoverageLevel::Partial,
                scope: &[],
                caveat: None,
                source: None,
                since_harness_version: None,
                until_harness_version: None,
            },
            CompatibilityEntry {
                event: HookEvent::Stop,
                native_event: Some("stop"),
                aliases: &[],
                coverage: CoverageLevel::Full,
                scope: &[],
                caveat: None,
                source: None,
                since_harness_version: None,
                until_harness_version: None,
            },
        ];
        let matrix = CompatibilityMatrix {
            spec_version: SPEC_VERSION,
            adapter: "test",
            events: EVENTS,
        };

        let matched = matrix.find_event("stop").expect("stop event");
        assert_eq!(matched.event, HookEvent::Stop);
        assert_eq!(matched.coverage, CoverageLevel::Full);
    }

    #[test]
    fn aliases_remain_available_when_no_canonical_name_matches() {
        const EVENTS: &[CompatibilityEntry] = &[CompatibilityEntry {
            event: HookEvent::PreToolUse,
            native_event: Some("PreToolUse"),
            aliases: &["BeforeTool"],
            coverage: CoverageLevel::Full,
            scope: &[],
            caveat: None,
            source: None,
            since_harness_version: None,
            until_harness_version: None,
        }];
        let matrix = CompatibilityMatrix {
            spec_version: SPEC_VERSION,
            adapter: "test",
            events: EVENTS,
        };

        assert_eq!(
            matrix.find_event("BeforeTool").map(|entry| entry.event),
            Some(HookEvent::PreToolUse)
        );
    }
}