godmode-core 0.8.1

Core library for godmode: task graphs, session state, dispatch, and Claude Code plugin integrations.
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
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
//! Conformance checks for skills, agents, plugin metadata, and library references.

use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;

use anyhow::{Context, Result};

#[derive(Debug, serde::Serialize, PartialEq)]
pub enum Severity {
    Blocking,
    Suggestion,
    Nitpick,
}

#[derive(Debug, serde::Serialize)]
pub struct Finding {
    pub skill: String,
    pub check: String,
    pub message: String,
    pub severity: Severity,
}

#[derive(Debug, serde::Serialize)]
pub struct ReviewReport {
    pub checks: u32,
    pub findings: Vec<Finding>,
    pub passed: bool,
}

impl ReviewReport {
    fn new() -> Self {
        Self {
            checks: 0,
            findings: vec![],
            passed: true,
        }
    }

    fn fail(&mut self, skill: impl Into<String>, check: impl Into<String>, msg: impl Into<String>) {
        self.findings.push(Finding {
            skill: skill.into(),
            check: check.into(),
            message: msg.into(),
            severity: Severity::Blocking,
        });
        self.passed = false;
    }

    fn merge(&mut self, other: ReviewReport) {
        self.checks += other.checks;
        self.findings.extend(other.findings);
        if !other.passed {
            self.passed = false;
        }
    }
}

// Helpers

fn skills_dir(root: &Path) -> PathBuf {
    root.join("skills")
}

fn agents_dir(root: &Path) -> PathBuf {
    root.join("agents")
}

/// Return all skill dirs excluding `_lib`.
fn skill_dirs(root: &Path) -> Result<Vec<PathBuf>> {
    let dir = skills_dir(root);
    if !dir.exists() {
        return Ok(vec![]);
    }
    let mut out = vec![];
    for entry in fs::read_dir(&dir)? {
        let entry = entry?;
        if entry.file_type()?.is_dir() {
            let name = entry.file_name();
            if name != "_lib" {
                out.push(entry.path());
            }
        }
    }
    out.sort();
    Ok(out)
}

/// Return all agent `.md` files in `agents/`.
fn agent_files(root: &Path) -> Result<Vec<PathBuf>> {
    let dir = agents_dir(root);
    if !dir.exists() {
        return Ok(vec![]);
    }
    let mut out = vec![];
    for entry in fs::read_dir(&dir)? {
        let entry = entry?;
        let path = entry.path();
        if path.extension().and_then(|e| e.to_str()) == Some("md") {
            out.push(path);
        }
    }
    out.sort();
    Ok(out)
}

/// Extract frontmatter `name:` value from SKILL.md content.
fn extract_fm_name(content: &str) -> Option<String> {
    let mut in_fm = false;
    let mut past_first = false;
    for line in content.lines() {
        if line == "---" {
            if !past_first {
                in_fm = true;
                past_first = true;
            } else {
                break;
            }
        } else if in_fm && let Some(rest) = line.strip_prefix("name:") {
            let val = rest.trim().trim_matches('"').trim().to_string();
            if !val.is_empty() {
                return Some(val);
            }
        }
    }
    None
}

/// Extract frontmatter field value.
fn extract_fm_field<'a>(content: &'a str, field: &str) -> Option<&'a str> {
    let mut in_fm = false;
    let mut past_first = false;
    for line in content.lines() {
        if line == "---" {
            if !past_first {
                in_fm = true;
                past_first = true;
            } else {
                break;
            }
        } else if in_fm {
            let prefix = format!("{field}:");
            if let Some(rest) = line.strip_prefix(&prefix) {
                return Some(rest.trim());
            }
        }
    }
    None
}

// Public API

/// Run all conformance checks (equivalent to `just conformance`).
pub fn run_all(root: &Path) -> Result<ReviewReport> {
    let mut report = ReviewReport::new();
    report.merge(check_skills(root)?);
    report.merge(check_agents(root)?);
    report.merge(check_agent_naming(root)?);
    report.merge(check_plugin_json(root)?);
    report.merge(check_lib(root)?);
    Ok(report)
}

// TODO(rustqual,#87): split check_skills() into focused, single-responsibility helpers.
// cognitive_complexity=80, cyclomatic_complexity=39, long_function=219 lines.
// Suggested split: check_skill_frontmatter(), check_skill_index_entries(),
// check_skill_links(), check_skill_subcommands(), check_skill_consistency().
/// Check skill dirs: SKILL.md present, frontmatter name, index/using-godmode entries,
/// link resolution, CLI subcommand validity, cross-skill consistency.
pub fn check_skills(root: &Path) -> Result<ReviewReport> {
    let mut r = ReviewReport::new();
    let dirs = skill_dirs(root)?;

    let index_names = load_skill_index_names(root)?;
    let using_path = root.join("skills/using-godmode/SKILL.md");
    let using_content = fs::read_to_string(&using_path).unwrap_or_default();

    for dir in &dirs {
        r.merge(check_skill_frontmatter(
            root,
            dir,
            &index_names,
            &using_content,
        )?);
        r.merge(check_skill_links(root, dir)?);
        r.merge(check_skill_subcommands(dir)?);
        r.merge(check_skill_consistency(dir)?);
    }

    r.merge(check_skill_index_entries(&dirs, &index_names));

    Ok(r)
}

fn skill_name_of(dir: &Path) -> String {
    dir.file_name()
        .unwrap_or_default()
        .to_string_lossy()
        .to_string()
}

/// Check SKILL.md existence and frontmatter name; check index/using-godmode entries.
fn check_skill_frontmatter(
    _root: &Path,
    dir: &Path,
    index_names: &std::collections::BTreeSet<String>,
    using_content: &str,
) -> Result<ReviewReport> {
    let mut r = ReviewReport::new();
    let skill_name = skill_name_of(dir);
    let skill_md = dir.join("SKILL.md");

    // Check 1: SKILL.md exists
    r.checks += 1;
    if !skill_md.exists() {
        r.fail(
            &skill_name,
            "missing SKILL.md",
            format!("[{skill_name}] missing SKILL.md"),
        );
        return Ok(r);
    }

    let content = fs::read_to_string(&skill_md)?;

    // Check 2: frontmatter name present
    r.checks += 1;
    let fm_name = extract_fm_name(&content);
    if fm_name.is_none() {
        r.fail(
            &skill_name,
            "missing frontmatter name",
            format!("[{skill_name}] missing or empty frontmatter name:"),
        );
    }

    if let Some(ref full_name) = fm_name {
        // Check 3: directory name in canonical skill-index.json.
        if skill_name != "using-godmode" {
            r.checks += 1;
            if !index_names.contains(&skill_name) {
                r.fail(
                    &skill_name,
                    "not in skill-index.json",
                    format!("[{skill_name}] name '{full_name}' not found in skill-index.json"),
                );
            }

            // Check 4: name in using-godmode/SKILL.md
            r.checks += 1;
            if !using_content.contains(full_name.as_str()) {
                r.fail(
                    &skill_name,
                    "not in using-godmode SKILL.md",
                    format!(
                        "[{skill_name}] name '{full_name}' not found in using-godmode/SKILL.md"
                    ),
                );
            }
        }
    }

    Ok(r)
}

fn load_skill_index_names(root: &Path) -> Result<std::collections::BTreeSet<String>> {
    let path = root.join("skills/using-godmode/references/skill-index.json");
    let content =
        fs::read_to_string(&path).with_context(|| format!("cannot read {}", path.display()))?;
    let value: serde_json::Value = serde_json::from_str(&content)
        .with_context(|| format!("invalid JSON in {}", path.display()))?;
    value
        .get("skills")
        .and_then(serde_json::Value::as_array)
        .context("skill-index.json missing skills array")?
        .iter()
        .map(|entry| {
            entry
                .get("name")
                .and_then(serde_json::Value::as_str)
                .map(str::to_string)
                .context("skill-index.json entry missing name")
        })
        .collect()
}

/// Check orphan JSON index entries against repository skill directories.
fn check_skill_index_entries(
    dirs: &[PathBuf],
    index_names: &std::collections::BTreeSet<String>,
) -> ReviewReport {
    let mut report = ReviewReport::new();
    for name in index_names {
        report.checks += 1;
        let exists = dirs
            .iter()
            .any(|dir| dir.file_name().unwrap_or_default().to_string_lossy() == name.as_str());
        if !exists {
            report.fail(
                "index",
                "orphan entry",
                format!("[index] orphan entry {name} — no matching skills/{name}/ dir"),
            );
        }
    }
    report
}

/// Check references/, helpers/, and _lib/ links resolve.
fn check_skill_links(root: &Path, dir: &Path) -> Result<ReviewReport> {
    let mut r = ReviewReport::new();
    let skill_name = skill_name_of(dir);
    let skill_md = dir.join("SKILL.md");
    if !skill_md.exists() {
        return Ok(r);
    }
    let content = fs::read_to_string(&skill_md)?;

    // Check 5: references/ links resolve
    for line in content.lines() {
        if let Some(cap) = extract_backtick_path(line, "references/") {
            if cap.ends_with(char::from(47)) {
                continue;
            }
            r.checks += 1;
            let resolved = dir.join(&cap);
            if !resolved.exists() {
                r.fail(
                    &skill_name,
                    "broken references link",
                    format!("[{skill_name}] broken references link: {cap}"),
                );
            }
        }
    }

    // Check 6: helpers/ links resolve
    for line in content.lines() {
        if let Some(cap) = extract_backtick_path(line, "helpers/") {
            if cap.ends_with(char::from(47)) {
                continue;
            }
            r.checks += 1;
            let resolved = dir.join(&cap);
            if !resolved.exists() {
                r.fail(
                    &skill_name,
                    "broken helpers link",
                    format!("[{skill_name}] broken helpers link: {cap}"),
                );
            }
        }
    }

    // Check 10: _lib/ references resolve
    for line in content.lines() {
        if let Some(cap) = extract_backtick_path(line, "skills/_lib/") {
            r.checks += 1;
            let resolved = root.join(&cap);
            if !resolved.exists() {
                r.fail(
                    &skill_name,
                    "broken _lib link",
                    format!("[{skill_name}] broken _lib link: {cap}"),
                );
            }
        }
    }

    Ok(r)
}

/// Check CLI subcommand validity.
fn check_skill_subcommands(dir: &Path) -> Result<ReviewReport> {
    let mut r = ReviewReport::new();
    let skill_name = skill_name_of(dir);
    let skill_md = dir.join("SKILL.md");
    if !skill_md.exists() {
        return Ok(r);
    }
    let content = fs::read_to_string(&skill_md)?;

    // Check 7: CLI subcommand validity
    for (lineno, line) in content.lines().enumerate() {
        let trimmed = line.trim();
        if !trimmed.starts_with("godmode ") {
            continue;
        }
        let parts: Vec<&str> = trimmed
            .split_whitespace()
            .skip(1)
            .filter(|p| !p.is_empty())
            .collect();
        if parts.is_empty() {
            continue;
        }
        let first = parts[0];
        if first.starts_with('-')
            || first.starts_with('<')
            || first.starts_with('$')
            || first.starts_with('#')
        {
            continue;
        }
        let two = if parts.len() >= 2 {
            let second = parts[1];
            if !second.starts_with('-')
                && !second.starts_with('<')
                && !second.starts_with('$')
                && !second.starts_with('[')
            {
                format!("{first} {second}")
            } else {
                String::new()
            }
        } else {
            String::new()
        };

        r.checks += 1;
        let matched = if !two.is_empty() {
            CANONICAL_SUBCOMMANDS.contains(&two.as_str()) || CANONICAL_SUBCOMMANDS.contains(&first)
        } else {
            CANONICAL_SUBCOMMANDS.contains(&first)
        };
        if !matched {
            let shown = if !two.is_empty() { &two } else { first };
            r.fail(
                &skill_name,
                "unknown subcommand",
                format!(
                    "[{skill_name}:{}] unknown subcommand: godmode {shown}",
                    lineno + 1
                ),
            );
        }
    }

    Ok(r)
}

/// Check cross-skill consistency: merge strategy and branch guard.
fn check_skill_consistency(dir: &Path) -> Result<ReviewReport> {
    let mut r = ReviewReport::new();
    let skill_name = skill_name_of(dir);
    let skill_md = dir.join("SKILL.md");
    if !skill_md.exists() {
        return Ok(r);
    }
    let content = fs::read_to_string(&skill_md)?;

    // Check 8: merge strategy — git merge must use --no-ff
    r.checks += 1;
    if content.contains("git merge") && !content.contains("--no-ff") {
        r.fail(
            &skill_name,
            "merge strategy",
            format!(
                "[{skill_name}] consistency violation: merge strategy — mentions 'git merge' \
                 but not '--no-ff'"
            ),
        );
    }

    // Check 9: branch guard — git commit requires git branch --show-current
    r.checks += 1;
    if content.contains("git commit") && !content.contains("git branch --show-current") {
        r.fail(
            &skill_name,
            "branch guard",
            format!(
                "[{skill_name}] consistency violation: branch guard — has 'git commit' but no \
                 'git branch --show-current' check"
            ),
        );
    }

    Ok(r)
}

// TODO(rustqual,#88): split check_agents() into focused helpers.
// cognitive_complexity=24, long_function=109 lines.
// Suggested split: check_agent_frontmatter(), check_agent_skill_refs(), check_agent_tools().
/// Check agent frontmatter: name, model, tools fields all present and non-empty.
/// Also checks description length, skill directory existence, and tools non-empty.
pub fn check_agents(root: &Path) -> Result<ReviewReport> {
    let mut r = ReviewReport::new();
    let files = agent_files(root)?;

    for path in &files {
        r.merge(check_agent_frontmatter(root, path)?);
        r.merge(check_agent_tools(path)?);
        r.merge(check_agent_skill_refs(root, path)?);
    }

    Ok(r)
}

/// Check agent name/model/description frontmatter fields.
fn check_agent_frontmatter(root: &Path, path: &Path) -> Result<ReviewReport> {
    use crate::agent_index;

    let mut r = ReviewReport::new();
    let agent_name = path
        .file_stem()
        .unwrap_or_default()
        .to_string_lossy()
        .to_string();
    let content = fs::read_to_string(path)?;

    for field in ["name", "model", "tools"] {
        r.checks += 1;
        match extract_fm_field(&content, field) {
            None => {
                r.fail(
                    &agent_name,
                    format!("missing {field}"),
                    format!("[{agent_name}] agent missing frontmatter field: {field}"),
                );
            }
            Some("") => {
                r.fail(
                    &agent_name,
                    format!("empty {field}"),
                    format!("[{agent_name}] agent frontmatter field empty: {field}"),
                );
            }
            _ => {}
        }
    }

    // Check: description non-empty and > 20 chars
    r.checks += 1;
    let desc_raw = extract_fm_field(&content, "description").unwrap_or("");
    let desc_text = desc_raw.trim();
    let effective_desc = if desc_text.is_empty() {
        agent_index::list_agents(root)
            .ok()
            .and_then(|agents| {
                agents.into_iter().find(|a| {
                    a.path.file_stem().and_then(|s| s.to_str()).unwrap_or("") == agent_name
                })
            })
            .map(|a| a.description)
            .unwrap_or_default()
    } else {
        desc_text.to_string()
    };
    if effective_desc.is_empty() {
        r.fail(
            &agent_name,
            "description empty",
            format!("[{agent_name}] agent description is empty"),
        );
    } else if effective_desc.len() <= 20 {
        r.fail(
            &agent_name,
            "description too short",
            format!(
                "[{agent_name}] agent description is too short ({} chars, need > 20)",
                effective_desc.len()
            ),
        );
    }

    Ok(r)
}

/// Check that the tools field is non-empty.
fn check_agent_tools(path: &Path) -> Result<ReviewReport> {
    let mut r = ReviewReport::new();
    let agent_name = path
        .file_stem()
        .unwrap_or_default()
        .to_string_lossy()
        .to_string();
    let content = fs::read_to_string(path)?;

    let tools_val = extract_fm_field(&content, "tools").unwrap_or("");
    r.checks += 1;
    if tools_val.trim().is_empty() || tools_val.trim() == "[]" {
        r.fail(
            &agent_name,
            "tools empty",
            format!("[{agent_name}] agent tools field is empty"),
        );
    }

    Ok(r)
}

/// Check that skill references in frontmatter point to existing skill dirs.
fn check_agent_skill_refs(root: &Path, path: &Path) -> Result<ReviewReport> {
    let mut r = ReviewReport::new();
    let agent_name = path
        .file_stem()
        .unwrap_or_default()
        .to_string_lossy()
        .to_string();
    let content = fs::read_to_string(path)?;

    let skills_val = extract_fm_field(&content, "skills").unwrap_or("");
    if !skills_val.is_empty() {
        for skill in skills_val
            .split(',')
            .map(|s| s.trim())
            .filter(|s| !s.is_empty())
        {
            r.checks += 1;
            let skill_dir = root.join("skills").join(skill);
            if !skill_dir.exists() {
                r.fail(
                    &agent_name,
                    "unknown skill reference",
                    format!(
                        "[{agent_name}] skill '{skill}' referenced but skills/{skill}/ does \
                         not exist"
                    ),
                );
            }
        }
    }

    Ok(r)
}

/// Check agent naming conventions: all agents should use `gm-*` prefix.
pub fn check_agent_naming(root: &Path) -> Result<ReviewReport> {
    let mut r = ReviewReport::new();
    let files = agent_files(root)?;

    for path in &files {
        let content = fs::read_to_string(path)?;
        let agent_file = path
            .file_stem()
            .unwrap_or_default()
            .to_string_lossy()
            .to_string();

        if let Some(name) = extract_fm_name(&content) {
            r.checks += 1;
            // Allow special cases: valerie, godmode-crate-agent
            let is_exception =
                name == "valerie" || name == "godmode-crate-agent" || name == "gm-crate";
            if !name.starts_with("gm-") && !is_exception {
                r.findings.push(Finding {
                    skill: agent_file,
                    check: "naming convention".into(),
                    message: format!("[{name}] agent name does not follow gm-* convention"),
                    severity: Severity::Suggestion,
                });
            }
        }
    }

    Ok(r)
}

// TODO(rustqual,#89): reduce cognitive complexity in check_plugin_json().
// cognitive_complexity=16. Extract field-validation and nu-parse loops into helpers.
/// Check plugin.json allowed fields and _lib/*.nu parse.
pub fn check_plugin_json(root: &Path) -> Result<ReviewReport> {
    let mut r = ReviewReport::new();
    let plugin_path = root.join(".claude-plugin/plugin.json");

    r.checks += 1;
    if !plugin_path.exists() {
        r.fail(
            "plugin.json",
            "file not found",
            "[plugin.json] file not found at .claude-plugin/plugin.json",
        );
        return Ok(r);
    }

    let content = fs::read_to_string(&plugin_path)?;
    let json: serde_json::Value = serde_json::from_str(&content)?;

    if let Some(obj) = json.as_object() {
        r.merge(validate_plugin_fields(obj));
    }

    Ok(r)
}

/// Validate top-level and author fields in a plugin.json object.
fn validate_plugin_fields(obj: &serde_json::Map<String, serde_json::Value>) -> ReviewReport {
    let mut r = ReviewReport::new();
    let allowed = ["name", "version", "author", "description"];

    for key in obj.keys() {
        r.checks += 1;
        if !allowed.contains(&key.as_str()) {
            r.fail(
                "plugin.json",
                "disallowed field",
                format!("[plugin.json] disallowed field: {key}"),
            );
        }
    }

    if let Some(author) = obj.get("author").and_then(|a| a.as_object()) {
        for key in author.keys() {
            r.checks += 1;
            if key != "name" {
                r.fail(
                    "plugin.json",
                    "disallowed author field",
                    format!("[plugin.json] disallowed author field: {key}"),
                );
            }
        }
    }

    r
}

/// Check _lib/*.nu files parse without error.
pub fn check_lib(root: &Path) -> Result<ReviewReport> {
    let mut r = ReviewReport::new();
    let lib_dir = root.join("skills/_lib");
    if !lib_dir.exists() {
        return Ok(r);
    }

    for entry in fs::read_dir(&lib_dir)? {
        let entry = entry?;
        let path = entry.path();
        if path.extension().and_then(|e| e.to_str()) != Some("nu") {
            continue;
        }
        let lib_name = path
            .file_name()
            .unwrap_or_default()
            .to_string_lossy()
            .to_string();
        r.checks += 1;

        let out = Command::new("nu")
            .args(["-c", &format!("use {}", path.display())])
            .output();

        match out {
            Err(_) => {} // nu not available — skip
            Ok(o) if !o.status.success() => {
                let err = String::from_utf8_lossy(&o.stderr);
                let first_line = err.lines().next().unwrap_or("").trim().to_string();
                r.fail(
                    format!("_lib/{lib_name}"),
                    "parse error",
                    format!("[_lib/{lib_name}] parse error: {first_line}"),
                );
            }
            _ => {}
        }
    }

    Ok(r)
}

// Internal utilities

const CANONICAL_SUBCOMMANDS: &[&str] = &[
    "handon",
    "handoff",
    "status",
    "context",
    "visualize-graph",
    "pin",
    "unpin",
    "init",
    "doctor",
    "memory-banking",
    "task list",
    "task next",
    "task add",
    "task start",
    "task done",
    "task block",
    "task unblock",
    "task unblock-all",
    "task run",
    "task remove",
    "task clear",
    "task pull",
    "task push-done",
    "task apply",
    "task list-templates",
    "plan ingest",
    "dispatch",
    "agent",
    "hook",
    "skill",
    "pipeline",
    "policy",
    "insight",
    "session",
    "workflow",
    "scaffold",
    "test-check",
    "agent list",
    "agent index",
    "agent dispatch",
    "verify",
    "wave init",
    "wave status",
    "wave done",
    "wave block",
    "wave check",
    "worktree add",
    "worktree remove",
    "ci triage",
    "issue list",
    "issue close",
    "issue sync-todos",
    "graph build",
    "review self",
    "review skills",
    "review agents",
    "release current",
    "release bump",
    "release tag",
    "release push",
    "release validate",
    "release changelog",
    "session prune",
    "agent generate",
    "agent migrate",
    "skill list",
    "skill install",
    "skill uninstall",
    "hook list",
    "hook log",
    "hook test",
    "hook migrate",
    "workflow run",
    "workflow list",
    "workflow status",
    "visualize-graph",
];

/// Extract a backtick-quoted path that starts with the given prefix from a line.
fn extract_backtick_path(line: &str, prefix: &str) -> Option<String> {
    let mut rest = line;
    while let Some(start) = rest.find('`') {
        rest = &rest[start + 1..];
        if let Some(end) = rest.find('`') {
            let inner = &rest[..end];
            if inner.starts_with(prefix) {
                return inner.split_whitespace().next().map(str::to_string);
            }
            rest = &rest[end + 1..];
        } else {
            break;
        }
    }
    None
}

// Tests

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

    fn make_skill(dir: &Path, name: &str, fm_name: &str) {
        let skill_dir = dir.join("skills").join(name);
        fs::create_dir_all(&skill_dir).unwrap();
        fs::write(
            skill_dir.join("SKILL.md"),
            format!("---\nname: \"{fm_name}\"\n---\n\nContent.\n"),
        )
        .unwrap();
    }

    fn make_index(dir: &Path, entries: &[&str]) {
        let ref_dir = dir.join("skills/using-godmode/references");
        fs::create_dir_all(&ref_dir).unwrap();
        let skills: Vec<serde_json::Value> = entries
            .iter()
            .map(|entry| serde_json::json!({"name": entry.trim_start_matches("godmode:")}))
            .collect();
        fs::write(
            ref_dir.join("skill-index.json"),
            serde_json::to_string(&serde_json::json!({"skills": skills})).unwrap(),
        )
        .unwrap();
    }

    fn make_using_godmode(dir: &Path, entries: &[&str]) {
        let skill_dir = dir.join("skills/using-godmode");
        fs::create_dir_all(&skill_dir).unwrap();
        let body: String = entries.iter().map(|e| format!("{e}\n")).collect();
        fs::write(
            skill_dir.join("SKILL.md"),
            format!("---\nname: \"godmode:using-godmode\"\n---\n\n{body}"),
        )
        .unwrap();
    }

    fn minimal_fixture() -> TempDir {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        make_skill(root, "brainstorm", "godmode:brainstorm");
        make_index(root, &["godmode:brainstorm"]);
        make_using_godmode(root, &["godmode:brainstorm"]);
        tmp
    }

    #[test]
    fn all_checks_pass_on_clean_fixture() {
        let tmp = minimal_fixture();
        let r = check_skills(tmp.path()).unwrap();
        assert!(r.passed, "findings: {:?}", r.findings);
    }

    #[test]
    fn detects_missing_skill_md() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        fs::create_dir_all(root.join("skills/empty-skill")).unwrap();
        make_index(root, &[]);
        make_using_godmode(root, &[]);
        let r = check_skills(root).unwrap();
        assert!(!r.passed);
        assert!(r.findings.iter().any(|f| f.check == "missing SKILL.md"));
    }

    #[test]
    fn detects_missing_frontmatter_name() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        let skill_dir = root.join("skills/no-name");
        fs::create_dir_all(&skill_dir).unwrap();
        fs::write(skill_dir.join("SKILL.md"), "---\n---\n\nContent.\n").unwrap();
        make_index(root, &[]);
        make_using_godmode(root, &[]);
        let r = check_skills(root).unwrap();
        assert!(!r.passed);
        assert!(
            r.findings
                .iter()
                .any(|f| f.check == "missing frontmatter name")
        );
    }

    #[test]
    fn detects_frontmatter_missing_from_using_godmode_table() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        make_skill(root, "brainstorm", "godmode:brainstorm");
        make_index(root, &["godmode:brainstorm"]);
        make_using_godmode(root, &[]);
        let report = check_skills(root).unwrap();
        assert!(
            report
                .findings
                .iter()
                .any(|finding| finding.check == "not in using-godmode SKILL.md")
        );
    }

    #[test]
    fn detects_orphan_index_entry() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        // index references a skill dir that doesn't exist
        make_index(root, &["godmode:ghost"]);
        make_using_godmode(root, &[]);
        let r = check_skills(root).unwrap();
        assert!(!r.passed);
        assert!(r.findings.iter().any(|f| f.check == "orphan entry"));
    }

    #[test]
    fn detects_broken_references_link() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        let skill_dir = root.join("skills/miskill");
        fs::create_dir_all(&skill_dir).unwrap();
        fs::write(
            skill_dir.join("SKILL.md"),
            "---\nname: \"godmode:miskill\"\n---\n\nSee `references/missing.md`.\n",
        )
        .unwrap();
        make_index(root, &["godmode:miskill"]);
        make_using_godmode(root, &["godmode:miskill"]);
        let r = check_skills(root).unwrap();
        assert!(!r.passed);
        assert!(
            r.findings
                .iter()
                .any(|f| f.check == "broken references link")
        );
    }

    #[test]
    fn detects_agent_missing_model_field() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        let agents_dir = root.join("agents");
        fs::create_dir_all(&agents_dir).unwrap();
        // name and tools present, model missing
        fs::write(
            agents_dir.join("my-agent.md"),
            "---\nname: my-agent\ntools: [Read]\n---\n\nBody.\n",
        )
        .unwrap();
        let r = check_agents(root).unwrap();
        assert!(!r.passed);
        assert!(r.findings.iter().any(|f| f.check == "missing model"));
    }

    #[test]
    fn extract_fm_name_parses_quoted_and_unquoted() {
        assert_eq!(
            extract_fm_name("---\nname: \"godmode:foo\"\n---\n"),
            Some("godmode:foo".to_string())
        );
        assert_eq!(
            extract_fm_name("---\nname: godmode:bar\n---\n"),
            Some("godmode:bar".to_string())
        );
        assert_eq!(extract_fm_name("---\n---\n"), None);
    }

    #[test]
    fn plugin_json_check_passes_on_valid_file() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        fs::create_dir_all(root.join(".claude-plugin")).unwrap();
        fs::write(
            root.join(".claude-plugin/plugin.json"),
            r#"{"name":"godmode","version":"1.0.0","author":{"name":"Joe"},"description":"x"}"#,
        )
        .unwrap();
        let r = check_plugin_json(root).unwrap();
        assert!(r.passed, "findings: {:?}", r.findings);
    }

    #[test]
    fn agent_naming_flags_non_gm_prefix() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        let agents_dir = root.join("agents");
        fs::create_dir_all(&agents_dir).unwrap();
        fs::write(
            agents_dir.join("bad-agent.md"),
            "---\nname: my-custom-agent\nmodel: sonnet\ntools: [Read]\ndescription: does things and more stuff\n---\n\nBody.\n",
        )
        .unwrap();
        let r = check_agent_naming(root).unwrap();
        assert_eq!(r.findings.len(), 1);
        assert_eq!(r.findings[0].check, "naming convention");
    }

    #[test]
    fn agent_naming_allows_gm_prefix() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        let agents_dir = root.join("agents");
        fs::create_dir_all(&agents_dir).unwrap();
        fs::write(
            agents_dir.join("good-agent.md"),
            "---\nname: gm-review\nmodel: sonnet\ntools: [Read]\ndescription: does reviews of code changes\n---\n\nBody.\n",
        )
        .unwrap();
        let r = check_agent_naming(root).unwrap();
        assert!(r.findings.is_empty());
    }

    #[test]
    fn agent_naming_allows_exceptions() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        let agents_dir = root.join("agents");
        fs::create_dir_all(&agents_dir).unwrap();
        fs::write(
            agents_dir.join("valerie.md"),
            "---\nname: valerie\nmodel: sonnet\ntools: [Read]\ndescription: task management specialist agent\n---\n\nBody.\n",
        )
        .unwrap();
        let r = check_agent_naming(root).unwrap();
        assert!(r.findings.is_empty());
    }

    #[test]
    fn canonical_subcommands_include_native_issue_sync() {
        assert!(CANONICAL_SUBCOMMANDS.contains(&"issue sync-todos"));
    }

    #[test]
    fn plugin_json_check_fails_on_extra_field() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        fs::create_dir_all(root.join(".claude-plugin")).unwrap();
        fs::write(
            root.join(".claude-plugin/plugin.json"),
            r#"{"name":"x","version":"1.0.0","author":{"name":"Joe"},"description":"y","extra":"bad"}"#,
        )
        .unwrap();
        let r = check_plugin_json(root).unwrap();
        assert!(!r.passed);
        assert!(r.findings.iter().any(|f| f.check == "disallowed field"));
    }
}