agnix-core 0.21.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
//! `.claude/rules/*.md` frontmatter validation rules (CC-MEM-011, CC-MEM-012)
//!
//! Validates:
//! - CC-MEM-011: Invalid paths glob in rules (HIGH) - glob patterns must be valid
//! - CC-MEM-012: Rules file unknown frontmatter key (MEDIUM) - only `paths` is known

use crate::{
    config::LintConfig,
    diagnostics::{Diagnostic, Fix},
    rules::{Validator, ValidatorMetadata},
    schemas::claude_rules::{parse_frontmatter, validate_glob_pattern},
};
use rust_i18n::t;
use std::path::Path;

const RULE_IDS: &[&str] = &["CC-MEM-011", "CC-MEM-012"];

pub struct ClaudeRulesValidator;

fn line_byte_range(content: &str, line_number: usize) -> Option<(usize, usize)> {
    if line_number == 0 {
        return None;
    }

    let mut current_line = 1usize;
    let mut line_start = 0usize;

    for (idx, ch) in content.char_indices() {
        if current_line == line_number && ch == '\n' {
            return Some((line_start, idx + 1));
        }
        if ch == '\n' {
            current_line += 1;
            line_start = idx + 1;
        }
    }

    if current_line == line_number {
        Some((line_start, content.len()))
    } else {
        None
    }
}

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

    fn validate(&self, path: &Path, content: &str, config: &LintConfig) -> Vec<Diagnostic> {
        let mut diagnostics = Vec::new();

        // Only validate .claude/rules/*.md files
        let parent = path
            .parent()
            .and_then(|p| p.file_name())
            .and_then(|n| n.to_str());
        let grandparent = path
            .parent()
            .and_then(|p| p.parent())
            .and_then(|p| p.file_name())
            .and_then(|n| n.to_str());

        if parent != Some("rules") || grandparent != Some(".claude") {
            return diagnostics;
        }

        // Parse frontmatter - if no frontmatter, nothing to validate
        let parsed = match parse_frontmatter(content) {
            Some(p) => p,
            None => return diagnostics,
        };

        // If there's a parse error, emit a diagnostic and return early
        if let Some(ref parse_error) = parsed.parse_error {
            diagnostics.push(
                Diagnostic::error(
                    path.to_path_buf(),
                    parsed.start_line,
                    0,
                    "CC-MEM-011",
                    format!("Invalid frontmatter: {}", parse_error),
                )
                .with_suggestion("Close frontmatter with a line containing only `---`."),
            );
            return diagnostics;
        }

        // CC-MEM-011: Invalid paths glob in rules (ERROR)
        if config.is_rule_enabled("CC-MEM-011") {
            if let Some(ref schema) = parsed.schema {
                for (i, pattern) in schema.paths.iter().enumerate() {
                    let validation = validate_glob_pattern(pattern);
                    if !validation.valid {
                        // Try to find the line number of this pattern in the frontmatter
                        let line = find_pattern_line(&parsed.raw, pattern, parsed.start_line)
                            .unwrap_or(parsed.start_line + 1);

                        diagnostics.push(
                            Diagnostic::error(
                                path.to_path_buf(),
                                line,
                                0,
                                "CC-MEM-011",
                                t!(
                                    "rules.cc_mem_011.message",
                                    pattern = pattern.as_str(),
                                    error = validation.error.unwrap_or_default(),
                                    index = i + 1
                                ),
                            )
                            .with_suggestion(t!("rules.cc_mem_011.suggestion")),
                        );
                    }
                }
            }
        }

        // CC-MEM-012: Unknown frontmatter keys (WARNING)
        if config.is_rule_enabled("CC-MEM-012") {
            for unknown in &parsed.unknown_keys {
                let mut diagnostic = Diagnostic::warning(
                    path.to_path_buf(),
                    unknown.line,
                    unknown.column,
                    "CC-MEM-012",
                    t!("rules.cc_mem_012.message", key = unknown.key.as_str()),
                )
                .with_suggestion(t!(
                    "rules.cc_mem_012.suggestion",
                    key = unknown.key.as_str()
                ));

                // Auto-fix: remove unknown top-level frontmatter key line.
                // Marked unsafe because the key's value may span multiple lines
                // (e.g. block scalars, nested maps) and we only delete the key line.
                if let Some((start, end)) = line_byte_range(content, unknown.line) {
                    diagnostic = diagnostic.with_fix(Fix::delete(
                        start,
                        end,
                        format!("Remove unknown frontmatter key '{}'", unknown.key),
                        false,
                    ));
                }

                diagnostics.push(diagnostic);
            }
        }

        diagnostics
    }
}

/// Find the line number of a pattern in the raw frontmatter
///
/// Matches YAML list items precisely by stripping the leading `- ` prefix
/// and surrounding quotes, avoiding false matches when one pattern is a
/// substring of another.
fn find_pattern_line(raw: &str, pattern: &str, start_line: usize) -> Option<usize> {
    for (i, line) in raw.lines().enumerate() {
        if let Some(value_part) = line.trim().strip_prefix('-') {
            let value = value_part.trim();
            let value_unquoted = value.trim_matches(|c| c == '\'' || c == '"');
            if value_unquoted == pattern {
                return Some(start_line + 1 + i);
            }
        }
    }
    None
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::LintConfig;
    use crate::diagnostics::DiagnosticLevel;

    fn validate_rule(content: &str) -> Vec<Diagnostic> {
        let validator = ClaudeRulesValidator;
        validator.validate(
            Path::new(".claude/rules/my-rule.md"),
            content,
            &LintConfig::default(),
        )
    }

    fn validate_rule_with_config(content: &str, config: &LintConfig) -> Vec<Diagnostic> {
        let validator = ClaudeRulesValidator;
        validator.validate(Path::new(".claude/rules/my-rule.md"), content, config)
    }

    // ===== CC-MEM-011: Invalid Paths Glob =====

    #[test]
    fn test_cc_mem_011_invalid_glob() {
        let content = r#"---
paths:
  - "[unclosed"
---
# Rule content
"#;
        let diagnostics = validate_rule(content);
        let mem_011: Vec<_> = diagnostics
            .iter()
            .filter(|d| d.rule == "CC-MEM-011")
            .collect();
        assert_eq!(mem_011.len(), 1);
        assert_eq!(mem_011[0].level, DiagnosticLevel::Error);
        assert!(mem_011[0].message.contains("[unclosed"));
    }

    #[test]
    fn test_cc_mem_011_multiple_invalid_globs() {
        let content = r#"---
paths:
  - "[bad1"
  - "**/*.ts"
  - "[bad2"
---
# Rule content
"#;
        let diagnostics = validate_rule(content);
        let mem_011: Vec<_> = diagnostics
            .iter()
            .filter(|d| d.rule == "CC-MEM-011")
            .collect();
        assert_eq!(mem_011.len(), 2);
    }

    #[test]
    fn test_cc_mem_011_valid_globs() {
        let patterns = vec![
            "**/*.ts",
            "*.rs",
            "src/**/*.js",
            "tests/**/*.test.ts",
            "{src,lib}/**/*.ts",
        ];

        for pattern in patterns {
            let content = format!(
                r#"---
paths:
  - "{}"
---
# Rule content
"#,
                pattern
            );
            let diagnostics = validate_rule(&content);
            let mem_011: Vec<_> = diagnostics
                .iter()
                .filter(|d| d.rule == "CC-MEM-011")
                .collect();
            assert!(mem_011.is_empty(), "Pattern '{}' should be valid", pattern);
        }
    }

    #[test]
    fn test_cc_mem_011_no_frontmatter() {
        let content = "# Rule without frontmatter\n\nSome instructions.";
        let diagnostics = validate_rule(content);
        let mem_011: Vec<_> = diagnostics
            .iter()
            .filter(|d| d.rule == "CC-MEM-011")
            .collect();
        assert!(mem_011.is_empty());
    }

    #[test]
    fn test_cc_mem_011_empty_paths() {
        let content = "---\npaths: []\n---\n# Content";
        let diagnostics = validate_rule(content);
        let mem_011: Vec<_> = diagnostics
            .iter()
            .filter(|d| d.rule == "CC-MEM-011")
            .collect();
        assert!(mem_011.is_empty());
    }

    #[test]
    fn test_cc_mem_011_unclosed_frontmatter() {
        let content = "---\npaths:\n  - \"src/**/*.ts\"";
        let diagnostics = validate_rule(content);
        let mem_011: Vec<_> = diagnostics
            .iter()
            .filter(|d| d.rule == "CC-MEM-011")
            .collect();
        assert_eq!(mem_011.len(), 1);
        assert!(mem_011[0].message.contains("missing closing ---"));
    }

    // ===== CC-MEM-012: Unknown Frontmatter Keys =====

    #[test]
    fn test_cc_mem_012_unknown_keys() {
        let content = r#"---
paths:
  - "src/**/*.ts"
description: "some rule"
alwaysApply: true
---
# Content
"#;
        let diagnostics = validate_rule(content);
        let mem_012: Vec<_> = diagnostics
            .iter()
            .filter(|d| d.rule == "CC-MEM-012")
            .collect();
        assert_eq!(mem_012.len(), 2);
        assert_eq!(mem_012[0].level, DiagnosticLevel::Warning);
        assert!(mem_012.iter().any(|d| d.message.contains("description")));
        assert!(mem_012.iter().any(|d| d.message.contains("alwaysApply")));
    }

    #[test]
    fn test_cc_mem_012_has_autofix() {
        let content = r#"---
paths:
  - "src/**/*.ts"
description: "some rule"
---
# Content
"#;
        let diagnostics = validate_rule(content);
        let mem_012: Vec<_> = diagnostics
            .iter()
            .filter(|d| d.rule == "CC-MEM-012")
            .collect();
        assert_eq!(mem_012.len(), 1);
        assert!(mem_012[0].has_fixes());
        assert!(!mem_012[0].fixes[0].safe); // Unsafe: single-line delete may miss multi-line values
        assert!(mem_012[0].fixes[0].is_deletion());
    }

    #[test]
    fn test_cc_mem_012_no_unknown_keys() {
        let content = r#"---
paths:
  - "src/**/*.ts"
---
# Content
"#;
        let diagnostics = validate_rule(content);
        let mem_012: Vec<_> = diagnostics
            .iter()
            .filter(|d| d.rule == "CC-MEM-012")
            .collect();
        assert!(mem_012.is_empty());
    }

    #[test]
    fn test_cc_mem_012_no_frontmatter() {
        let content = "# Rule without frontmatter";
        let diagnostics = validate_rule(content);
        let mem_012: Vec<_> = diagnostics
            .iter()
            .filter(|d| d.rule == "CC-MEM-012")
            .collect();
        assert!(mem_012.is_empty());
    }

    // ===== Path Guard =====

    #[test]
    fn test_wrong_path_no_diagnostics() {
        let validator = ClaudeRulesValidator;
        let content = r#"---
unknownKey: value
---
# Content
"#;
        // Not in .claude/rules/ path
        let diagnostics = validator.validate(
            Path::new("some/other/path.md"),
            content,
            &LintConfig::default(),
        );
        assert!(diagnostics.is_empty());
    }

    #[test]
    fn test_claude_rules_path() {
        let validator = ClaudeRulesValidator;
        let content = r#"---
unknownKey: value
---
# Content
"#;
        let diagnostics = validator.validate(
            Path::new(".claude/rules/my-rule.md"),
            content,
            &LintConfig::default(),
        );
        assert!(!diagnostics.is_empty());
    }

    // ===== Config Integration =====

    #[test]
    fn test_config_disabled_memory_category() {
        let mut config = LintConfig::default();
        config.rules_mut().memory = false;

        let content = r#"---
unknownKey: value
paths:
  - "[invalid"
---
# Content
"#;
        let diagnostics = validate_rule_with_config(content, &config);
        assert!(diagnostics.is_empty());
    }

    #[test]
    fn test_config_disabled_specific_rules() {
        let rules = ["CC-MEM-011", "CC-MEM-012"];

        for rule in rules {
            let mut config = LintConfig::default();
            config.rules_mut().disabled_rules = vec![rule.to_string()];

            let content = r#"---
unknownKey: value
paths:
  - "[invalid"
---
# Content
"#;
            let diagnostics = validate_rule_with_config(content, &config);

            assert!(
                !diagnostics.iter().any(|d| d.rule == rule),
                "Rule {} should be disabled",
                rule
            );
        }
    }

    // ===== Combined Issues =====

    #[test]
    fn test_both_rules_trigger() {
        let content = r#"---
paths:
  - "[invalid"
unknownKey: value
---
# Content
"#;
        let diagnostics = validate_rule(content);
        assert!(
            diagnostics.iter().any(|d| d.rule == "CC-MEM-011"),
            "Expected CC-MEM-011"
        );
        assert!(
            diagnostics.iter().any(|d| d.rule == "CC-MEM-012"),
            "Expected CC-MEM-012"
        );
    }

    #[test]
    fn test_valid_rule_file_no_issues() {
        let content = r#"---
paths:
  - "src/**/*.ts"
  - "lib/**/*.js"
---
# TypeScript Guidelines

Always use strict mode and explicit types.
"#;
        let diagnostics = validate_rule(content);
        assert!(
            diagnostics.is_empty(),
            "Expected no diagnostics, got: {:?}",
            diagnostics
        );
    }
}