mars-agents 0.4.7

Agent package manager for .agents/ directories
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
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
/// Hook compiler lane.
///
/// Discovers, parses, validates, orders, and translates hook definitions
/// from package trees into per-target config entries.
///
/// V0 scope:
/// - Universal event vocabulary: `session.start`, `session.end`, `tool.pre`, `tool.post`
/// - Non-V0 events are rejected with a hard error
/// - Per-target lossiness classification: exact | approximate | dropped
/// - Deterministic total ordering: depth → dependency order → `order` field → name
use std::fmt;
use std::path::{Path, PathBuf};

use serde::Deserialize;

use crate::error::{ConfigError, MarsError};

// ---------------------------------------------------------------------------
// Universal event vocabulary (V0)
// ---------------------------------------------------------------------------

/// V0 universal hook events.
///
/// Any event string not in this list is rejected by the compiler.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum UniversalEvent {
    SessionStart,
    SessionEnd,
    ToolPre,
    ToolPost,
}

impl UniversalEvent {
    /// Parse a string into a universal event, rejecting unknown/non-V0 values.
    pub fn parse(s: &str) -> Result<Self, MarsError> {
        match s {
            "session.start" => Ok(Self::SessionStart),
            "session.end" => Ok(Self::SessionEnd),
            "tool.pre" => Ok(Self::ToolPre),
            "tool.post" => Ok(Self::ToolPost),
            other => Err(MarsError::Config(ConfigError::Invalid {
                message: format!(
                    "unknown or unsupported hook event `{other}` — \
                     V0 events are: session.start, session.end, tool.pre, tool.post"
                ),
            })),
        }
    }

    /// The canonical event string.
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::SessionStart => "session.start",
            Self::SessionEnd => "session.end",
            Self::ToolPre => "tool.pre",
            Self::ToolPost => "tool.post",
        }
    }
}

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

// ---------------------------------------------------------------------------
// Schema types
// ---------------------------------------------------------------------------

/// The action a hook performs.
#[derive(Debug, Clone, Deserialize)]
#[serde(tag = "kind")]
pub enum HookAction {
    /// Run a script.
    #[serde(rename = "script")]
    Script {
        /// Path to the script, relative to the hook directory.
        path: String,
    },
}

/// Raw deserialization form of a hook definition.
/// Exists so we can parse the `event` as a plain string before validating.
#[derive(Debug, Deserialize)]
struct RawHookDef {
    name: String,
    event: String,
    #[serde(default = "default_visibility")]
    visibility: String,
    #[serde(default)]
    targets: Vec<String>,
    action: HookAction,
    #[serde(default)]
    order: i32,
}

fn default_visibility() -> String {
    "local".to_string()
}

/// A parsed, validated hook definition.
#[derive(Debug, Clone)]
pub struct HookDef {
    pub name: String,
    pub event: UniversalEvent,
    pub visibility: String,
    pub targets: Vec<String>,
    pub action: HookAction,
    /// Explicit ordering hint (lower = earlier).
    pub order: i32,
}

/// A discovered hook item with provenance.
#[derive(Debug, Clone)]
pub struct ParsedHookItem {
    pub def: HookDef,
    /// Source package name.
    pub source_name: String,
    /// Depth in the dependency graph (0 = root package).
    pub package_depth: usize,
    /// Position of the source in the dependency declaration order.
    /// Used for stable ordering within the same depth.
    pub decl_order: usize,
    /// Absolute path to the package root this hook was discovered in.
    pub package_root: PathBuf,
}

// ---------------------------------------------------------------------------
// Path traversal validation
// ---------------------------------------------------------------------------

/// Validate a hook name used as a path component.
///
/// Rejects names that could escape the package root via path traversal.
fn validate_path_component(name: &str) -> Result<(), &'static str> {
    if name.contains('\0') {
        return Err("contains null byte");
    }
    // Reject any path component that is or starts with `..`.
    for component in Path::new(name).components() {
        use std::path::Component;
        match component {
            Component::ParentDir => return Err("contains `..` component"),
            Component::RootDir | Component::Prefix(_) => {
                return Err("must not be an absolute path");
            }
            _ => {}
        }
    }
    Ok(())
}

/// Validate a script path from `HookAction::Script`.
///
/// - Rejects absolute paths (POSIX `/` or Windows drive letters).
/// - Rejects paths containing `..` components.
/// - Rejects paths with null bytes.
fn validate_hook_script_path(path: &str) -> Result<(), &'static str> {
    if path.contains('\0') {
        return Err("contains null byte");
    }
    use std::path::Component;
    for component in Path::new(path).components() {
        match component {
            Component::ParentDir => return Err("contains `..` component"),
            Component::RootDir | Component::Prefix(_) => {
                return Err("must not be an absolute path");
            }
            _ => {}
        }
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// Discovery
// ---------------------------------------------------------------------------

/// Discover hook items from a package root.
///
/// Scans `<package_root>/hooks/<name>/hook.toml` for each subdirectory.
pub fn discover_hook_items(
    package_root: &Path,
    source_name: &str,
    package_depth: usize,
    decl_order: usize,
) -> Result<Vec<ParsedHookItem>, MarsError> {
    let hooks_dir = package_root.join("hooks");
    if !hooks_dir.is_dir() {
        return Ok(Vec::new());
    }

    let mut items = Vec::new();
    let mut entries: Vec<_> = std::fs::read_dir(&hooks_dir)
        .map_err(MarsError::from)?
        .filter_map(|e| e.ok())
        .filter(|e| e.path().is_dir())
        .collect();
    entries.sort_by_key(|e| e.file_name());

    for entry in entries {
        let dir_name = entry.file_name();
        let hook_dir_name = dir_name.to_string_lossy();
        if hook_dir_name.starts_with('.') {
            continue;
        }

        let toml_path = entry.path().join("hook.toml");
        if !toml_path.is_file() {
            continue;
        }

        let raw = std::fs::read_to_string(&toml_path).map_err(MarsError::from)?;
        let raw_def: RawHookDef = toml::from_str(&raw).map_err(|e| {
            MarsError::Config(ConfigError::Invalid {
                message: format!("failed to parse {}: {e}", toml_path.display()),
            })
        })?;

        // Validate event — reject non-V0 events with a hard error.
        let event = UniversalEvent::parse(&raw_def.event)?;

        // Validate the hook name used in path construction.
        if let Err(msg) = validate_path_component(&raw_def.name) {
            return Err(MarsError::Config(ConfigError::Invalid {
                message: format!(
                    "hook in {}: invalid name `{}`: {msg}",
                    toml_path.display(),
                    raw_def.name
                ),
            }));
        }

        // Validate the script path from HookAction::Script.
        {
            let HookAction::Script {
                path: ref script_path,
            } = raw_def.action;
            if let Err(msg) = validate_hook_script_path(script_path) {
                return Err(MarsError::Config(ConfigError::Invalid {
                    message: format!(
                        "hook `{}` in {}: invalid script path `{script_path}`: {msg}",
                        raw_def.name,
                        toml_path.display()
                    ),
                }));
            }
        }

        items.push(ParsedHookItem {
            def: HookDef {
                name: raw_def.name,
                event,
                visibility: raw_def.visibility,
                targets: raw_def.targets,
                action: raw_def.action,
                order: raw_def.order,
            },
            source_name: source_name.to_string(),
            package_depth,
            decl_order,
            package_root: package_root.to_path_buf(),
        });
    }

    Ok(items)
}

// ---------------------------------------------------------------------------
// Ordering
// ---------------------------------------------------------------------------

/// A hook with a fully computed sort key for deterministic ordering.
#[derive(Debug, Clone)]
pub struct OrderedHook {
    pub item: ParsedHookItem,
    /// Sort key: (depth, decl_order, order_field, name)
    pub sort_key: (usize, usize, i32, String),
}

/// Order hooks by the deterministic total order defined in the spec:
///
/// 1. package depth (root first, depth 0 < depth 1 < ...)
/// 2. dependency declaration order within the same depth
/// 3. explicit `order` field (lower = earlier; default 0)
/// 4. hook name (lexicographic, final tie-breaker)
pub fn order_hooks(items: Vec<ParsedHookItem>) -> Vec<OrderedHook> {
    let mut ordered: Vec<OrderedHook> = items
        .into_iter()
        .map(|item| {
            let sort_key = (
                item.package_depth,
                item.decl_order,
                item.def.order,
                item.def.name.clone(),
            );
            OrderedHook { item, sort_key }
        })
        .collect();

    ordered.sort_by(|a, b| a.sort_key.cmp(&b.sort_key));
    ordered
}

// ---------------------------------------------------------------------------
// Lossiness classification and target translation
// ---------------------------------------------------------------------------

/// How well a universal hook event maps to a target's native hook mechanism.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LossinessKind {
    /// Native target has the same semantics.
    Exact,
    /// Native target has a nearby semantic equivalent.
    Approximate,
    /// No native equivalent — the hook entry will be dropped with a warning.
    Dropped,
}

/// Result of translating a hook for a specific target.
#[derive(Debug, Clone)]
pub struct TranslatedHook {
    pub hook: OrderedHook,
    pub lossiness: LossinessKind,
    /// Native event name in the target (None when Dropped).
    pub native_event: Option<String>,
}

/// Translate an ordered hook for a specific target root.
///
/// Lossiness table (Claude):
///   session.start → SessionStart (exact)
///   session.end   → SessionStop  (approximate — Claude uses Stop not End)
///   tool.pre      → PreToolUse   (exact)
///   tool.post     → PostToolUse  (exact)
///
/// Lossiness table (Codex):
///   All events → approximate (Codex hook config is structural, not event-named)
///
/// Lossiness table (OpenCode):
///   All events → approximate (plugin hooks)
///
/// Lossiness table (Cursor):
///   All events → dropped (limited/undocumented hook surface)
///
/// Lossiness table (Pi):
///   All events → dropped (no native hook support)
pub fn translate_hook_for_target(hook: OrderedHook, target_root: &str) -> TranslatedHook {
    let (lossiness, native_event) = classify_for_target(hook.item.def.event.clone(), target_root);
    TranslatedHook {
        hook,
        lossiness,
        native_event,
    }
}

fn classify_for_target(
    event: UniversalEvent,
    target_root: &str,
) -> (LossinessKind, Option<String>) {
    match target_root {
        ".claude" => match event {
            UniversalEvent::SessionStart => {
                (LossinessKind::Exact, Some("SessionStart".to_string()))
            }
            UniversalEvent::SessionEnd => {
                // Claude uses SessionStop, not SessionEnd — close but not exact.
                (LossinessKind::Approximate, Some("SessionStop".to_string()))
            }
            UniversalEvent::ToolPre => (LossinessKind::Exact, Some("PreToolUse".to_string())),
            UniversalEvent::ToolPost => (LossinessKind::Exact, Some("PostToolUse".to_string())),
        },
        ".codex" => {
            // Codex uses structural hook entries, not named events — approximate for all.
            let codex_event = match event {
                UniversalEvent::SessionStart => "start",
                UniversalEvent::SessionEnd => "stop",
                UniversalEvent::ToolPre => "pre-exec",
                UniversalEvent::ToolPost => "post-exec",
            };
            (LossinessKind::Approximate, Some(codex_event.to_string()))
        }
        ".opencode" => {
            let opencode_event = match event {
                UniversalEvent::SessionStart => "session:start",
                UniversalEvent::SessionEnd => "session:end",
                UniversalEvent::ToolPre => "tool:before",
                UniversalEvent::ToolPost => "tool:after",
            };
            (LossinessKind::Approximate, Some(opencode_event.to_string()))
        }
        ".cursor" | ".pi" => {
            // No native hook surface.
            (LossinessKind::Dropped, None)
        }
        _ => (LossinessKind::Dropped, None),
    }
}

/// Translate all hooks for a target root, filtering to those that apply.
///
/// Dropped hooks emit a log-level warning (callers should emit diagnostics).
/// Returns both non-dropped and dropped entries so callers can report lossiness.
pub fn translate_hooks_for_target(
    ordered: Vec<OrderedHook>,
    target_root: &str,
) -> Vec<TranslatedHook> {
    ordered
        .into_iter()
        .filter(|h| {
            h.item.def.targets.is_empty() || h.item.def.targets.iter().any(|t| t == target_root)
        })
        .map(|h| translate_hook_for_target(h, target_root))
        .collect()
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    fn make_hook_toml_dir(dir: &Path, hook_name: &str, toml: &str) {
        let hook_dir = dir.join("hooks").join(hook_name);
        std::fs::create_dir_all(&hook_dir).unwrap();
        std::fs::write(hook_dir.join("hook.toml"), toml).unwrap();
    }

    fn make_script_hook(dir: &Path, hook_name: &str, event: &str) {
        make_hook_toml_dir(
            dir,
            hook_name,
            &format!(
                r#"
name = "{hook_name}"
event = "{event}"
[action]
kind = "script"
path = "./run.sh"
"#
            ),
        );
    }

    #[test]
    fn discover_finds_hook_items() {
        let tmp = TempDir::new().unwrap();
        make_script_hook(tmp.path(), "audit", "tool.pre");

        let items = discover_hook_items(tmp.path(), "base", 0, 0).unwrap();
        assert_eq!(items.len(), 1);
        assert_eq!(items[0].def.name, "audit");
        assert_eq!(items[0].def.event, UniversalEvent::ToolPre);
    }

    #[test]
    fn discover_empty_when_no_hooks_dir() {
        let tmp = TempDir::new().unwrap();
        let items = discover_hook_items(tmp.path(), "base", 0, 0).unwrap();
        assert!(items.is_empty());
    }

    #[test]
    fn discover_rejects_non_v0_event() {
        let tmp = TempDir::new().unwrap();
        make_hook_toml_dir(
            tmp.path(),
            "bad-hook",
            r#"
name = "bad"
event = "spawn.created"
[action]
kind = "script"
path = "./run.sh"
"#,
        );
        let result = discover_hook_items(tmp.path(), "base", 0, 0);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("spawn.created"));
    }

    #[test]
    fn universal_event_parse_accepts_all_v0() {
        assert!(UniversalEvent::parse("session.start").is_ok());
        assert!(UniversalEvent::parse("session.end").is_ok());
        assert!(UniversalEvent::parse("tool.pre").is_ok());
        assert!(UniversalEvent::parse("tool.post").is_ok());
    }

    #[test]
    fn universal_event_parse_rejects_unknown() {
        let err = UniversalEvent::parse("work.start").unwrap_err();
        assert!(err.to_string().contains("work.start"));
    }

    #[test]
    fn order_hooks_depth_first() {
        let tmp_root = TempDir::new().unwrap();
        let tmp_dep = TempDir::new().unwrap();

        make_script_hook(tmp_root.path(), "root-hook", "tool.pre");
        make_script_hook(tmp_dep.path(), "dep-hook", "tool.pre");

        let mut root_items = discover_hook_items(tmp_root.path(), "root", 0, 0).unwrap();
        let dep_items = discover_hook_items(tmp_dep.path(), "dep", 1, 0).unwrap();
        root_items.extend(dep_items);

        let ordered = order_hooks(root_items);
        assert_eq!(ordered[0].item.def.name, "root-hook");
        assert_eq!(ordered[1].item.def.name, "dep-hook");
    }

    #[test]
    fn order_hooks_explicit_order_field() {
        let tmp = TempDir::new().unwrap();
        make_hook_toml_dir(
            tmp.path(),
            "hook-b",
            r#"
name = "hook-b"
event = "tool.pre"
order = 10
[action]
kind = "script"
path = "./b.sh"
"#,
        );
        make_hook_toml_dir(
            tmp.path(),
            "hook-a",
            r#"
name = "hook-a"
event = "tool.pre"
order = 5
[action]
kind = "script"
path = "./a.sh"
"#,
        );

        let items = discover_hook_items(tmp.path(), "base", 0, 0).unwrap();
        let ordered = order_hooks(items);
        // hook-a has lower order (5) so it runs first.
        assert_eq!(ordered[0].item.def.name, "hook-a");
        assert_eq!(ordered[1].item.def.name, "hook-b");
    }

    #[test]
    fn order_hooks_name_as_tiebreaker() {
        let tmp = TempDir::new().unwrap();
        make_script_hook(tmp.path(), "zebra", "tool.pre");
        make_script_hook(tmp.path(), "alpha", "tool.pre");

        let items = discover_hook_items(tmp.path(), "base", 0, 0).unwrap();
        let ordered = order_hooks(items);
        // Same depth, same order field (0), name tiebreaker: alpha < zebra.
        assert_eq!(ordered[0].item.def.name, "alpha");
        assert_eq!(ordered[1].item.def.name, "zebra");
    }

    #[test]
    fn translate_claude_tool_pre_is_exact() {
        let tmp = TempDir::new().unwrap();
        make_script_hook(tmp.path(), "audit", "tool.pre");
        let items = discover_hook_items(tmp.path(), "base", 0, 0).unwrap();
        let ordered = order_hooks(items);
        let translated = translate_hook_for_target(ordered.into_iter().next().unwrap(), ".claude");
        assert_eq!(translated.lossiness, LossinessKind::Exact);
        assert_eq!(translated.native_event.as_deref(), Some("PreToolUse"));
    }

    #[test]
    fn translate_claude_session_end_is_approximate() {
        let tmp = TempDir::new().unwrap();
        make_script_hook(tmp.path(), "cleanup", "session.end");
        let items = discover_hook_items(tmp.path(), "base", 0, 0).unwrap();
        let ordered = order_hooks(items);
        let translated = translate_hook_for_target(ordered.into_iter().next().unwrap(), ".claude");
        assert_eq!(translated.lossiness, LossinessKind::Approximate);
        assert_eq!(translated.native_event.as_deref(), Some("SessionStop"));
    }

    #[test]
    fn translate_cursor_is_dropped() {
        let tmp = TempDir::new().unwrap();
        make_script_hook(tmp.path(), "hook", "tool.pre");
        let items = discover_hook_items(tmp.path(), "base", 0, 0).unwrap();
        let ordered = order_hooks(items);
        let translated = translate_hook_for_target(ordered.into_iter().next().unwrap(), ".cursor");
        assert_eq!(translated.lossiness, LossinessKind::Dropped);
        assert!(translated.native_event.is_none());
    }

    #[test]
    fn translate_hooks_filters_by_target() {
        let tmp = TempDir::new().unwrap();
        make_hook_toml_dir(
            tmp.path(),
            "claude-only",
            r#"
name = "claude-only"
event = "tool.pre"
targets = [".claude"]
[action]
kind = "script"
path = "./run.sh"
"#,
        );
        make_script_hook(tmp.path(), "all-targets", "tool.post");

        let items = discover_hook_items(tmp.path(), "base", 0, 0).unwrap();
        let ordered = order_hooks(items);

        let claude_hooks = translate_hooks_for_target(ordered.clone(), ".claude");
        assert_eq!(claude_hooks.len(), 2);

        let codex_hooks = translate_hooks_for_target(ordered, ".codex");
        assert_eq!(codex_hooks.len(), 1);
        assert_eq!(codex_hooks[0].hook.item.def.name, "all-targets");
    }

    #[test]
    fn ordering_is_deterministic_across_multiple_calls() {
        let tmp = TempDir::new().unwrap();
        make_script_hook(tmp.path(), "c-hook", "tool.pre");
        make_script_hook(tmp.path(), "a-hook", "session.start");
        make_script_hook(tmp.path(), "b-hook", "tool.post");

        let items = discover_hook_items(tmp.path(), "base", 0, 0).unwrap();
        let first: Vec<String> = order_hooks(items.clone())
            .iter()
            .map(|h| h.item.def.name.clone())
            .collect();
        for _ in 0..5 {
            let items2 = discover_hook_items(tmp.path(), "base", 0, 0).unwrap();
            let current: Vec<String> = order_hooks(items2)
                .iter()
                .map(|h| h.item.def.name.clone())
                .collect();
            assert_eq!(first, current);
        }
    }

    #[test]
    fn discover_rejects_dotdot_in_script_path() {
        let tmp = TempDir::new().unwrap();
        make_hook_toml_dir(
            tmp.path(),
            "bad-hook",
            r#"
name = "bad"
event = "tool.pre"
[action]
kind = "script"
path = "../../etc/passwd"
"#,
        );
        let result = discover_hook_items(tmp.path(), "base", 0, 0);
        assert!(result.is_err());
        let msg = result.unwrap_err().to_string();
        assert!(msg.contains(".."), "expected traversal error, got: {msg}");
    }

    #[test]
    fn discover_rejects_absolute_script_path() {
        let tmp = TempDir::new().unwrap();
        make_hook_toml_dir(
            tmp.path(),
            "bad-hook",
            r#"
name = "bad"
event = "tool.pre"
[action]
kind = "script"
path = "/etc/passwd"
"#,
        );
        let result = discover_hook_items(tmp.path(), "base", 0, 0);
        assert!(result.is_err());
        let msg = result.unwrap_err().to_string();
        assert!(
            msg.contains("absolute"),
            "expected absolute-path error, got: {msg}"
        );
    }

    #[test]
    fn validate_path_component_rejects_dotdot() {
        assert!(validate_path_component("..").is_err());
        assert!(validate_path_component("../foo").is_err());
    }

    #[test]
    fn validate_path_component_accepts_normal_name() {
        assert!(validate_path_component("my-hook").is_ok());
        assert!(validate_path_component("audit_v2").is_ok());
    }

    #[test]
    fn validate_hook_script_path_rejects_null_byte() {
        assert!(validate_hook_script_path("run\0.sh").is_err());
    }

    #[test]
    fn validate_hook_script_path_accepts_relative() {
        assert!(validate_hook_script_path("./run.sh").is_ok());
        assert!(validate_hook_script_path("run.sh").is_ok());
        assert!(validate_hook_script_path("scripts/run.sh").is_ok());
    }
}