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
//! Kiro POWER.md validation rules (KR-PW-001 to KR-PW-008).
//!
//! Validates:
//! - KR-PW-001: Missing required POWER.md frontmatter fields
//! - KR-PW-002: Empty POWER.md keywords array
//! - KR-PW-003: Empty POWER.md body
//! - KR-PW-004: Adjacent power mcp.json has invalid mcpServers structure
//! - KR-PW-005: Step missing description
//! - KR-PW-006: Duplicate keywords
//! - KR-PW-007: Name invalid characters
//! - KR-PW-008: Secrets in power body

use crate::{
    config::LintConfig,
    diagnostics::Diagnostic,
    rules::{Validator, ValidatorMetadata, seems_plaintext_secret},
    schemas::{kiro_mcp::parse_kiro_mcp_config, kiro_power::parse_kiro_power},
};
use regex::Regex;
use rust_i18n::t;
use std::collections::HashSet;
use std::path::Path;
use std::sync::OnceLock;

const RULE_IDS: &[&str] = &[
    "KR-PW-001",
    "KR-PW-002",
    "KR-PW-003",
    "KR-PW-004",
    "KR-PW-005",
    "KR-PW-006",
    "KR-PW-007",
    "KR-PW-008",
];

fn power_name_pattern() -> &'static Regex {
    static RE: OnceLock<Regex> = OnceLock::new();
    RE.get_or_init(|| {
        Regex::new(r"^[a-z0-9][a-z0-9_-]*$").expect("power name pattern must compile")
    })
}

fn power_secret_pattern() -> &'static Regex {
    static RE: OnceLock<Regex> = OnceLock::new();
    RE.get_or_init(|| {
        Regex::new(
            r"(?im)\b(?:api[_-]?key|token|password|[a-z0-9_-]+secret|secret[a-z0-9_-]+)\b\s*[:=]\s*(?P<value>[^\s#]+)",
        )
        .expect("power secret pattern must compile")
    })
}

pub struct KiroPowerValidator;

impl Validator for KiroPowerValidator {
    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();
        let parsed = parse_kiro_power(content);

        if config.is_rule_enabled("KR-PW-001") {
            if !parsed.has_frontmatter {
                diagnostics.push(
                    Diagnostic::error(
                        path.to_path_buf(),
                        1,
                        0,
                        "KR-PW-001",
                        t!(
                            "rules.kr_pw_001.message",
                            fields = "name, description, keywords"
                        ),
                    )
                    .with_suggestion(t!("rules.kr_pw_001.suggestion")),
                );
            } else if let Some(parse_error) = parsed.parse_error.as_ref() {
                diagnostics.push(
                    Diagnostic::error(
                        path.to_path_buf(),
                        parse_error.line,
                        parse_error.column,
                        "KR-PW-001",
                        t!(
                            "rules.kr_pw_001_parse.message",
                            error = parse_error.message.as_str()
                        ),
                    )
                    .with_suggestion(t!("rules.kr_pw_001_parse.suggestion")),
                );
            } else if let Some(frontmatter) = parsed.frontmatter.as_ref() {
                let mut missing = Vec::new();
                if frontmatter.name.as_deref().is_none()
                    || frontmatter
                        .name
                        .as_deref()
                        .is_some_and(|value| value.trim().is_empty())
                {
                    missing.push("name");
                }
                if frontmatter.description.as_deref().is_none()
                    || frontmatter
                        .description
                        .as_deref()
                        .is_some_and(|value| value.trim().is_empty())
                {
                    missing.push("description");
                }
                if frontmatter.keywords.is_none() {
                    missing.push("keywords");
                }

                if !missing.is_empty() {
                    diagnostics.push(
                        Diagnostic::error(
                            path.to_path_buf(),
                            1,
                            0,
                            "KR-PW-001",
                            t!("rules.kr_pw_001.message", fields = missing.join(", ")),
                        )
                        .with_suggestion(t!("rules.kr_pw_001.suggestion")),
                    );
                }
            }
        }

        if config.is_rule_enabled("KR-PW-002")
            && let Some(frontmatter) = parsed.frontmatter.as_ref()
            && let Some(keywords) = frontmatter.keywords.as_ref()
            && keywords.is_empty()
        {
            diagnostics.push(
                Diagnostic::warning(
                    path.to_path_buf(),
                    1,
                    0,
                    "KR-PW-002",
                    t!("rules.kr_pw_002.message"),
                )
                .with_suggestion(t!("rules.kr_pw_002.suggestion")),
            );
        }

        if config.is_rule_enabled("KR-PW-003")
            && parsed.has_frontmatter
            && parsed.has_closing_frontmatter
            && parsed.parse_error.is_none()
            && parsed.body.trim().is_empty()
        {
            diagnostics.push(
                Diagnostic::warning(
                    path.to_path_buf(),
                    1,
                    0,
                    "KR-PW-003",
                    t!("rules.kr_pw_003.message"),
                )
                .with_suggestion(t!("rules.kr_pw_003.suggestion")),
            );
        }

        if config.is_rule_enabled("KR-PW-004")
            && let Some(power_dir) = path.parent()
        {
            let mcp_path = power_dir.join("mcp.json");
            let fs = config.fs();
            if fs.exists(&mcp_path) {
                match fs.read_to_string(&mcp_path) {
                    Ok(mcp_content) => {
                        let parsed_mcp = parse_kiro_mcp_config(&mcp_content);
                        let invalid_structure = parsed_mcp.parse_error.is_some()
                            || parsed_mcp
                                .config
                                .as_ref()
                                .and_then(|cfg| cfg.mcp_servers.as_ref())
                                .is_none();

                        if invalid_structure {
                            diagnostics.push(
                                Diagnostic::warning(
                                    path.to_path_buf(),
                                    1,
                                    0,
                                    "KR-PW-004",
                                    t!("rules.kr_pw_004.message"),
                                )
                                .with_suggestion(t!("rules.kr_pw_004.suggestion")),
                            );
                        }
                    }
                    Err(_) => {
                        diagnostics.push(
                            Diagnostic::warning(
                                path.to_path_buf(),
                                1,
                                0,
                                "KR-PW-004",
                                t!("rules.kr_pw_004.message"),
                            )
                            .with_suggestion(t!("rules.kr_pw_004.suggestion")),
                        );
                    }
                }
            }
        }

        // KR-PW-005: Step missing description (empty heading section in body)
        // Intentionally checks only ## headings - Kiro power files use ## for steps
        // per Kiro convention. Higher/lower heading levels are not step markers.
        if config.is_rule_enabled("KR-PW-005")
            && parsed.has_frontmatter
            && parsed.parse_error.is_none()
        {
            let body = parsed.body.trim();
            // Collected into Vec intentionally for look-ahead (checking next headings).
            // Power files are small, so the allocation is negligible.
            let lines: Vec<&str> = body.lines().collect();
            for (i, line) in lines.iter().enumerate() {
                if line.starts_with("## ") {
                    // Check if the next non-empty line is another heading or end of file
                    let has_content = lines[i + 1..]
                        .iter()
                        .take_while(|l| !l.starts_with("## "))
                        .any(|l| !l.trim().is_empty());
                    if !has_content {
                        diagnostics.push(
                            Diagnostic::error(
                                path.to_path_buf(),
                                1,
                                0,
                                "KR-PW-005",
                                t!("rules.kr_pw_005.message", step = line.trim()),
                            )
                            .with_suggestion(t!("rules.kr_pw_005.suggestion")),
                        );
                    }
                }
            }
        }

        // KR-PW-006: Duplicate keywords
        if config.is_rule_enabled("KR-PW-006")
            && let Some(frontmatter) = parsed.frontmatter.as_ref()
            && let Some(keywords) = frontmatter.keywords.as_ref()
        {
            let mut seen = HashSet::new();
            for keyword in keywords {
                let normalized = keyword.trim().to_ascii_lowercase();
                if !normalized.is_empty() && !seen.insert(normalized) {
                    diagnostics.push(
                        Diagnostic::info(
                            path.to_path_buf(),
                            1,
                            0,
                            "KR-PW-006",
                            t!("rules.kr_pw_006.message", keyword = keyword.as_str()),
                        )
                        .with_suggestion(t!("rules.kr_pw_006.suggestion")),
                    );
                }
            }
        }

        // KR-PW-007: Name invalid characters
        if config.is_rule_enabled("KR-PW-007")
            && let Some(frontmatter) = parsed.frontmatter.as_ref()
            && let Some(name) = frontmatter.name.as_deref()
            && !name.trim().is_empty()
        {
            if !power_name_pattern().is_match(name.trim()) {
                diagnostics.push(
                    Diagnostic::warning(
                        path.to_path_buf(),
                        1,
                        0,
                        "KR-PW-007",
                        t!("rules.kr_pw_007.message", name = name.trim()),
                    )
                    .with_suggestion(t!("rules.kr_pw_007.suggestion")),
                );
            }
        }

        // KR-PW-008: Secrets in power body
        if config.is_rule_enabled("KR-PW-008")
            && parsed.has_frontmatter
            && parsed.parse_error.is_none()
        {
            let body = &parsed.body;
            for captures in power_secret_pattern().captures_iter(body) {
                let value = captures
                    .name("value")
                    .map(|m| m.as_str())
                    .unwrap_or_default();
                if seems_plaintext_secret(value) {
                    diagnostics.push(
                        Diagnostic::error(
                            path.to_path_buf(),
                            1,
                            0,
                            "KR-PW-008",
                            t!("rules.kr_pw_008.message"),
                        )
                        .with_suggestion(t!("rules.kr_pw_008.suggestion")),
                    );
                    break;
                }
            }
        }

        diagnostics
    }
}

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

    fn validate(content: &str) -> Vec<Diagnostic> {
        let validator = KiroPowerValidator;
        validator.validate(
            Path::new(".kiro/powers/test-power/POWER.md"),
            content,
            &LintConfig::default(),
        )
    }

    #[test]
    fn test_kr_pw_001_missing_frontmatter() {
        let diagnostics = validate("# Missing frontmatter");
        assert!(diagnostics.iter().any(|d| d.rule == "KR-PW-001"));
    }

    #[test]
    fn test_kr_pw_001_missing_required_fields() {
        let diagnostics = validate(
            r#"---
name: sample
---
# Sample
"#,
        );
        assert!(diagnostics.iter().any(|d| d.rule == "KR-PW-001"));
    }

    #[test]
    fn test_kr_pw_002_empty_keywords() {
        let diagnostics = validate(
            r#"---
name: empty-keywords
description: test
keywords: []
---
# Body
"#,
        );
        assert!(diagnostics.iter().any(|d| d.rule == "KR-PW-002"));
    }

    #[test]
    fn test_kr_pw_003_empty_body() {
        let diagnostics = validate(
            r#"---
name: empty-body
description: test
keywords:
  - one
---
"#,
        );
        assert!(diagnostics.iter().any(|d| d.rule == "KR-PW-003"));
    }

    #[test]
    fn test_kr_pw_004_invalid_adjacent_mcp() {
        let temp = tempfile::TempDir::new().unwrap();
        let power_dir = temp.path().join(".kiro").join("powers").join("bad");
        fs::create_dir_all(&power_dir).unwrap();

        let power_path = power_dir.join("POWER.md");
        fs::write(
            &power_path,
            r#"---
name: bad
description: test
keywords:
  - one
---
# Body
"#,
        )
        .unwrap();
        fs::write(power_dir.join("mcp.json"), r#"{"mcpServers":[]}"#).unwrap();

        let validator = KiroPowerValidator;
        let content = fs::read_to_string(&power_path).unwrap();
        let diagnostics = validator.validate(&power_path, &content, &LintConfig::default());
        assert!(diagnostics.iter().any(|d| d.rule == "KR-PW-004"));
    }

    #[test]
    fn test_kr_pw_004_allows_empty_mcp_servers_object() {
        let temp = tempfile::TempDir::new().unwrap();
        let power_dir = temp.path().join(".kiro").join("powers").join("ok");
        fs::create_dir_all(&power_dir).unwrap();

        let power_path = power_dir.join("POWER.md");
        fs::write(
            &power_path,
            r#"---
name: ok
description: test
keywords:
  - one
---
# Body
"#,
        )
        .unwrap();
        fs::write(power_dir.join("mcp.json"), r#"{"mcpServers":{}}"#).unwrap();

        let validator = KiroPowerValidator;
        let content = fs::read_to_string(&power_path).unwrap();
        let diagnostics = validator.validate(&power_path, &content, &LintConfig::default());
        assert!(!diagnostics.iter().any(|d| d.rule == "KR-PW-004"));
    }

    #[test]
    fn test_valid_power_has_no_pw_diagnostics() {
        let diagnostics = validate(
            r#"---
name: valid
description: test
keywords:
  - kiro
---
# Body
Valid content.
"#,
        );
        assert!(diagnostics.iter().all(|d| !d.rule.starts_with("KR-PW-")));
    }

    #[test]
    fn test_kr_pw_005_step_missing_description() {
        let diagnostics = validate(
            r#"---
name: empty-step
description: test
keywords:
  - one
---
## Step 1
## Step 2
Some content here.
"#,
        );
        assert!(diagnostics.iter().any(|d| d.rule == "KR-PW-005"));
    }

    #[test]
    fn test_kr_pw_005_step_with_description_no_diagnostic() {
        let diagnostics = validate(
            r#"---
name: good-steps
description: test
keywords:
  - one
---
## Step 1
This step does something.
## Step 2
This step does another thing.
"#,
        );
        assert!(diagnostics.iter().all(|d| d.rule != "KR-PW-005"));
    }

    #[test]
    fn test_kr_pw_006_duplicate_keywords() {
        let diagnostics = validate(
            r#"---
name: dupes
description: test
keywords:
  - foo
  - bar
  - foo
---
# Body
"#,
        );
        assert!(diagnostics.iter().any(|d| d.rule == "KR-PW-006"));
    }

    #[test]
    fn test_kr_pw_006_unique_keywords_no_diagnostic() {
        let diagnostics = validate(
            r#"---
name: unique
description: test
keywords:
  - foo
  - bar
---
# Body
"#,
        );
        assert!(diagnostics.iter().all(|d| d.rule != "KR-PW-006"));
    }

    #[test]
    fn test_kr_pw_007_invalid_name_characters() {
        let diagnostics = validate(
            r#"---
name: My Power!
description: test
keywords:
  - one
---
# Body
"#,
        );
        assert!(diagnostics.iter().any(|d| d.rule == "KR-PW-007"));
    }

    #[test]
    fn test_kr_pw_007_valid_name_no_diagnostic() {
        let diagnostics = validate(
            r#"---
name: my-power-1
description: test
keywords:
  - one
---
# Body
"#,
        );
        assert!(diagnostics.iter().all(|d| d.rule != "KR-PW-007"));
    }

    #[test]
    fn test_kr_pw_008_secrets_in_body() {
        let diagnostics = validate(
            r#"---
name: secrets
description: test
keywords:
  - one
---
Configure with api_key= hardcodedsecret123value
"#,
        );
        assert!(diagnostics.iter().any(|d| d.rule == "KR-PW-008"));
    }

    #[test]
    fn test_kr_pw_008_no_secrets_no_diagnostic() {
        let diagnostics = validate(
            r#"---
name: clean
description: test
keywords:
  - one
---
# Body
Normal instructions here.
"#,
        );
        assert!(diagnostics.iter().all(|d| d.rule != "KR-PW-008"));
    }

    #[test]
    fn test_kr_pw_006_case_insensitive_duplicate_keywords() {
        let diagnostics = validate(
            r#"---
name: case-dupes
description: test
keywords:
  - foo
  - Foo
---
# Body
"#,
        );
        assert!(diagnostics.iter().any(|d| d.rule == "KR-PW-006"));
    }

    #[test]
    fn test_kr_pw_008_template_values_not_flagged() {
        let diagnostics = validate(
            r#"---
name: template
description: test
keywords:
  - one
---
Configure with api_key= ${API_KEY}
"#,
        );
        assert!(diagnostics.iter().all(|d| d.rule != "KR-PW-008"));
    }

    // M14: KR-PW-005 step at end of body with no content after
    #[test]
    fn test_kr_pw_005_step_at_end_of_body() {
        let diagnostics = validate(
            r#"---
name: end-step
description: test
keywords:
  - one
---
## Step 1
"#,
        );
        assert!(diagnostics.iter().any(|d| d.rule == "KR-PW-005"));
    }

    // L4: KR-PW-007 valid kebab-case name should not trigger
    #[test]
    fn test_kr_pw_007_valid_kebab_case_no_diagnostic() {
        let diagnostics = validate(
            r#"---
name: my-power-test-123
description: test
keywords:
  - one
---
# Body
"#,
        );
        assert!(diagnostics.iter().all(|d| d.rule != "KR-PW-007"));
    }

    #[test]
    fn test_metadata() {
        let validator = KiroPowerValidator;
        let metadata = validator.metadata();
        assert_eq!(metadata.name, "KiroPowerValidator");
        assert_eq!(
            metadata.rule_ids,
            &[
                "KR-PW-001",
                "KR-PW-002",
                "KR-PW-003",
                "KR-PW-004",
                "KR-PW-005",
                "KR-PW-006",
                "KR-PW-007",
                "KR-PW-008",
            ]
        );
    }
}