ironclaw 0.5.0

Secure personal AI assistant that protects your data and expands its capabilities on the fly
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
//! Hook registry for managing and executing lifecycle hooks.

use std::sync::Arc;

use tokio::sync::RwLock;

use crate::hooks::hook::{Hook, HookContext, HookError, HookEvent, HookFailureMode, HookOutcome};

/// A registered hook with its priority.
struct HookEntry {
    hook: Arc<dyn Hook>,
    priority: u32,
}

/// Registry that manages hooks and executes them at lifecycle points.
///
/// Hooks are executed in priority order (lower number = higher priority).
/// A `Reject` outcome stops the chain immediately.
/// A `Modify` outcome chains through subsequent hooks.
pub struct HookRegistry {
    hooks: RwLock<Vec<HookEntry>>,
}

impl HookRegistry {
    /// Create an empty registry.
    pub fn new() -> Self {
        Self {
            hooks: RwLock::new(Vec::new()),
        }
    }

    /// Register a hook with default priority (100).
    pub async fn register(&self, hook: Arc<dyn Hook>) {
        self.register_with_priority(hook, 100).await;
    }

    /// Register a hook with a specific priority.
    ///
    /// Lower priority number = runs first.
    pub async fn register_with_priority(&self, hook: Arc<dyn Hook>, priority: u32) {
        let mut hooks = self.hooks.write().await;
        hooks.push(HookEntry { hook, priority });
        hooks.sort_by_key(|e| e.priority);
    }

    /// Unregister a hook by name. Returns `true` if it was found and removed.
    pub async fn unregister(&self, name: &str) -> bool {
        let mut hooks = self.hooks.write().await;
        let before = hooks.len();
        hooks.retain(|e| e.hook.name() != name);
        hooks.len() < before
    }

    /// List all registered hook names (in priority order).
    pub async fn list(&self) -> Vec<String> {
        let hooks = self.hooks.read().await;
        hooks.iter().map(|e| e.hook.name().to_string()).collect()
    }

    /// Run all hooks matching the event's hook point.
    ///
    /// - Hooks run in priority order (lowest first).
    /// - `Reject` stops the chain immediately.
    /// - `Modify` chains the modification through subsequent hooks.
    /// - Timeout/error handling respects each hook's `failure_mode`.
    pub async fn run(&self, event: &HookEvent) -> Result<HookOutcome, HookError> {
        let point = event.hook_point();
        let ctx = HookContext::default();

        // Clone matching hooks and drop the read guard before executing.
        // Each hook can run up to its timeout, so holding the guard would
        // block concurrent register/unregister/run calls.
        let matching: Vec<Arc<dyn Hook>> = {
            let hooks = self.hooks.read().await;
            hooks
                .iter()
                .filter(|e| e.hook.hook_points().contains(&point))
                .map(|e| e.hook.clone())
                .collect()
        };

        if matching.is_empty() {
            return Ok(HookOutcome::ok());
        }

        let mut current_event = event.clone();

        for hook in &matching {
            let timeout = hook.timeout();

            let result = tokio::time::timeout(timeout, hook.execute(&current_event, &ctx)).await;

            match result {
                Ok(Ok(HookOutcome::Reject { reason })) => {
                    tracing::debug!(hook = hook.name(), "Hook rejected: {}", reason);
                    return Err(HookError::Rejected { reason });
                }
                Ok(Ok(HookOutcome::Continue {
                    modified: Some(value),
                })) => {
                    tracing::debug!(hook = hook.name(), "Hook modified content");
                    current_event.apply_modification(&value);
                }
                Ok(Ok(HookOutcome::Continue { modified: None })) => {
                    // No-op, continue chain
                }
                Ok(Err(err)) => match hook.failure_mode() {
                    HookFailureMode::FailOpen => {
                        tracing::warn!(hook = hook.name(), "Hook failed (fail-open): {}", err);
                    }
                    HookFailureMode::FailClosed => {
                        tracing::warn!(hook = hook.name(), "Hook failed (fail-closed): {}", err);
                        return Err(HookError::ExecutionFailed {
                            reason: format!("Hook '{}' failed: {}", hook.name(), err),
                        });
                    }
                },
                Err(_elapsed) => match hook.failure_mode() {
                    HookFailureMode::FailOpen => {
                        tracing::warn!(
                            hook = hook.name(),
                            "Hook timed out (fail-open) after {:?}",
                            timeout
                        );
                    }
                    HookFailureMode::FailClosed => {
                        tracing::warn!(
                            hook = hook.name(),
                            "Hook timed out (fail-closed) after {:?}",
                            timeout
                        );
                        return Err(HookError::Timeout { timeout });
                    }
                },
            }
        }

        // Determine final outcome by comparing with original event
        let modified = extract_content(&current_event);
        let original = extract_content(event);

        if modified != original {
            Ok(HookOutcome::modify(modified))
        } else {
            Ok(HookOutcome::ok())
        }
    }
}

impl Default for HookRegistry {
    fn default() -> Self {
        Self::new()
    }
}

/// Extract the primary content string from a hook event.
fn extract_content(event: &HookEvent) -> String {
    match event {
        HookEvent::Inbound { content, .. } | HookEvent::Outbound { content, .. } => content.clone(),
        HookEvent::ToolCall { parameters, .. } => {
            serde_json::to_string(parameters).unwrap_or_default()
        }
        HookEvent::ResponseTransform { response, .. } => response.clone(),
        HookEvent::SessionStart { session_id, .. } | HookEvent::SessionEnd { session_id, .. } => {
            session_id.clone()
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::hooks::hook::{HookFailureMode, HookPoint};
    use async_trait::async_trait;
    use std::time::Duration;

    /// A test hook that always returns ok.
    struct PassthroughHook {
        name: String,
        points: Vec<HookPoint>,
    }

    #[async_trait]
    impl Hook for PassthroughHook {
        fn name(&self) -> &str {
            &self.name
        }
        fn hook_points(&self) -> &[HookPoint] {
            &self.points
        }
        async fn execute(
            &self,
            _event: &HookEvent,
            _ctx: &HookContext,
        ) -> Result<HookOutcome, HookError> {
            Ok(HookOutcome::ok())
        }
    }

    /// A hook that modifies content by appending a suffix.
    struct ModifyHook {
        name: String,
        suffix: String,
        points: Vec<HookPoint>,
    }

    #[async_trait]
    impl Hook for ModifyHook {
        fn name(&self) -> &str {
            &self.name
        }
        fn hook_points(&self) -> &[HookPoint] {
            &self.points
        }
        async fn execute(
            &self,
            event: &HookEvent,
            _ctx: &HookContext,
        ) -> Result<HookOutcome, HookError> {
            let content = extract_content(event);
            Ok(HookOutcome::modify(format!("{}{}", content, self.suffix)))
        }
    }

    /// A hook that always rejects.
    struct RejectHook {
        name: String,
        reason: String,
        points: Vec<HookPoint>,
    }

    #[async_trait]
    impl Hook for RejectHook {
        fn name(&self) -> &str {
            &self.name
        }
        fn hook_points(&self) -> &[HookPoint] {
            &self.points
        }
        async fn execute(
            &self,
            _event: &HookEvent,
            _ctx: &HookContext,
        ) -> Result<HookOutcome, HookError> {
            Ok(HookOutcome::reject(&self.reason))
        }
    }

    /// A hook that always errors.
    struct ErrorHook {
        name: String,
        points: Vec<HookPoint>,
        failure_mode: HookFailureMode,
    }

    #[async_trait]
    impl Hook for ErrorHook {
        fn name(&self) -> &str {
            &self.name
        }
        fn hook_points(&self) -> &[HookPoint] {
            &self.points
        }
        fn failure_mode(&self) -> HookFailureMode {
            self.failure_mode
        }
        async fn execute(
            &self,
            _event: &HookEvent,
            _ctx: &HookContext,
        ) -> Result<HookOutcome, HookError> {
            Err(HookError::ExecutionFailed {
                reason: "test error".into(),
            })
        }
    }

    /// A hook that sleeps longer than its timeout.
    struct SlowHook {
        name: String,
        points: Vec<HookPoint>,
        failure_mode: HookFailureMode,
    }

    #[async_trait]
    impl Hook for SlowHook {
        fn name(&self) -> &str {
            &self.name
        }
        fn hook_points(&self) -> &[HookPoint] {
            &self.points
        }
        fn failure_mode(&self) -> HookFailureMode {
            self.failure_mode
        }
        fn timeout(&self) -> Duration {
            Duration::from_millis(50)
        }
        async fn execute(
            &self,
            _event: &HookEvent,
            _ctx: &HookContext,
        ) -> Result<HookOutcome, HookError> {
            tokio::time::sleep(Duration::from_millis(200)).await;
            Ok(HookOutcome::ok())
        }
    }

    fn test_event() -> HookEvent {
        HookEvent::Inbound {
            user_id: "user-1".into(),
            channel: "test".into(),
            content: "hello".into(),
            thread_id: None,
        }
    }

    #[tokio::test]
    async fn test_empty_registry_returns_ok() {
        let registry = HookRegistry::new();
        let result = registry.run(&test_event()).await;
        assert!(result.is_ok());
        assert!(matches!(
            result.unwrap(),
            HookOutcome::Continue { modified: None }
        ));
    }

    #[tokio::test]
    async fn test_register_and_list() {
        let registry = HookRegistry::new();
        registry
            .register(Arc::new(PassthroughHook {
                name: "hook-a".into(),
                points: vec![HookPoint::BeforeInbound],
            }))
            .await;
        registry
            .register(Arc::new(PassthroughHook {
                name: "hook-b".into(),
                points: vec![HookPoint::BeforeInbound],
            }))
            .await;

        let names = registry.list().await;
        assert_eq!(names, vec!["hook-a", "hook-b"]);
    }

    #[tokio::test]
    async fn test_priority_ordering() {
        let registry = HookRegistry::new();

        // Register in reverse priority order
        registry
            .register_with_priority(
                Arc::new(ModifyHook {
                    name: "low-prio".into(),
                    suffix: "-LOW".into(),
                    points: vec![HookPoint::BeforeInbound],
                }),
                200,
            )
            .await;
        registry
            .register_with_priority(
                Arc::new(ModifyHook {
                    name: "high-prio".into(),
                    suffix: "-HIGH".into(),
                    points: vec![HookPoint::BeforeInbound],
                }),
                10,
            )
            .await;

        // Should run in priority order: high-prio first, then low-prio
        let names = registry.list().await;
        assert_eq!(names[0], "high-prio");
        assert_eq!(names[1], "low-prio");

        let result = registry.run(&test_event()).await.unwrap();
        match result {
            HookOutcome::Continue { modified: Some(m) } => {
                // "hello" -> "hello-HIGH" -> "hello-HIGH-LOW"
                assert_eq!(m, "hello-HIGH-LOW");
            }
            other => panic!("Expected modification chain, got: {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_reject_stops_chain() {
        let registry = HookRegistry::new();

        registry
            .register_with_priority(
                Arc::new(RejectHook {
                    name: "blocker".into(),
                    reason: "blocked".into(),
                    points: vec![HookPoint::BeforeInbound],
                }),
                10,
            )
            .await;
        registry
            .register_with_priority(
                Arc::new(ModifyHook {
                    name: "modifier".into(),
                    suffix: "-MODIFIED".into(),
                    points: vec![HookPoint::BeforeInbound],
                }),
                20,
            )
            .await;

        let result = registry.run(&test_event()).await;
        assert!(result.is_err());
        match result.unwrap_err() {
            HookError::Rejected { reason } => assert_eq!(reason, "blocked"),
            other => panic!("Expected Rejected, got: {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_modification_chaining() {
        let registry = HookRegistry::new();

        registry
            .register_with_priority(
                Arc::new(ModifyHook {
                    name: "first".into(),
                    suffix: "-A".into(),
                    points: vec![HookPoint::BeforeInbound],
                }),
                10,
            )
            .await;
        registry
            .register_with_priority(
                Arc::new(ModifyHook {
                    name: "second".into(),
                    suffix: "-B".into(),
                    points: vec![HookPoint::BeforeInbound],
                }),
                20,
            )
            .await;

        let result = registry.run(&test_event()).await.unwrap();
        match result {
            HookOutcome::Continue { modified: Some(m) } => {
                assert_eq!(m, "hello-A-B");
            }
            other => panic!("Expected chained modification, got: {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_fail_open_on_error() {
        let registry = HookRegistry::new();
        registry
            .register(Arc::new(ErrorHook {
                name: "err-open".into(),
                points: vec![HookPoint::BeforeInbound],
                failure_mode: HookFailureMode::FailOpen,
            }))
            .await;

        let result = registry.run(&test_event()).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_fail_closed_on_error() {
        let registry = HookRegistry::new();
        registry
            .register(Arc::new(ErrorHook {
                name: "err-closed".into(),
                points: vec![HookPoint::BeforeInbound],
                failure_mode: HookFailureMode::FailClosed,
            }))
            .await;

        let result = registry.run(&test_event()).await;
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            HookError::ExecutionFailed { .. }
        ));
    }

    #[tokio::test]
    async fn test_fail_open_on_timeout() {
        let registry = HookRegistry::new();
        registry
            .register(Arc::new(SlowHook {
                name: "slow-open".into(),
                points: vec![HookPoint::BeforeInbound],
                failure_mode: HookFailureMode::FailOpen,
            }))
            .await;

        let result = registry.run(&test_event()).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_fail_closed_on_timeout() {
        let registry = HookRegistry::new();
        registry
            .register(Arc::new(SlowHook {
                name: "slow-closed".into(),
                points: vec![HookPoint::BeforeInbound],
                failure_mode: HookFailureMode::FailClosed,
            }))
            .await;

        let result = registry.run(&test_event()).await;
        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), HookError::Timeout { .. }));
    }

    #[tokio::test]
    async fn test_unregister() {
        let registry = HookRegistry::new();
        registry
            .register(Arc::new(PassthroughHook {
                name: "removable".into(),
                points: vec![HookPoint::BeforeInbound],
            }))
            .await;

        assert_eq!(registry.list().await.len(), 1);
        assert!(registry.unregister("removable").await);
        assert_eq!(registry.list().await.len(), 0);

        // Unregistering non-existent returns false
        assert!(!registry.unregister("nonexistent").await);
    }

    #[tokio::test]
    async fn test_hooks_only_match_their_points() {
        let registry = HookRegistry::new();
        registry
            .register(Arc::new(RejectHook {
                name: "outbound-only".into(),
                reason: "blocked".into(),
                points: vec![HookPoint::BeforeOutbound],
            }))
            .await;

        // Inbound event should not be affected by outbound-only hook
        let result = registry.run(&test_event()).await;
        assert!(result.is_ok());
    }
}