collet 0.1.0

Relentless agentic coding orchestrator with zero-drop agent loops
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
#![allow(dead_code)]
//! Hook runtime — parse and execute plugin lifecycle hooks.
//!
//! Supports both collet-native and Claude Code–compatible hook formats.
//!
//! # Supported events
//!
//! | Event | Timing | Use case |
//! |-------|--------|----------|
//! | `SessionStart` | Agent session starts | Initialization, context injection |
//! | `PreToolUse` | Before tool execution | Guard, block dangerous commands |
//! | `PostToolUse` | After tool execution | Observation, logging, post-processing |
//! | `PreCompact` | Before context compaction | Preserve important data |
//! | `Stop` | Agent loop ending (before final response) | Notifications, final validation |
//! | `SessionEnd` | Session teardown | Cleanup, report generation |
//! | `SubagentStart` | Subagent spawned | Monitoring, tracking |
//! | `SubagentStop` | Subagent completed | Result collection, aggregation |
//!
//! # Matcher syntax
//!
//! - `"*"` — match all tools
//! - `"Bash"` — match a specific tool name
//! - `"file_edit|file_write"` — pipe-separated OR matching
//!
//! ```json
//! {
//!   "hooks": {
//!     "SessionStart": [{ "matcher": "*", "hooks": [{ "type": "command", "command": "..." }] }],
//!     "PreToolUse":   [{ "matcher": "Bash", "hooks": [...] }],
//!     "PostToolUse":  [{ "matcher": "file_edit|file_write|git_patch", "hooks": [...] }],
//!     "PreCompact":   [{ "matcher": "*", "hooks": [...] }],
//!     "Stop":         [{ "matcher": "*", "hooks": [...] }],
//!     "SessionEnd":   [{ "matcher": "*", "hooks": [...] }],
//!     "SubagentStart":[{ "matcher": "*", "hooks": [...] }],
//!     "SubagentStop": [{ "matcher": "*", "hooks": [...] }]
//!   }
//! }
//! ```

use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::time::Duration;

use anyhow::{Context, Result};

/// Lifecycle events that hooks can attach to.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum HookEvent {
    SessionStart,
    PreToolUse,
    PostToolUse,
    PreCompact,
    Stop,
    SessionEnd,
    SubagentStart,
    SubagentStop,
}

impl HookEvent {
    /// All hook events in order.
    #[allow(dead_code)]
    pub fn all() -> &'static [HookEvent] {
        &[
            HookEvent::SessionStart,
            HookEvent::PreToolUse,
            HookEvent::PostToolUse,
            HookEvent::PreCompact,
            HookEvent::Stop,
            HookEvent::SessionEnd,
            HookEvent::SubagentStart,
            HookEvent::SubagentStop,
        ]
    }

    /// Parse from the JSON key name.
    pub fn from_str_name(s: &str) -> Option<Self> {
        match s {
            "SessionStart" => Some(HookEvent::SessionStart),
            "PreToolUse" => Some(HookEvent::PreToolUse),
            "PostToolUse" => Some(HookEvent::PostToolUse),
            "PreCompact" => Some(HookEvent::PreCompact),
            "Stop" => Some(HookEvent::Stop),
            "SessionEnd" => Some(HookEvent::SessionEnd),
            "SubagentStart" => Some(HookEvent::SubagentStart),
            "SubagentStop" => Some(HookEvent::SubagentStop),
            _ => None,
        }
    }
}

/// A parsed `hooks.json` file.
#[derive(Debug, Clone)]
pub struct HookConfig {
    /// Raw JSON for lazy parsing.
    raw: serde_json::Value,
}

/// A single hook registration (one entry in the `hooks` array).
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub struct RegisteredHook {
    /// Which event triggers this hook.
    pub event: HookEvent,
    /// Tool name matcher ("*" = all tools, "Bash" = only Bash tool, etc.)
    pub matcher: String,
    /// The command to execute.
    pub command: String,
    /// Description for logging.
    pub description: Option<String>,
    /// Whether to run asynchronously (don't block the agent loop).
    pub is_async: bool,
    /// Timeout in seconds.
    pub timeout_secs: Option<u64>,
    /// The plugin root directory (for ${CLAUDE_PLUGIN_ROOT} substitution).
    pub plugin_root: PathBuf,
}

/// Runtime that holds all hooks from all plugins, grouped by event.
#[derive(Debug, Clone, Default)]
pub struct HookRuntime {
    /// event → list of registered hooks.
    hooks: HashMap<HookEvent, Vec<RegisteredHook>>,
}

/// Result of firing a hook.
#[derive(Debug)]
pub enum HookAction {
    /// Hook completed normally (allow the action).
    Allow,
    /// Hook blocked the action (exit code 2 from PreToolUse).
    Block(String),
    /// Hook ran but produced an error (non-fatal).
    Error(String),
}

/// Context provided to hooks at fire time.
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub struct HookContext {
    /// Tool name (for PreToolUse/PostToolUse).
    pub tool_name: Option<String>,
    /// Tool arguments as JSON string (for PreToolUse).
    pub tool_args: Option<String>,
    /// Tool result (for PostToolUse).
    pub tool_result: Option<String>,
    /// Whether the tool succeeded (for PostToolUse).
    pub tool_success: Option<bool>,
    /// Working directory.
    pub working_dir: PathBuf,
}

impl HookContext {
    /// Create context for PreToolUse.
    pub fn pre_tool_use(tool_name: &str, args: &str, working_dir: &Path) -> Self {
        Self {
            tool_name: Some(tool_name.to_string()),
            tool_args: Some(args.to_string()),
            tool_result: None,
            tool_success: None,
            working_dir: working_dir.to_path_buf(),
        }
    }

    /// Create context for PostToolUse.
    pub fn post_tool_use(tool_name: &str, result: &str, success: bool, working_dir: &Path) -> Self {
        Self {
            tool_name: Some(tool_name.to_string()),
            tool_args: None,
            tool_result: Some(result.to_string()),
            tool_success: Some(success),
            working_dir: working_dir.to_path_buf(),
        }
    }

    /// Create context for SessionStart / SessionEnd / PreCompact / Stop.
    pub fn simple(working_dir: &Path) -> Self {
        Self {
            tool_name: None,
            tool_args: None,
            tool_result: None,
            tool_success: None,
            working_dir: working_dir.to_path_buf(),
        }
    }

    /// Create context for Stop (includes stop reason as tool_name).
    pub fn stop(reason: &str, working_dir: &Path) -> Self {
        Self {
            tool_name: Some(reason.to_string()),
            tool_args: None,
            tool_result: None,
            tool_success: None,
            working_dir: working_dir.to_path_buf(),
        }
    }

    /// Create context for SubagentStart.
    pub fn subagent_start(agent_id: &str, agent_name: &str, working_dir: &Path) -> Self {
        Self {
            tool_name: Some(agent_name.to_string()),
            tool_args: Some(agent_id.to_string()),
            tool_result: None,
            tool_success: None,
            working_dir: working_dir.to_path_buf(),
        }
    }

    /// Create context for SubagentStop.
    pub fn subagent_stop(
        agent_id: &str,
        agent_name: &str,
        success: bool,
        working_dir: &Path,
    ) -> Self {
        Self {
            tool_name: Some(agent_name.to_string()),
            tool_args: Some(agent_id.to_string()),
            tool_result: None,
            tool_success: Some(success),
            working_dir: working_dir.to_path_buf(),
        }
    }
}

impl HookRuntime {
    /// Create an empty runtime.
    pub fn new() -> Self {
        Self {
            hooks: HashMap::new(),
        }
    }

    /// Merge hooks from a parsed HookConfig, resolving environment variables.
    pub fn merge(&mut self, config: &HookConfig, plugin_root: &Path) {
        let hooks_obj = match config.raw.get("hooks") {
            Some(serde_json::Value::Object(obj)) => obj,
            _ => return,
        };

        for (event_name, registrations) in hooks_obj {
            let event = match HookEvent::from_str_name(event_name) {
                Some(e) => e,
                None => {
                    tracing::debug!(event = %event_name, "Unknown hook event, skipping");
                    continue;
                }
            };

            let reg_list = match registrations.as_array() {
                Some(arr) => arr,
                None => continue,
            };

            for reg in reg_list {
                let matcher = reg
                    .get("matcher")
                    .and_then(|v| v.as_str())
                    .unwrap_or("*")
                    .to_string();

                let description = reg
                    .get("description")
                    .and_then(|v| v.as_str())
                    .map(|s| s.to_string());

                let inner_hooks = match reg.get("hooks").and_then(|v| v.as_array()) {
                    Some(arr) => arr,
                    None => continue,
                };

                for hook_def in inner_hooks {
                    let command = match hook_def.get("command").and_then(|v| v.as_str()) {
                        Some(cmd) => cmd.to_string(),
                        None => continue,
                    };

                    let is_async = hook_def
                        .get("async")
                        .and_then(|v| v.as_bool())
                        .unwrap_or(false);

                    let timeout_secs = hook_def
                        .get("timeout")
                        .and_then(|v| v.as_u64())
                        .or(if is_async { Some(5) } else { None });

                    self.hooks.entry(event).or_default().push(RegisteredHook {
                        event,
                        matcher: matcher.clone(),
                        command,
                        description: description.clone(),
                        is_async,
                        timeout_secs,
                        plugin_root: plugin_root.to_path_buf(),
                    });
                }
            }
        }
    }

    /// Fire all hooks matching an event, respecting matchers.
    ///
    /// For `PreToolUse`, returns `Block` if any hook exits with code 2.
    /// For other events, all hooks run and errors are logged but non-fatal.
    ///
    /// # Matcher syntax
    ///
    /// - `"*"` — match everything
    /// - `"Bash"` — match a single tool name
    /// - `"file_edit|file_write"` — pipe-separated OR matching
    pub async fn fire(&self, event: HookEvent, ctx: &HookContext) -> Vec<HookAction> {
        let hooks = match self.hooks.get(&event) {
            Some(h) => h,
            None => return Vec::new(),
        };

        let mut results = Vec::new();

        for hook in hooks {
            // Check matcher
            if !matcher_matches(&hook.matcher, ctx.tool_name.as_deref()) {
                continue;
            }

            let action = self.run_hook(hook, ctx).await;
            results.push(action);
        }

        results
    }

    /// Execute a single hook command.
    async fn run_hook(&self, hook: &RegisteredHook, ctx: &HookContext) -> HookAction {
        // Substitute environment variables
        const MAX_COMMAND_LEN: usize = 4096;
        let command = substitute_env(&hook.command, &hook.plugin_root, ctx);
        if command.len() > MAX_COMMAND_LEN {
            return HookAction::Error(format!(
                "Hook command exceeds maximum length ({} > {MAX_COMMAND_LEN})",
                command.len()
            ));
        }

        let desc = hook.description.as_deref().unwrap_or(&hook.command);

        tracing::debug!(
            event = ?hook.event,
            matcher = %hook.matcher,
            desc = %desc,
            command = %command,
            "Firing plugin hook"
        );

        let exec = async {
            // Split command into argv tokens; reject shell metacharacters.
            let argv = match split_command(&command) {
                Some(v) => v,
                None => {
                    return HookAction::Error(format!(
                        "Hook '{}' command contains shell metacharacters or is invalid — \
                         use a plain executable with arguments only",
                        desc
                    ));
                }
            };

            let mut cmd = tokio::process::Command::new(&argv[0]);
            cmd.args(&argv[1..])
                .current_dir(&ctx.working_dir)
                .env("COLLET_PLUGIN_ROOT", &hook.plugin_root)
                // Backward compat: also set CLAUDE_PLUGIN_ROOT
                .env("CLAUDE_PLUGIN_ROOT", &hook.plugin_root)
                .stdout(std::process::Stdio::null())
                .stderr(std::process::Stdio::null());

            match cmd.status().await {
                Ok(status) => {
                    if status.success() {
                        HookAction::Allow
                    } else if status.code() == Some(2) {
                        // Exit code 2 = block (Claude Code convention)
                        HookAction::Block(desc.to_string())
                    } else {
                        HookAction::Error(format!(
                            "Hook '{}' exited with code {}",
                            desc,
                            status.code().unwrap_or(-1)
                        ))
                    }
                }
                Err(e) => HookAction::Error(format!("Hook '{}' failed to execute: {e}", desc)),
            }
        };

        // Always apply a timeout — default 30s to prevent the agent loop from
        // blocking indefinitely when a hook produces no output.
        let secs = hook.timeout_secs.unwrap_or(30);
        match tokio::time::timeout(Duration::from_secs(secs), exec).await {
            Ok(action) => action,
            Err(_) => HookAction::Error(format!("Hook '{}' timed out after {}s", desc, secs)),
        }
    }

    /// Check if any hooks are registered for an event.
    pub fn has_hooks(&self, event: HookEvent) -> bool {
        self.hooks.get(&event).is_some_and(|v| !v.is_empty())
    }

    /// Count total registered hooks.
    #[allow(dead_code)]
    pub fn total_count(&self) -> usize {
        self.hooks.values().map(|v| v.len()).sum()
    }
}

/// Split a command string into argv tokens using simple shell-word splitting.
///
/// - Splits on whitespace, respecting single and double quotes.
/// - Returns `None` if any shell metacharacters are detected outside quotes:
///   `;`, `&&`, `||`, `|`, `` ` ``, `$(`, `>`, `<`, `&` (except inside `${...}`)
pub(crate) fn split_command(s: &str) -> Option<Vec<String>> {
    let mut tokens: Vec<String> = Vec::new();
    let mut current = String::new();
    let mut chars = s.chars().peekable();

    while let Some(ch) = chars.next() {
        match ch {
            // Single-quoted: everything literal until closing '
            '\'' => {
                loop {
                    match chars.next() {
                        Some('\'') => break,
                        Some(c) => current.push(c),
                        None => return None, // unterminated quote
                    }
                }
            }
            // Double-quoted: everything literal until closing " (no escapes needed for our use case)
            '"' => {
                loop {
                    match chars.next() {
                        Some('"') => break,
                        Some(c) => current.push(c),
                        None => return None, // unterminated quote
                    }
                }
            }
            // `${...}` is allowed (env var substitution reference) — pass through
            '$' => {
                current.push('$');
                if chars.peek() == Some(&'(') {
                    // $( ... ) is command substitution — reject
                    return None;
                }
                // Otherwise fine (e.g. ${VAR})
            }
            // Reject: semicolon
            ';' => return None,
            // Reject: backtick
            '`' => return None,
            // Reject: redirect
            '>' | '<' => return None,
            // `|` or `&` — need to look for `||`, `&&`, lone `|`, lone `&`
            '|' => return None,
            '&' => {
                // peek next: if `&` it's `&&` — either way, reject
                return None;
            }
            // Whitespace: token boundary
            c if c.is_whitespace() => {
                if !current.is_empty() {
                    tokens.push(std::mem::take(&mut current));
                }
            }
            c => current.push(c),
        }
    }

    if !current.is_empty() {
        tokens.push(current);
    }

    if tokens.is_empty() {
        return None;
    }

    Some(tokens)
}

/// Check if a matcher pattern matches the given tool name.
///
/// - `"*"` matches everything (including `None`)
/// - `"Bash"` matches exactly `"Bash"`
/// - `"file_edit|file_write|git_patch"` matches any of the pipe-separated names
/// - A specific matcher never matches when `tool_name` is `None`
fn matcher_matches(matcher: &str, tool_name: Option<&str>) -> bool {
    if matcher == "*" {
        return true;
    }
    match tool_name {
        Some(name) => matcher.split('|').any(|m| m == name),
        None => false,
    }
}

/// Substitute `${COLLET_PLUGIN_ROOT}` and related variables in a command string.
fn substitute_env(command: &str, plugin_root: &Path, _ctx: &HookContext) -> String {
    let root_str = plugin_root.to_string_lossy();
    command
        .replace("${CLAUDE_PLUGIN_ROOT}", &root_str)
        .replace("${COLLET_PLUGIN_ROOT}", &root_str)
}

/// Parse a `hooks.json` file.
pub fn parse_hooks_json(path: &Path) -> Result<HookConfig> {
    let content = std::fs::read_to_string(path)
        .with_context(|| format!("Failed to read {}", path.display()))?;
    let raw: serde_json::Value = serde_json::from_str(&content)
        .with_context(|| format!("Failed to parse {}", path.display()))?;
    Ok(HookConfig { raw })
}

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

    #[test]
    fn test_parse_hooks_json() {
        let dir = tempfile::tempdir().unwrap();
        let hooks_json = dir.path().join("hooks.json");
        fs::write(
            &hooks_json,
            r#"{
                "hooks": {
                    "SessionStart": [{
                        "matcher": "*",
                        "hooks": [{
                            "type": "command",
                            "command": "echo hello"
                        }]
                    }],
                    "PreToolUse": [{
                        "matcher": "Bash",
                        "hooks": [{
                            "type": "command",
                            "command": "${CLAUDE_PLUGIN_ROOT}/guard.sh"
                        }]
                    }],
                    "PostToolUse": [{
                        "matcher": "*",
                        "hooks": [{
                            "type": "command",
                            "command": "observe.sh",
                            "async": true,
                            "timeout": 5
                        }]
                    }]
                }
            }"#,
        )
        .unwrap();

        let config = parse_hooks_json(&hooks_json).unwrap();
        let mut runtime = HookRuntime::new();
        runtime.merge(&config, Path::new("/tmp/test-plugin"));

        assert!(runtime.has_hooks(HookEvent::SessionStart));
        assert!(runtime.has_hooks(HookEvent::PreToolUse));
        assert!(runtime.has_hooks(HookEvent::PostToolUse));
        assert!(!runtime.has_hooks(HookEvent::PreCompact));
        assert_eq!(runtime.total_count(), 3);

        // Check PreToolUse hook has the right matcher
        let pre_hooks = runtime.hooks.get(&HookEvent::PreToolUse).unwrap();
        assert_eq!(pre_hooks[0].matcher, "Bash");
    }

    #[test]
    fn test_substitute_env() {
        let result = substitute_env(
            "${CLAUDE_PLUGIN_ROOT}/hooks/bin/epic-harness",
            Path::new("/home/user/.collet/plugins/epic"),
            &HookContext::simple(Path::new(".")),
        );
        assert_eq!(
            result,
            "/home/user/.collet/plugins/epic/hooks/bin/epic-harness"
        );
    }

    #[test]
    fn test_split_command_rejects_metacharacters() {
        assert!(split_command("echo hello").is_some());
        assert!(split_command("echo hello; rm -rf /").is_none());
        assert!(split_command("cmd && other").is_none());
        assert!(split_command("${PLUGIN_ROOT}/script.py --flag value").is_some());
    }

    #[test]
    fn test_hook_event_from_str() {
        assert_eq!(
            HookEvent::from_str_name("SessionStart"),
            Some(HookEvent::SessionStart)
        );
        assert_eq!(
            HookEvent::from_str_name("PreToolUse"),
            Some(HookEvent::PreToolUse)
        );
        assert_eq!(
            HookEvent::from_str_name("PostToolUse"),
            Some(HookEvent::PostToolUse)
        );
        assert_eq!(
            HookEvent::from_str_name("PreCompact"),
            Some(HookEvent::PreCompact)
        );
        assert_eq!(
            HookEvent::from_str_name("SessionEnd"),
            Some(HookEvent::SessionEnd)
        );
        assert_eq!(HookEvent::from_str_name("Unknown"), None);
    }
}