agnix-core 0.19.0

Core validation engine for agent configurations
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
//! Hooks validation rules (CC-HK-001 to CC-HK-025)

use crate::{
    config::LintConfig,
    diagnostics::{Diagnostic, Fix},
    rules::{Validator, ValidatorMetadata},
    schemas::hooks::{Hook, HooksSchema, SettingsSchema},
};
use rust_i18n::t;
use std::path::Path;

mod helpers;
use helpers::*;

const RULE_IDS: &[&str] = &[
    "CC-HK-001",
    "CC-HK-002",
    "CC-HK-003",
    "CC-HK-004",
    "CC-HK-005",
    "CC-HK-006",
    "CC-HK-007",
    "CC-HK-008",
    "CC-HK-009",
    "CC-HK-010",
    "CC-HK-011",
    "CC-HK-012",
    "CC-HK-013",
    "CC-HK-014",
    "CC-HK-015",
    "CC-HK-016",
    "CC-HK-017",
    "CC-HK-018",
    "CC-HK-019",
    "CC-HK-020",
    "CC-HK-021",
    "CC-HK-022",
    "CC-HK-023",
    "CC-HK-024",
    "CC-HK-025",
];

pub struct HooksValidator;

/// Default timeout thresholds per hook type (from official Claude Code docs)
const COMMAND_HOOK_DEFAULT_TIMEOUT: u64 = 600; // 10 minutes
const PROMPT_HOOK_DEFAULT_TIMEOUT: u64 = 30; // 30 seconds

/// CC-HK-006: Missing command field
fn validate_cc_hk_006_command_field(
    command: &Option<String>,
    hook_location: &str,
    path: &Path,
    diagnostics: &mut Vec<Diagnostic>,
) {
    if command.is_none() {
        diagnostics.push(
            Diagnostic::error(
                path.to_path_buf(),
                1,
                0,
                "CC-HK-006",
                t!("rules.cc_hk_006.message", location = hook_location),
            )
            .with_suggestion(t!("rules.cc_hk_006.suggestion")),
        );
    }
}

/// CC-HK-008: Script file not found
fn validate_cc_hk_008_script_exists(
    command: &str,
    project_dir: &Path,
    config: &LintConfig,
    path: &Path,
    diagnostics: &mut Vec<Diagnostic>,
) {
    let fs = config.fs();
    for script_path in extract_script_paths(command) {
        if !has_unresolved_env_vars(&script_path) {
            let resolved = resolve_script_path(&script_path, project_dir);
            if !fs.exists(&resolved) {
                diagnostics.push(
                    Diagnostic::error(
                        path.to_path_buf(),
                        1,
                        0,
                        "CC-HK-008",
                        t!(
                            "rules.cc_hk_008.message",
                            script = script_path.as_str(),
                            resolved = resolved.display().to_string()
                        ),
                    )
                    .with_suggestion(t!("rules.cc_hk_008.suggestion")),
                );
            }
        }
    }
}

/// CC-HK-009: Dangerous command patterns
fn validate_cc_hk_009_dangerous_patterns(
    command: &str,
    path: &Path,
    diagnostics: &mut Vec<Diagnostic>,
) {
    if let Some((pattern, reason)) = check_dangerous_patterns(command) {
        diagnostics.push(
            Diagnostic::warning(
                path.to_path_buf(),
                1,
                0,
                "CC-HK-009",
                t!("rules.cc_hk_009.message", reason = reason),
            )
            .with_suggestion(t!("rules.cc_hk_009.suggestion", pattern = pattern)),
        );
    }
}

/// CC-HK-010: Command hook timeout policy
fn validate_cc_hk_010_command_timeout(
    timeout: &Option<u64>,
    hook_location: &str,
    version_pinned: bool,
    path: &Path,
    diagnostics: &mut Vec<Diagnostic>,
) {
    if timeout.is_none() {
        let mut diag = Diagnostic::warning(
            path.to_path_buf(),
            1,
            0,
            "CC-HK-010",
            t!(
                "rules.cc_hk_010.command_no_timeout",
                location = hook_location
            ),
        )
        .with_suggestion(t!("rules.cc_hk_010.command_no_timeout_suggestion"));

        if !version_pinned {
            diag = diag.with_assumption(t!("rules.cc_hk_010.assumption"));
        }

        diagnostics.push(diag);
    }
    if let Some(t) = timeout {
        if *t > COMMAND_HOOK_DEFAULT_TIMEOUT {
            let mut diag = Diagnostic::warning(
                path.to_path_buf(),
                1,
                0,
                "CC-HK-010",
                t!(
                    "rules.cc_hk_010.command_exceeds",
                    location = hook_location,
                    timeout = t,
                    default = COMMAND_HOOK_DEFAULT_TIMEOUT
                ),
            )
            .with_suggestion(t!(
                "rules.cc_hk_010.command_exceeds_suggestion",
                default = COMMAND_HOOK_DEFAULT_TIMEOUT
            ));

            if !version_pinned {
                diag = diag.with_assumption(t!("rules.cc_hk_010.assumption"));
            }

            diagnostics.push(diag);
        }
    }
}

/// CC-HK-015: Model on command hook
fn validate_cc_hk_015_model_on_command(
    hook_location: &str,
    path: &Path,
    content: &str,
    diagnostics: &mut Vec<Diagnostic>,
) {
    let mut diagnostic = Diagnostic::warning(
        path.to_path_buf(),
        1,
        0,
        "CC-HK-015",
        t!("rules.cc_hk_015.message", location = hook_location),
    )
    .with_suggestion(t!("rules.cc_hk_015.suggestion"));

    // Safe auto-fix: remove the model field line
    if let Some((start, end)) = find_unique_json_field_line_span(content, "model") {
        diagnostic = diagnostic.with_fix(Fix::delete(start, end, t!("rules.cc_hk_015.fix"), true));
    }

    diagnostics.push(diagnostic);
}

/// CC-HK-017: Prompt hook missing $ARGUMENTS
fn validate_cc_hk_017_prompt_arguments(
    prompt: &str,
    hook_location: &str,
    path: &Path,
    diagnostics: &mut Vec<Diagnostic>,
) {
    if !prompt.contains("$ARGUMENTS") {
        diagnostics.push(
            Diagnostic::warning(
                path.to_path_buf(),
                1,
                0,
                "CC-HK-017",
                t!("rules.cc_hk_017.message", location = hook_location),
            )
            .with_suggestion(t!("rules.cc_hk_017.suggestion")),
        );
    }
}

/// CC-HK-018: Matcher on UserPromptSubmit/Stop events (silently ignored)
fn validate_cc_hk_018_matcher_ignored(
    event: &str,
    matcher: &Option<String>,
    matcher_idx: usize,
    path: &Path,
    content: &str,
    diagnostics: &mut Vec<Diagnostic>,
) {
    let ignored_events = ["UserPromptSubmit", "Stop"];
    if ignored_events.contains(&event) && matcher.is_some() {
        let hook_location = format!("hooks.{}[{}]", event, matcher_idx);
        let mut diagnostic = Diagnostic::info(
            path.to_path_buf(),
            1,
            0,
            "CC-HK-018",
            t!(
                "rules.cc_hk_018.message",
                location = hook_location.as_str(),
                event = event
            ),
        )
        .with_suggestion(t!("rules.cc_hk_018.suggestion", event = event));

        // Safe auto-fix: remove the matcher field line
        if let Some(matcher_val) = matcher {
            if let Some((start, end)) = find_unique_matcher_line_span(content, matcher_val) {
                diagnostic = diagnostic.with_fix(Fix::delete(
                    start,
                    end,
                    t!("rules.cc_hk_018.fix", event = event),
                    true,
                ));
            }
        }

        diagnostics.push(diagnostic);
    }
}

/// CC-HK-002: Prompt hook on wrong event
fn validate_cc_hk_002_prompt_event_type(
    event: &str,
    hook_location: &str,
    path: &Path,
    diagnostics: &mut Vec<Diagnostic>,
) {
    if !HooksSchema::is_prompt_event(event) {
        diagnostics.push(
            Diagnostic::error(
                path.to_path_buf(),
                1,
                0,
                "CC-HK-002",
                t!(
                    "rules.cc_hk_002.message",
                    location = hook_location,
                    event = event
                ),
            )
            .with_suggestion(t!("rules.cc_hk_002.suggestion")),
        );
    }
}

/// CC-HK-007: Missing prompt field
fn validate_cc_hk_007_prompt_field(
    prompt: &Option<String>,
    hook_location: &str,
    path: &Path,
    diagnostics: &mut Vec<Diagnostic>,
) {
    if prompt.is_none() {
        diagnostics.push(
            Diagnostic::error(
                path.to_path_buf(),
                1,
                0,
                "CC-HK-007",
                t!("rules.cc_hk_007.message", location = hook_location),
            )
            .with_suggestion(t!("rules.cc_hk_007.suggestion")),
        );
    }
}

/// CC-HK-010: Prompt hook timeout policy
fn validate_cc_hk_010_prompt_timeout(
    timeout: &Option<u64>,
    hook_location: &str,
    version_pinned: bool,
    path: &Path,
    diagnostics: &mut Vec<Diagnostic>,
) {
    if timeout.is_none() {
        let mut diag = Diagnostic::warning(
            path.to_path_buf(),
            1,
            0,
            "CC-HK-010",
            t!(
                "rules.cc_hk_010.prompt_no_timeout",
                location = hook_location
            ),
        )
        .with_suggestion(t!("rules.cc_hk_010.prompt_no_timeout_suggestion"));

        if !version_pinned {
            diag = diag.with_assumption(t!("rules.cc_hk_010.assumption"));
        }

        diagnostics.push(diag);
    }
    if let Some(t) = timeout {
        if *t > PROMPT_HOOK_DEFAULT_TIMEOUT {
            let mut diag = Diagnostic::warning(
                path.to_path_buf(),
                1,
                0,
                "CC-HK-010",
                t!(
                    "rules.cc_hk_010.prompt_exceeds",
                    location = hook_location,
                    timeout = t,
                    default = PROMPT_HOOK_DEFAULT_TIMEOUT
                ),
            )
            .with_suggestion(t!(
                "rules.cc_hk_010.prompt_exceeds_suggestion",
                default = PROMPT_HOOK_DEFAULT_TIMEOUT
            ));

            if !version_pinned {
                diag = diag.with_assumption(t!("rules.cc_hk_010.assumption"));
            }

            diagnostics.push(diag);
        }
    }
}

#[cfg(test)]
#[allow(dead_code)]
impl HooksValidator {
    fn check_dangerous_patterns(&self, command: &str) -> Option<(&'static str, &'static str)> {
        check_dangerous_patterns(command)
    }

    fn extract_script_paths(&self, command: &str) -> Vec<String> {
        extract_script_paths(command)
    }

    fn resolve_script_path(&self, script_path: &str, project_dir: &Path) -> std::path::PathBuf {
        resolve_script_path(script_path, project_dir)
    }

    fn has_unresolved_env_vars(&self, path: &str) -> bool {
        has_unresolved_env_vars(path)
    }
}

impl Validator for HooksValidator {
    fn metadata(&self) -> ValidatorMetadata {
        ValidatorMetadata {
            name: self.name(),
            rule_ids: RULE_IDS,
        }
    }

    /// Main validation entry point for hooks configuration.
    ///
    /// ## Validation Phases
    ///
    /// 1. **Category check** - Early return if hooks category disabled
    /// 2. **JSON parsing** - Parse raw JSON, report CC-HK-012 on failure
    /// 3. **Pre-parse validation** - Raw JSON checks (CC-HK-005, CC-HK-011, CC-HK-013..014, CC-HK-016, CC-HK-020..024)
    /// 4. **Typed parsing** - Parse into SettingsSchema
    /// 5. **Event iteration** - Validate each event and hook (CC-HK-015, CC-HK-017, CC-HK-018)
    fn validate(&self, path: &Path, content: &str, config: &LintConfig) -> Vec<Diagnostic> {
        let mut diagnostics = Vec::new();

        if !config.rules().hooks {
            return diagnostics;
        }

        let raw_value: serde_json::Value = match serde_json::from_str(content) {
            Ok(v) => v,
            Err(e) => {
                if config.is_rule_enabled("CC-HK-012") {
                    diagnostics.push(
                        Diagnostic::error(
                            path.to_path_buf(),
                            1,
                            0,
                            "CC-HK-012",
                            t!("rules.cc_hk_012.message", error = e.to_string()),
                        )
                        .with_suggestion(t!("rules.cc_hk_012.suggestion")),
                    );
                }
                return diagnostics;
            }
        };

        // Raw JSON validation: CC-HK-005, 011, 013, 014, 016, 020-025.
        // Single consolidated traversal (2 passes max instead of 11).
        if !validate_all_raw_hooks(&raw_value, path, content, config, &mut diagnostics) {
            return diagnostics;
        }

        let settings: SettingsSchema = match serde_json::from_value(raw_value) {
            Ok(s) => s,
            Err(e) => {
                if config.is_rule_enabled("CC-HK-012") {
                    diagnostics.push(
                        Diagnostic::error(
                            path.to_path_buf(),
                            1,
                            0,
                            "CC-HK-012",
                            t!("rules.cc_hk_012.message", error = e.to_string()),
                        )
                        .with_suggestion(t!("rules.cc_hk_012.suggestion")),
                    );
                }
                return diagnostics;
            }
        };

        let project_dir = path
            .parent()
            .and_then(|p| {
                if p.ends_with(".claude") {
                    p.parent()
                } else {
                    Some(p)
                }
            })
            .unwrap_or_else(|| Path::new("."));

        for (event, matchers) in &settings.hooks {
            // --- Event-level validation ---
            // CC-HK-001: Invalid event name
            if config.is_rule_enabled("CC-HK-001") {
                if !validate_cc_hk_001_event_name(event, path, content, &mut diagnostics) {
                    continue;
                }
            } else if !HooksSchema::VALID_EVENTS.contains(&event.as_str()) {
                continue; // Skip invalid events even if rule disabled
            }

            // CC-HK-019: Deprecated event name
            if config.is_rule_enabled("CC-HK-019") {
                validate_cc_hk_019_deprecated_event(event, path, content, &mut diagnostics);
            }

            for (matcher_idx, matcher) in matchers.iter().enumerate() {
                // --- Matcher-level validation ---
                // CC-HK-003: Matcher hint for tool events
                if config.is_rule_enabled("CC-HK-003") {
                    validate_cc_hk_003_matcher_hint(
                        event,
                        &matcher.matcher,
                        matcher_idx,
                        path,
                        &mut diagnostics,
                    );
                }

                // CC-HK-004: Matcher on non-tool event
                if config.is_rule_enabled("CC-HK-004") {
                    validate_cc_hk_004_matcher_forbidden(
                        event,
                        &matcher.matcher,
                        matcher_idx,
                        path,
                        content,
                        &mut diagnostics,
                    );
                }

                // CC-HK-018: Matcher on UserPromptSubmit/Stop
                if config.is_rule_enabled("CC-HK-018") {
                    validate_cc_hk_018_matcher_ignored(
                        event,
                        &matcher.matcher,
                        matcher_idx,
                        path,
                        content,
                        &mut diagnostics,
                    );
                }

                // --- Hook-level validation ---
                for (hook_idx, hook) in matcher.hooks.iter().enumerate() {
                    let hook_location = format!(
                        "hooks.{}{}.hooks[{}]",
                        event,
                        matcher
                            .matcher
                            .as_ref()
                            .map(|m| format!("[matcher={}]", m))
                            .unwrap_or_else(|| format!("[{}]", matcher_idx)),
                        hook_idx
                    );

                    match hook {
                        Hook::Command {
                            command,
                            timeout,
                            model,
                            ..
                        } => {
                            // CC-HK-010: Command timeout policy
                            if config.is_rule_enabled("CC-HK-010") {
                                validate_cc_hk_010_command_timeout(
                                    timeout,
                                    &hook_location,
                                    config.is_claude_code_version_pinned(),
                                    path,
                                    &mut diagnostics,
                                );
                            }

                            // CC-HK-006: Missing command field
                            if config.is_rule_enabled("CC-HK-006") {
                                validate_cc_hk_006_command_field(
                                    command,
                                    &hook_location,
                                    path,
                                    &mut diagnostics,
                                );
                            }

                            // CC-HK-015: Model on command hook
                            if config.is_rule_enabled("CC-HK-015") && model.is_some() {
                                validate_cc_hk_015_model_on_command(
                                    &hook_location,
                                    path,
                                    content,
                                    &mut diagnostics,
                                );
                            }

                            if let Some(cmd) = command {
                                // CC-HK-008: Script file not found
                                if config.is_rule_enabled("CC-HK-008") {
                                    validate_cc_hk_008_script_exists(
                                        cmd,
                                        project_dir,
                                        config,
                                        path,
                                        &mut diagnostics,
                                    );
                                }

                                // CC-HK-009: Dangerous command patterns
                                if config.is_rule_enabled("CC-HK-009") {
                                    validate_cc_hk_009_dangerous_patterns(
                                        cmd,
                                        path,
                                        &mut diagnostics,
                                    );
                                }
                            }
                        }
                        Hook::Prompt {
                            prompt, timeout, ..
                        } => {
                            // CC-HK-010: Prompt timeout policy
                            if config.is_rule_enabled("CC-HK-010") {
                                validate_cc_hk_010_prompt_timeout(
                                    timeout,
                                    &hook_location,
                                    config.is_claude_code_version_pinned(),
                                    path,
                                    &mut diagnostics,
                                );
                            }

                            // CC-HK-002: Prompt on wrong event
                            if config.is_rule_enabled("CC-HK-002") {
                                validate_cc_hk_002_prompt_event_type(
                                    event,
                                    &hook_location,
                                    path,
                                    &mut diagnostics,
                                );
                            }

                            // CC-HK-007: Missing prompt field
                            if config.is_rule_enabled("CC-HK-007") {
                                validate_cc_hk_007_prompt_field(
                                    prompt,
                                    &hook_location,
                                    path,
                                    &mut diagnostics,
                                );
                            }

                            // CC-HK-017: Prompt hook missing $ARGUMENTS
                            if config.is_rule_enabled("CC-HK-017") {
                                if let Some(p) = prompt {
                                    validate_cc_hk_017_prompt_arguments(
                                        p,
                                        &hook_location,
                                        path,
                                        &mut diagnostics,
                                    );
                                }
                            }
                        }
                        Hook::Agent {
                            prompt, timeout, ..
                        } => {
                            // CC-HK-010: Agent timeout policy (same as prompt)
                            if config.is_rule_enabled("CC-HK-010") {
                                validate_cc_hk_010_prompt_timeout(
                                    timeout,
                                    &hook_location,
                                    config.is_claude_code_version_pinned(),
                                    path,
                                    &mut diagnostics,
                                );
                            }

                            // CC-HK-002: Agent hook on wrong event (same restriction as prompt)
                            if config.is_rule_enabled("CC-HK-002") {
                                validate_cc_hk_002_prompt_event_type(
                                    event,
                                    &hook_location,
                                    path,
                                    &mut diagnostics,
                                );
                            }

                            // CC-HK-007: Missing prompt field
                            if config.is_rule_enabled("CC-HK-007") {
                                validate_cc_hk_007_prompt_field(
                                    prompt,
                                    &hook_location,
                                    path,
                                    &mut diagnostics,
                                );
                            }

                            // CC-HK-017: Agent hook missing $ARGUMENTS
                            if config.is_rule_enabled("CC-HK-017") {
                                if let Some(p) = prompt {
                                    validate_cc_hk_017_prompt_arguments(
                                        p,
                                        &hook_location,
                                        path,
                                        &mut diagnostics,
                                    );
                                }
                            }
                        }
                        Hook::Http { .. } => {
                            // HTTP hooks are validated at the raw JSON level:
                            // CC-HK-005 type check, CC-HK-011 timeout, CC-HK-016 type validation,
                            // CC-HK-020 url validation, CC-HK-024 headers env vars.
                            // No additional typed validation needed here.
                        }
                        Hook::McpTool { .. } => {
                            // MCP tool hooks (added Claude Code v2.1.118) are
                            // validated at the raw JSON level via CC-HK-016
                            // (string allow-list). Schema details for required
                            // fields are not yet documented at
                            // code.claude.com/docs/en/hooks (as of 2026-04-23);
                            // re-tighten when upstream docs land.
                        }
                    }
                }
            }
        }

        diagnostics
    }
}

#[cfg(test)]
mod tests;