ironclaw 0.24.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
//! Hooks management CLI commands.
//!
//! Lists all discoverable lifecycle hooks from bundled and plugin (WASM
//! capabilities) sources. Plugin discovery uses the same flat-file sidecar
//! layout as the WASM tool/channel loaders (`foo.wasm` + `foo.capabilities.json`).
//!
//! Workspace hooks (`hooks/hooks.json`, `hooks/*.hook.json`) are stored in the
//! database-backed Workspace and require a DB connection to enumerate; this
//! command does not connect to the database, so workspace hooks are omitted.

use std::path::Path;

use clap::Subcommand;

use crate::hooks::bundled::{HookBundleConfig, HookRuleConfig, OutboundWebhookConfig};
use crate::hooks::hook::HookPoint;

const BUNDLED_AUDIT_PRIORITY: u32 = 25;
const DEFAULT_RULE_PRIORITY: u32 = 100;
const DEFAULT_WEBHOOK_PRIORITY: u32 = 300;

#[derive(Subcommand, Debug, Clone)]
pub enum HooksCommand {
    /// List discoverable hooks (bundled + plugin; not filtered by active extensions)
    List {
        /// Show detailed information (hook points, priority, failure mode)
        #[arg(short, long)]
        verbose: bool,

        /// Output as JSON
        #[arg(long)]
        json: bool,
    },
}

/// Run the hooks CLI subcommand.
pub async fn run_hooks_command(
    cmd: HooksCommand,
    config_path: Option<&Path>,
) -> anyhow::Result<()> {
    let config = crate::config::Config::from_env_with_toml(config_path)
        .await
        .map_err(|e| anyhow::anyhow!("{e:#}"))?;

    match cmd {
        HooksCommand::List { verbose, json } => cmd_list(&config, verbose, json).await,
    }
}

/// Discovered hook information for CLI display.
struct HookInfo {
    name: String,
    source: String,
    kind: String,
    points: Vec<HookPoint>,
    priority: u32,
    failure_mode: String,
}

/// Collect all discoverable hooks from bundled and plugin sources.
async fn discover_hooks(config: &crate::config::Config) -> Vec<HookInfo> {
    let mut hooks = Vec::new();

    // 1. Bundled hooks (hardcoded)
    hooks.push(HookInfo {
        name: "builtin.audit_log".to_string(),
        source: "bundled".to_string(),
        kind: "audit".to_string(),
        points: vec![
            HookPoint::BeforeInbound,
            HookPoint::BeforeToolCall,
            HookPoint::BeforeOutbound,
            HookPoint::OnSessionStart,
            HookPoint::OnSessionEnd,
            HookPoint::TransformResponse,
        ],
        priority: BUNDLED_AUDIT_PRIORITY,
        failure_mode: "fail_open".to_string(),
    });

    // 2. Plugin hooks from WASM capabilities sidecar files
    let wasm_tools_dir = &config.wasm.tools_dir;
    let wasm_channels_dir = &config.channels.wasm_channels_dir;

    collect_plugin_hooks(&mut hooks, wasm_tools_dir, "tool").await;
    collect_plugin_hooks(&mut hooks, wasm_channels_dir, "channel").await;

    // Note: workspace hooks (hooks/hooks.json, hooks/*.hook.json) are stored
    // in the database-backed Workspace and require a DB connection to list.

    // Sort by priority then name for stable output
    hooks.sort_by(|a, b| a.priority.cmp(&b.priority).then(a.name.cmp(&b.name)));

    hooks
}

/// Scan a WASM directory for `*.capabilities.json` sidecar files containing hook
/// definitions.
///
/// Uses the same flat-file layout as the real WASM loaders:
/// ```text
/// ~/.ironclaw/tools/
/// ├── slack.wasm
/// ├── slack.capabilities.json   <- hooks section parsed here
/// ├── github.wasm
/// └── github.capabilities.json
/// ```
async fn collect_plugin_hooks(hooks: &mut Vec<HookInfo>, dir: &Path, plugin_type: &str) {
    if !dir.exists() {
        return;
    }

    let mut entries = match tokio::fs::read_dir(dir).await {
        Ok(entries) => entries,
        Err(_) => return,
    };

    while let Ok(Some(entry)) = entries.next_entry().await {
        let path = entry.path();

        // Match only *.capabilities.json sidecar files (flat layout)
        let file_name = match path.file_name().and_then(|n| n.to_str()) {
            Some(n) => n.to_string(),
            None => continue,
        };

        if !file_name.ends_with(".capabilities.json") {
            continue;
        }

        // Extract tool/channel name: "slack.capabilities.json" -> "slack"
        let name = match file_name.strip_suffix(".capabilities.json") {
            Some(n) if !n.is_empty() => n.to_string(),
            _ => continue,
        };

        let bytes = match tokio::fs::read(&path).await {
            Ok(b) => b,
            Err(_) => continue,
        };

        let value: serde_json::Value = match serde_json::from_slice(&bytes) {
            Ok(v) => v,
            Err(_) => continue,
        };

        // Match the same extraction logic as bootstrap: check "hooks" key
        // at root or nested under "capabilities.hooks".
        let hooks_section = value
            .get("hooks")
            .or_else(|| value.get("capabilities").and_then(|c| c.get("hooks")));

        let Some(hooks_value) = hooks_section else {
            continue;
        };

        let bundle = match HookBundleConfig::from_value(hooks_value) {
            Ok(b) => b,
            Err(_) => continue,
        };

        let source = format!("plugin.{plugin_type}:{name}");

        for rule in &bundle.rules {
            hooks.push(hook_info_from_rule(&source, rule));
        }
        for webhook in &bundle.outbound_webhooks {
            hooks.push(hook_info_from_webhook(&source, webhook));
        }
    }
}

fn hook_info_from_rule(source: &str, rule: &HookRuleConfig) -> HookInfo {
    let scoped_name = format!("{source}::{}", rule.name);
    HookInfo {
        name: scoped_name,
        source: source.to_string(),
        kind: if rule.reject_reason.is_some() {
            "reject".to_string()
        } else {
            "rule".to_string()
        },
        points: rule.points.clone(),
        priority: rule.priority.unwrap_or(DEFAULT_RULE_PRIORITY),
        failure_mode: rule
            .failure_mode
            .as_ref()
            .map(|m| format!("{m:?}"))
            .unwrap_or_else(|| "fail_open".to_string()),
    }
}

fn hook_info_from_webhook(source: &str, webhook: &OutboundWebhookConfig) -> HookInfo {
    let scoped_name = format!("{source}::{}", webhook.name);
    HookInfo {
        name: scoped_name,
        source: source.to_string(),
        kind: "webhook".to_string(),
        points: webhook.points.clone(),
        priority: webhook.priority.unwrap_or(DEFAULT_WEBHOOK_PRIORITY),
        failure_mode: "fail_open".to_string(),
    }
}

/// List all discovered hooks.
async fn cmd_list(config: &crate::config::Config, verbose: bool, json: bool) -> anyhow::Result<()> {
    let hooks = discover_hooks(config).await;

    if json {
        let entries: Vec<serde_json::Value> = hooks
            .iter()
            .map(|h| {
                let mut v = serde_json::json!({
                    "name": h.name,
                    "source": h.source,
                    "kind": h.kind,
                    "priority": h.priority,
                    "points": h.points.iter().map(|p| p.as_str()).collect::<Vec<_>>(),
                });
                if verbose {
                    v["failure_mode"] = serde_json::json!(h.failure_mode);
                }
                v
            })
            .collect();
        println!(
            "{}",
            serde_json::to_string_pretty(&entries).unwrap_or_else(|_| "[]".to_string())
        );
        return Ok(());
    }

    if hooks.is_empty() {
        println!("No hooks found.");
        return Ok(());
    }

    println!("Discovered {} hook(s):\n", hooks.len());

    for h in &hooks {
        if verbose {
            let points_str: Vec<&str> = h.points.iter().map(|p| p.as_str()).collect();
            println!("  {}", h.name);
            println!("    Source:       {}", h.source);
            println!("    Kind:         {}", h.kind);
            println!("    Priority:     {}", h.priority);
            println!("    Points:       {}", points_str.join(", "));
            println!("    Failure mode: {}", h.failure_mode);
            println!();
        } else {
            let points_str: Vec<&str> = h.points.iter().map(|p| p.as_str()).collect();
            println!(
                "  {:<40} [{:<7}] pri={:<3} {}",
                h.name,
                h.kind,
                h.priority,
                points_str.join(", ")
            );
        }
    }

    if !verbose {
        println!();
        println!(
            "Use --verbose for details. Workspace hooks (DB-stored) are not listed without a database connection."
        );
    }

    Ok(())
}

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

    #[test]
    fn hook_info_from_rule_basic() {
        let rule = HookRuleConfig {
            name: "test-rule".to_string(),
            points: vec![HookPoint::BeforeInbound],
            priority: Some(50),
            failure_mode: None,
            timeout_ms: None,
            when_regex: None,
            reject_reason: None,
            replacements: vec![],
            prepend: None,
            append: None,
        };

        let info = hook_info_from_rule("plugin.tool:my_tool", &rule);
        assert_eq!(info.name, "plugin.tool:my_tool::test-rule");
        assert_eq!(info.source, "plugin.tool:my_tool");
        assert_eq!(info.kind, "rule");
        assert_eq!(info.priority, 50);
    }

    #[test]
    fn hook_info_from_rule_reject() {
        let rule = HookRuleConfig {
            name: "blocker".to_string(),
            points: vec![HookPoint::BeforeInbound, HookPoint::BeforeToolCall],
            priority: None,
            failure_mode: None,
            timeout_ms: None,
            when_regex: Some("bad_pattern".to_string()),
            reject_reason: Some("blocked".to_string()),
            replacements: vec![],
            prepend: None,
            append: None,
        };

        let info = hook_info_from_rule("workspace:hooks/block.hook.json", &rule);
        assert_eq!(info.kind, "reject");
        assert_eq!(info.priority, DEFAULT_RULE_PRIORITY);
    }

    #[test]
    fn hook_info_from_webhook_basic() {
        let webhook = OutboundWebhookConfig {
            name: "notify".to_string(),
            points: vec![HookPoint::BeforeOutbound],
            url: "https://example.com/hook".to_string(),
            headers: Default::default(),
            timeout_ms: None,
            priority: Some(200),
            max_in_flight: None,
        };

        let info = hook_info_from_webhook("plugin.tool:logger", &webhook);
        assert_eq!(info.name, "plugin.tool:logger::notify");
        assert_eq!(info.kind, "webhook");
        assert_eq!(info.priority, 200);
    }

    #[tokio::test]
    async fn discover_plugin_hooks_flat_layout() {
        let dir = tempfile::tempdir().expect("create temp dir");

        // Create a sidecar capabilities file with hooks (flat layout)
        let caps = serde_json::json!({
            "hooks": {
                "rules": [
                    {
                        "name": "redact-keys",
                        "points": ["beforeOutbound"],
                        "replacements": [
                            {"pattern": "sk-[a-zA-Z0-9]+", "replacement": "[REDACTED]"}
                        ]
                    }
                ],
                "outbound_webhooks": [
                    {
                        "name": "log-events",
                        "points": ["beforeInbound"],
                        "url": "https://example.com/events"
                    }
                ]
            }
        });
        let mut f =
            std::fs::File::create(dir.path().join("slack.capabilities.json")).expect("create file");
        f.write_all(serde_json::to_string(&caps).unwrap().as_bytes())
            .expect("write");

        // Also create a .wasm file (not required for discovery, but realistic)
        std::fs::File::create(dir.path().join("slack.wasm")).expect("create wasm");

        // A capabilities file without hooks should be skipped
        let no_hooks = serde_json::json!({"http": {"allowlist": []}});
        let mut f2 = std::fs::File::create(dir.path().join("github.capabilities.json"))
            .expect("create file");
        f2.write_all(serde_json::to_string(&no_hooks).unwrap().as_bytes())
            .expect("write");

        let mut hooks = Vec::new();
        collect_plugin_hooks(&mut hooks, dir.path(), "tool").await;

        assert_eq!(hooks.len(), 2, "should find 1 rule + 1 webhook");
        assert_eq!(hooks[0].name, "plugin.tool:slack::redact-keys");
        assert_eq!(hooks[0].kind, "rule");
        assert_eq!(hooks[1].name, "plugin.tool:slack::log-events");
        assert_eq!(hooks[1].kind, "webhook");
    }

    #[tokio::test]
    async fn discover_plugin_hooks_nested_capabilities() {
        let dir = tempfile::tempdir().expect("create temp dir");

        // Channel-style capabilities with hooks nested under "capabilities"
        let caps = serde_json::json!({
            "type": "channel",
            "capabilities": {
                "hooks": {
                    "rules": [
                        {
                            "name": "filter-spam",
                            "points": ["beforeInbound"],
                            "when_regex": "buy now",
                            "reject_reason": "spam detected"
                        }
                    ]
                }
            }
        });
        let mut f = std::fs::File::create(dir.path().join("telegram.capabilities.json"))
            .expect("create file");
        f.write_all(serde_json::to_string(&caps).unwrap().as_bytes())
            .expect("write");

        let mut hooks = Vec::new();
        collect_plugin_hooks(&mut hooks, dir.path(), "channel").await;

        assert_eq!(hooks.len(), 1);
        assert_eq!(hooks[0].name, "plugin.channel:telegram::filter-spam");
        assert_eq!(hooks[0].kind, "reject");
        assert_eq!(hooks[0].source, "plugin.channel:telegram");
    }

    #[tokio::test]
    async fn discover_plugin_hooks_empty_dir() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let mut hooks = Vec::new();
        collect_plugin_hooks(&mut hooks, dir.path(), "tool").await;
        assert!(hooks.is_empty());
    }

    #[tokio::test]
    async fn discover_plugin_hooks_nonexistent_dir() {
        let mut hooks = Vec::new();
        collect_plugin_hooks(&mut hooks, Path::new("/nonexistent/path"), "tool").await;
        assert!(hooks.is_empty());
    }

    #[tokio::test]
    async fn discover_plugin_hooks_skips_subdirectories() {
        let dir = tempfile::tempdir().expect("create temp dir");

        // Create a subdirectory with capabilities.json inside (old broken layout)
        // This should NOT be discovered — only flat sidecar files are valid.
        let sub = dir.path().join("my_tool");
        std::fs::create_dir_all(&sub).expect("create subdir");
        let caps =
            serde_json::json!({"hooks": {"rules": [{"name": "x", "points": ["beforeInbound"]}]}});
        let mut f = std::fs::File::create(sub.join("capabilities.json")).expect("create file");
        f.write_all(serde_json::to_string(&caps).unwrap().as_bytes())
            .expect("write");

        let mut hooks = Vec::new();
        collect_plugin_hooks(&mut hooks, dir.path(), "tool").await;

        // The subdirectory layout should be ignored
        assert!(
            hooks.is_empty(),
            "subdirectory capabilities.json should not be discovered"
        );
    }
}