pleme-doc-gen 0.1.45

Rust replacement for the M0 Python _gen-patterns.py + _gen-docs.py scripts in pleme-io/actions. Walks every action.yml + emits substrate's patterns-full.nix + per-action README.md + root catalog. Per the NO-SHELL prime directive.
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
//! caixa-forge validation — structural integrity proofs per-ecosystem.
//!
//! Per the 9-layer compounding pattern + the ★★ CLOSED-LOOP MASS-
//! SYNTHESIS directive Rule 1 (verification matrix as forcing function):
//! every forged repo carries structural invariants the substrate
//! MUST hold (manifest exists + key fields present + autobump shim
//! delegates to substrate + .caixa.lisp persisted). The Validator
//! trait formalizes those invariants per ecosystem; the lint
//! subcommand exposes them to operators; convert::Gate B consumes
//! the same trait for per-conversion verification.
//!
//! Three consumers, ONE trait surface, by the prime directive's
//! "any helper used across ≥2 crates → library" rule (here ≥2
//! call sites within the same crate).

use std::path::Path;

/// A single validator failure — typed for structured aggregation.
#[derive(Debug, Clone)]
pub struct ValidationIssue {
    pub kind: IssueKind,
    pub message: String,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IssueKind {
    /// Required file missing
    MissingFile,
    /// File present but missing a required field/section/marker
    MalformedContent,
    /// Substrate-level invariant broken (autobump wiring, etc.)
    SubstrateWiring,
}

/// Typed view over per-ecosystem structural validation. Mirrors the
/// ReverseExtractor + ast::Render trait shape — one method, dispatch
/// by ecosystem keyword, table-driven coverage.
pub trait Validator: Sync {
    /// Inspect a forged repo at `path` + return all structural issues.
    /// Empty Vec means the repo is structurally sound.
    fn validate(&self, path: &Path) -> Vec<ValidationIssue>;
}

// ── Universal validators (apply to every ecosystem) ────────────

fn check_file(path: &Path, relative: &str, kind: IssueKind) -> Option<ValidationIssue> {
    if path.join(relative).is_file() { return None; }
    Some(ValidationIssue { kind, message: format!("missing required file: {relative}") })
}

fn check_text_contains(
    path: &Path, relative: &str, needle: &str, kind: IssueKind,
) -> Option<ValidationIssue> {
    let p = path.join(relative);
    if !p.is_file() {
        return Some(ValidationIssue { kind: IssueKind::MissingFile,
            message: format!("missing required file: {relative}") });
    }
    let text = std::fs::read_to_string(&p).unwrap_or_default();
    if text.contains(needle) { return None; }
    Some(ValidationIssue { kind,
        message: format!("{relative}: missing required marker {needle:?}") })
}

/// Substrate invariants every forged repo must satisfy regardless of
/// ecosystem. Called by every concrete Validator impl.
fn check_substrate_wiring(path: &Path) -> Vec<ValidationIssue> {
    let mut issues = Vec::new();
    if let Some(i) = check_file(path, ".github/workflows/auto-release.yml", IssueKind::MissingFile) { issues.push(i); }
    if let Some(i) = check_file(path, ".pleme-io-release.toml", IssueKind::MissingFile) { issues.push(i); }
    // Accept any substrate reusable release workflow: per-language
    // (cargo-auto-release.yml / npm-auto-release.yml / ...) OR the
    // polymorphic auto-release.yml dispatcher. The required property
    // is *substrate delegation*, not the specific filename.
    if !contains_substrate_release_marker(path) {
        issues.push(ValidationIssue {
            kind: IssueKind::SubstrateWiring,
            message: String::from(
                ".github/workflows/auto-release.yml: missing substrate release-workflow delegation \
                 (expected `uses: pleme-io/substrate/.github/workflows/<lang>-(auto-)release.yml@main`)",
            ),
        });
    }
    if let Some(i) = check_text_contains(path, ".pleme-io-release.toml",
        "[bump]", IssueKind::SubstrateWiring) { issues.push(i); }
    if let Some(i) = check_text_contains(path, ".pleme-io-release.toml",
        "default-type = \"patch\"", IssueKind::SubstrateWiring) { issues.push(i); }
    issues
}

fn contains_substrate_release_marker(path: &Path) -> bool {
    let p = path.join(".github/workflows/auto-release.yml");
    let Ok(text) = std::fs::read_to_string(&p) else { return false; };
    text.lines().any(|l| {
        let t = l.trim();
        t.starts_with("uses: pleme-io/substrate/.github/workflows/")
            && (t.ends_with("-release.yml@main")
                || t.ends_with("-auto-release.yml@main")
                || t.ends_with("/auto-release.yml@main"))
    })
}

/// The persistent-spec invariant (Rule 3 of the directive) — every
/// forged repo carries a .caixa.lisp adjacent to its artifacts.
/// Callers pass the expected basename; absence is a Persistent-Spec
/// violation. Empty `expected_name` skips the check (used by lint
/// when the caller doesn't know the spec name a priori).
fn check_persistent_spec(path: &Path, expected_name: &str) -> Option<ValidationIssue> {
    if !expected_name.is_empty() {
        let mut name = String::from(expected_name);
        name.push_str(".caixa.lisp");
        if path.join(&name).is_file() { return None; }
    }
    // Fallback: any *.caixa.lisp in the root counts.
    if let Ok(entries) = std::fs::read_dir(path) {
        if entries.flatten().any(|e| e.file_name().to_string_lossy().ends_with(".caixa.lisp")) {
            return None;
        }
    }
    Some(ValidationIssue { kind: IssueKind::MissingFile,
        message: "no .caixa.lisp source persisted in output directory".to_string() })
}

// ── Per-ecosystem validators ───────────────────────────────────

pub struct RustSingleCrateValidator;
impl Validator for RustSingleCrateValidator {
    fn validate(&self, path: &Path) -> Vec<ValidationIssue> {
        let mut issues = check_substrate_wiring(path);
        if let Some(i) = check_text_contains(path, "Cargo.toml", "[package]", IssueKind::MalformedContent) { issues.push(i); }
        if let Some(i) = check_text_contains(path, "Cargo.toml", "edition", IssueKind::MalformedContent) { issues.push(i); }
        if let Some(i) = check_persistent_spec(path, "") { issues.push(i); }
        issues
    }
}

pub struct RustWorkspaceValidator;
impl Validator for RustWorkspaceValidator {
    fn validate(&self, path: &Path) -> Vec<ValidationIssue> {
        let mut issues = check_substrate_wiring(path);
        if let Some(i) = check_text_contains(path, "Cargo.toml", "[workspace]", IssueKind::MalformedContent) { issues.push(i); }
        if let Some(i) = check_persistent_spec(path, "") { issues.push(i); }
        issues
    }
}

pub struct NpmValidator;
impl Validator for NpmValidator {
    fn validate(&self, path: &Path) -> Vec<ValidationIssue> {
        let mut issues = check_substrate_wiring(path);
        if let Some(i) = check_text_contains(path, "package.json", "\"name\"", IssueKind::MalformedContent) { issues.push(i); }
        if let Some(i) = check_text_contains(path, "package.json", "\"version\"", IssueKind::MalformedContent) { issues.push(i); }
        if let Some(i) = check_persistent_spec(path, "") { issues.push(i); }
        issues
    }
}

pub struct PythonValidator;
impl Validator for PythonValidator {
    fn validate(&self, path: &Path) -> Vec<ValidationIssue> {
        let mut issues = check_substrate_wiring(path);
        if let Some(i) = check_text_contains(path, "pyproject.toml", "[project]", IssueKind::MalformedContent) { issues.push(i); }
        if let Some(i) = check_persistent_spec(path, "") { issues.push(i); }
        issues
    }
}

pub struct HelmValidator;
impl Validator for HelmValidator {
    fn validate(&self, path: &Path) -> Vec<ValidationIssue> {
        let mut issues = check_substrate_wiring(path);
        if let Some(i) = check_text_contains(path, "Chart.yaml", "apiVersion:", IssueKind::MalformedContent) { issues.push(i); }
        if let Some(i) = check_text_contains(path, "Chart.yaml", "name:", IssueKind::MalformedContent) { issues.push(i); }
        if let Some(i) = check_persistent_spec(path, "") { issues.push(i); }
        issues
    }
}

pub struct RubyGemValidator;
impl Validator for RubyGemValidator {
    fn validate(&self, path: &Path) -> Vec<ValidationIssue> {
        let mut issues = check_substrate_wiring(path);
        // <name>.gemspec is name-dependent — assert at least one
        // *.gemspec at the repo root.
        let has_gemspec = std::fs::read_dir(path).ok()
            .map(|entries| entries.flatten().any(|e|
                e.file_name().to_str()
                    .map(|n| n.ends_with(".gemspec"))
                    .unwrap_or(false)))
            .unwrap_or(false);
        if !has_gemspec {
            issues.push(ValidationIssue {
                kind: IssueKind::MissingFile,
                message: "no *.gemspec at repo root".into(),
            });
        }
        if let Some(i) = check_persistent_spec(path, "") { issues.push(i); }
        issues
    }
}

pub struct OcamlDuneValidator;
impl Validator for OcamlDuneValidator {
    fn validate(&self, path: &Path) -> Vec<ValidationIssue> {
        let mut issues = check_substrate_wiring(path);
        if let Some(i) = check_text_contains(path, "dune-project", "(lang dune", IssueKind::MalformedContent) { issues.push(i); }
        if let Some(i) = check_text_contains(path, "dune-project", "(name ", IssueKind::MalformedContent) { issues.push(i); }
        if let Some(i) = check_persistent_spec(path, "") { issues.push(i); }
        issues
    }
}

pub struct SwiftSpmValidator;
impl Validator for SwiftSpmValidator {
    fn validate(&self, path: &Path) -> Vec<ValidationIssue> {
        let mut issues = check_substrate_wiring(path);
        if let Some(i) = check_text_contains(path, "Package.swift", "swift-tools-version:", IssueKind::MalformedContent) { issues.push(i); }
        if let Some(i) = check_text_contains(path, "Package.swift", "Package(", IssueKind::MalformedContent) { issues.push(i); }
        if let Some(i) = check_persistent_spec(path, "") { issues.push(i); }
        issues
    }
}

pub struct ElixirMixValidator;
impl Validator for ElixirMixValidator {
    fn validate(&self, path: &Path) -> Vec<ValidationIssue> {
        let mut issues = check_substrate_wiring(path);
        if let Some(i) = check_text_contains(path, "mix.exs", "defmodule", IssueKind::MalformedContent) { issues.push(i); }
        if let Some(i) = check_text_contains(path, "mix.exs", "use Mix.Project", IssueKind::MalformedContent) { issues.push(i); }
        if let Some(i) = check_persistent_spec(path, "") { issues.push(i); }
        issues
    }
}

pub struct JavaGradleKtsValidator;
impl Validator for JavaGradleKtsValidator {
    fn validate(&self, path: &Path) -> Vec<ValidationIssue> {
        let mut issues = check_substrate_wiring(path);
        if let Some(i) = check_file(path, "build.gradle.kts", IssueKind::MissingFile) { issues.push(i); }
        if let Some(i) = check_persistent_spec(path, "") { issues.push(i); }
        issues
    }
}

pub struct CppCmakeValidator;
impl Validator for CppCmakeValidator {
    fn validate(&self, path: &Path) -> Vec<ValidationIssue> {
        let mut issues = check_substrate_wiring(path);
        if let Some(i) = check_text_contains(path, "CMakeLists.txt", "project(", IssueKind::MalformedContent) { issues.push(i); }
        if let Some(i) = check_text_contains(path, "CMakeLists.txt", "cmake_minimum_required", IssueKind::MalformedContent) { issues.push(i); }
        if let Some(i) = check_persistent_spec(path, "") { issues.push(i); }
        issues
    }
}

pub struct CppMesonValidator;
impl Validator for CppMesonValidator {
    fn validate(&self, path: &Path) -> Vec<ValidationIssue> {
        let mut issues = check_substrate_wiring(path);
        if let Some(i) = check_text_contains(path, "meson.build", "project(", IssueKind::MalformedContent) { issues.push(i); }
        if let Some(i) = check_persistent_spec(path, "") { issues.push(i); }
        issues
    }
}

pub struct CppConanValidator;
impl Validator for CppConanValidator {
    fn validate(&self, path: &Path) -> Vec<ValidationIssue> {
        let mut issues = check_substrate_wiring(path);
        if let Some(i) = check_text_contains(path, "conanfile.py", "ConanFile", IssueKind::MalformedContent) { issues.push(i); }
        if let Some(i) = check_persistent_spec(path, "") { issues.push(i); }
        issues
    }
}

pub struct HaskellCabalValidator;
impl Validator for HaskellCabalValidator {
    fn validate(&self, path: &Path) -> Vec<ValidationIssue> {
        let mut issues = check_substrate_wiring(path);
        let has_cabal = std::fs::read_dir(path).ok().map(|es| es.flatten().any(|e|
            e.file_name().to_str().map(|n| n.ends_with(".cabal")).unwrap_or(false))).unwrap_or(false);
        if !has_cabal {
            issues.push(ValidationIssue { kind: IssueKind::MissingFile, message: "no *.cabal at repo root".into() });
        }
        if let Some(i) = check_persistent_spec(path, "") { issues.push(i); }
        issues
    }
}

pub struct NimNimbleValidator;
impl Validator for NimNimbleValidator {
    fn validate(&self, path: &Path) -> Vec<ValidationIssue> {
        let mut issues = check_substrate_wiring(path);
        let has_nimble = std::fs::read_dir(path).ok().map(|es| es.flatten().any(|e|
            e.file_name().to_str().map(|n| n.ends_with(".nimble")).unwrap_or(false))).unwrap_or(false);
        if !has_nimble {
            issues.push(ValidationIssue { kind: IssueKind::MissingFile, message: "no *.nimble at repo root".into() });
        }
        if let Some(i) = check_persistent_spec(path, "") { issues.push(i); }
        issues
    }
}

pub struct LuaRockspecValidator;
impl Validator for LuaRockspecValidator {
    fn validate(&self, path: &Path) -> Vec<ValidationIssue> {
        let mut issues = check_substrate_wiring(path);
        let has_rs = std::fs::read_dir(path).ok().map(|es| es.flatten().any(|e|
            e.file_name().to_str().map(|n| n.ends_with(".rockspec")).unwrap_or(false))).unwrap_or(false);
        if !has_rs {
            issues.push(ValidationIssue { kind: IssueKind::MissingFile, message: "no *.rockspec at repo root".into() });
        }
        if let Some(i) = check_persistent_spec(path, "") { issues.push(i); }
        issues
    }
}

pub struct RDescriptionValidator;
impl Validator for RDescriptionValidator {
    fn validate(&self, path: &Path) -> Vec<ValidationIssue> {
        let mut issues = check_substrate_wiring(path);
        if let Some(i) = check_text_contains(path, "DESCRIPTION", "Package:", IssueKind::MalformedContent) { issues.push(i); }
        if let Some(i) = check_text_contains(path, "DESCRIPTION", "Version:", IssueKind::MalformedContent) { issues.push(i); }
        if let Some(i) = check_persistent_spec(path, "") { issues.push(i); }
        issues
    }
}

pub struct PythonPipenvValidator;
impl Validator for PythonPipenvValidator {
    fn validate(&self, path: &Path) -> Vec<ValidationIssue> {
        let mut issues = check_substrate_wiring(path);
        if let Some(i) = check_file(path, "Pipfile", IssueKind::MissingFile) { issues.push(i); }
        if let Some(i) = check_persistent_spec(path, "") { issues.push(i); }
        issues
    }
}

pub struct GithubActionValidator;
impl Validator for GithubActionValidator {
    fn validate(&self, path: &Path) -> Vec<ValidationIssue> {
        let mut issues = check_substrate_wiring(path);
        if !path.join("action.yml").is_file() && !path.join("action.yaml").is_file() {
            issues.push(ValidationIssue { kind: IssueKind::MissingFile, message: "no action.yml or action.yaml at repo root".into() });
        }
        if let Some(i) = check_persistent_spec(path, "") { issues.push(i); }
        issues
    }
}

pub struct JavaMavenValidator;
impl Validator for JavaMavenValidator {
    fn validate(&self, path: &Path) -> Vec<ValidationIssue> {
        let mut issues = check_substrate_wiring(path);
        if let Some(i) = check_text_contains(path, "pom.xml", "<groupId>", IssueKind::MalformedContent) { issues.push(i); }
        if let Some(i) = check_text_contains(path, "pom.xml", "<artifactId>", IssueKind::MalformedContent) { issues.push(i); }
        if let Some(i) = check_persistent_spec(path, "") { issues.push(i); }
        issues
    }
}

pub struct JsDenoValidator;
impl Validator for JsDenoValidator {
    fn validate(&self, path: &Path) -> Vec<ValidationIssue> {
        let mut issues = check_substrate_wiring(path);
        if let Some(i) = check_text_contains(path, "deno.json", "\"name\"", IssueKind::MalformedContent) { issues.push(i); }
        if let Some(i) = check_persistent_spec(path, "") { issues.push(i); }
        issues
    }
}

pub struct CppVcpkgValidator;
impl Validator for CppVcpkgValidator {
    fn validate(&self, path: &Path) -> Vec<ValidationIssue> {
        let mut issues = check_substrate_wiring(path);
        if let Some(i) = check_text_contains(path, "vcpkg.json", "\"name\"", IssueKind::MalformedContent) { issues.push(i); }
        if let Some(i) = check_persistent_spec(path, "") { issues.push(i); }
        issues
    }
}

pub struct PythonCondaValidator;
impl Validator for PythonCondaValidator {
    fn validate(&self, path: &Path) -> Vec<ValidationIssue> {
        let mut issues = check_substrate_wiring(path);
        if let Some(i) = check_text_contains(path, "meta.yaml", "package:", IssueKind::MalformedContent) { issues.push(i); }
        if let Some(i) = check_text_contains(path, "meta.yaml", "build:", IssueKind::MalformedContent) { issues.push(i); }
        if let Some(i) = check_persistent_spec(path, "") { issues.push(i); }
        issues
    }
}

pub struct AdaAlireValidator;
impl Validator for AdaAlireValidator {
    fn validate(&self, path: &Path) -> Vec<ValidationIssue> {
        let mut issues = check_substrate_wiring(path);
        let has_alire = std::fs::read_dir(path).ok()
            .map(|entries| entries.flatten().any(|e|
                e.file_name().to_str()
                    .map(|n| n.starts_with("alire-") && n.ends_with(".toml"))
                    .unwrap_or(false)))
            .unwrap_or(false);
        if !has_alire {
            issues.push(ValidationIssue {
                kind: IssueKind::MissingFile,
                message: "no alire-*.toml at repo root".into(),
            });
        }
        if let Some(i) = check_persistent_spec(path, "") { issues.push(i); }
        issues
    }
}

pub struct ZigValidator;
impl Validator for ZigValidator {
    fn validate(&self, path: &Path) -> Vec<ValidationIssue> {
        let mut issues = check_substrate_wiring(path);
        if let Some(i) = check_file(path, "build.zig", IssueKind::MissingFile) { issues.push(i); }
        if let Some(i) = check_file(path, "build.zig.zon", IssueKind::MissingFile) { issues.push(i); }
        if let Some(i) = check_persistent_spec(path, "") { issues.push(i); }
        issues
    }
}

pub struct FortranFpmValidator;
impl Validator for FortranFpmValidator {
    fn validate(&self, path: &Path) -> Vec<ValidationIssue> {
        let mut issues = check_substrate_wiring(path);
        if let Some(i) = check_text_contains(path, "fpm.toml", "name =", IssueKind::MalformedContent) { issues.push(i); }
        if let Some(i) = check_text_contains(path, "fpm.toml", "version =", IssueKind::MalformedContent) { issues.push(i); }
        if let Some(i) = check_persistent_spec(path, "") { issues.push(i); }
        issues
    }
}

pub struct GleamValidator;
impl Validator for GleamValidator {
    fn validate(&self, path: &Path) -> Vec<ValidationIssue> {
        let mut issues = check_substrate_wiring(path);
        if let Some(i) = check_text_contains(path, "gleam.toml", "name =", IssueKind::MalformedContent) { issues.push(i); }
        if let Some(i) = check_text_contains(path, "gleam.toml", "version =", IssueKind::MalformedContent) { issues.push(i); }
        if let Some(i) = check_persistent_spec(path, "") { issues.push(i); }
        issues
    }
}

pub struct RacketInfoValidator;
impl Validator for RacketInfoValidator {
    fn validate(&self, path: &Path) -> Vec<ValidationIssue> {
        let mut issues = check_substrate_wiring(path);
        if let Some(i) = check_text_contains(path, "info.rkt", "#lang info", IssueKind::MalformedContent) { issues.push(i); }
        if let Some(i) = check_text_contains(path, "info.rkt", "(define ", IssueKind::MalformedContent) { issues.push(i); }
        if let Some(i) = check_persistent_spec(path, "") { issues.push(i); }
        issues
    }
}

pub struct CrystalValidator;
impl Validator for CrystalValidator {
    fn validate(&self, path: &Path) -> Vec<ValidationIssue> {
        let mut issues = check_substrate_wiring(path);
        if let Some(i) = check_text_contains(path, "shard.yml", "name:", IssueKind::MalformedContent) { issues.push(i); }
        if let Some(i) = check_text_contains(path, "shard.yml", "version:", IssueKind::MalformedContent) { issues.push(i); }
        if let Some(i) = check_persistent_spec(path, "") { issues.push(i); }
        issues
    }
}

pub struct DartValidator;
impl Validator for DartValidator {
    fn validate(&self, path: &Path) -> Vec<ValidationIssue> {
        let mut issues = check_substrate_wiring(path);
        if let Some(i) = check_text_contains(path, "pubspec.yaml", "name:", IssueKind::MalformedContent) { issues.push(i); }
        if let Some(i) = check_text_contains(path, "pubspec.yaml", "version:", IssueKind::MalformedContent) { issues.push(i); }
        if let Some(i) = check_persistent_spec(path, "") { issues.push(i); }
        issues
    }
}

pub struct ComposerValidator;
impl Validator for ComposerValidator {
    fn validate(&self, path: &Path) -> Vec<ValidationIssue> {
        let mut issues = check_substrate_wiring(path);
        if let Some(i) = check_text_contains(path, "composer.json", "\"name\"", IssueKind::MalformedContent) { issues.push(i); }
        if let Some(i) = check_text_contains(path, "composer.json", "\"require\"", IssueKind::MalformedContent) { issues.push(i); }
        if let Some(i) = check_persistent_spec(path, "") { issues.push(i); }
        issues
    }
}

pub struct JuliaValidator;
impl Validator for JuliaValidator {
    fn validate(&self, path: &Path) -> Vec<ValidationIssue> {
        let mut issues = check_substrate_wiring(path);
        if let Some(i) = check_text_contains(path, "Project.toml", "name =", IssueKind::MalformedContent) { issues.push(i); }
        if let Some(i) = check_text_contains(path, "Project.toml", "version =", IssueKind::MalformedContent) { issues.push(i); }
        if let Some(i) = check_persistent_spec(path, "") { issues.push(i); }
        issues
    }
}

pub struct ScalaSbtValidator;
impl Validator for ScalaSbtValidator {
    fn validate(&self, path: &Path) -> Vec<ValidationIssue> {
        let mut issues = check_substrate_wiring(path);
        if let Some(i) = check_text_contains(path, "build.sbt", "name :=", IssueKind::MalformedContent) { issues.push(i); }
        if let Some(i) = check_text_contains(path, "build.sbt", "scalaVersion :=", IssueKind::MalformedContent) { issues.push(i); }
        if let Some(i) = check_persistent_spec(path, "") { issues.push(i); }
        issues
    }
}

pub struct ClojureDepsValidator;
impl Validator for ClojureDepsValidator {
    fn validate(&self, path: &Path) -> Vec<ValidationIssue> {
        let mut issues = check_substrate_wiring(path);
        if let Some(i) = check_text_contains(path, "deps.edn", ":paths", IssueKind::MalformedContent) { issues.push(i); }
        if let Some(i) = check_text_contains(path, "deps.edn", ":deps", IssueKind::MalformedContent) { issues.push(i); }
        if let Some(i) = check_persistent_spec(path, "") { issues.push(i); }
        issues
    }
}

pub struct DotnetCsprojValidator;
impl Validator for DotnetCsprojValidator {
    fn validate(&self, path: &Path) -> Vec<ValidationIssue> {
        let mut issues = check_substrate_wiring(path);
        let has_csproj = std::fs::read_dir(path).ok()
            .map(|entries| entries.flatten().any(|e|
                e.file_name().to_str()
                    .map(|n| n.ends_with(".csproj"))
                    .unwrap_or(false)))
            .unwrap_or(false);
        if !has_csproj {
            issues.push(ValidationIssue {
                kind: IssueKind::MissingFile,
                message: "no *.csproj at repo root".into(),
            });
        }
        if let Some(i) = check_persistent_spec(path, "") { issues.push(i); }
        issues
    }
}

pub struct GoValidator;
impl Validator for GoValidator {
    fn validate(&self, path: &Path) -> Vec<ValidationIssue> {
        let mut issues = check_substrate_wiring(path);
        if let Some(i) = check_text_contains(path, "go.mod", "module ", IssueKind::MalformedContent) { issues.push(i); }
        if let Some(i) = check_text_contains(path, "go.mod", "go ", IssueKind::MalformedContent) { issues.push(i); }
        if let Some(i) = check_file(path, "main.go", IssueKind::MissingFile) { issues.push(i); }
        if let Some(i) = check_persistent_spec(path, "") { issues.push(i); }
        issues
    }
}

/// Substrate-only validator — used when no per-ecosystem validator
/// exists. Checks just the substrate-wide invariants + the persistent
/// spec. Every forged repo passes this floor.
pub struct SubstrateOnlyValidator;
impl Validator for SubstrateOnlyValidator {
    fn validate(&self, path: &Path) -> Vec<ValidationIssue> {
        let mut issues = check_substrate_wiring(path);
        if let Some(i) = check_persistent_spec(path, "") { issues.push(i); }
        issues
    }
}

/// Dispatch by ecosystem keyword → matching validator. Unknown
/// ecosystems get the SubstrateOnlyValidator floor.
pub fn validator_for(ecosystem: &str) -> &'static dyn Validator {
    match ecosystem {
        "rust-single-crate"           => &RustSingleCrateValidator,
        "rust-workspace"              => &RustWorkspaceValidator,
        "npm" | "js-pnpm"             => &NpmValidator,
        "python" | "python-pdm"       => &PythonValidator,
        "helm"                        => &HelmValidator,
        "go"                          => &GoValidator,
        "ruby-gem"                    => &RubyGemValidator,
        "ocaml-dune"                  => &OcamlDuneValidator,
        "dotnet-csproj"               => &DotnetCsprojValidator,
        "swift-spm"                   => &SwiftSpmValidator,
        "elixir-mix"                  => &ElixirMixValidator,
        "scala-sbt"                   => &ScalaSbtValidator,
        "clojure-deps"                => &ClojureDepsValidator,
        "crystal"                     => &CrystalValidator,
        "dart"                        => &DartValidator,
        "composer"                    => &ComposerValidator,
        "julia"                       => &JuliaValidator,
        "zig"                         => &ZigValidator,
        "fortran-fpm"                 => &FortranFpmValidator,
        "gleam"                       => &GleamValidator,
        "racket-info"                 => &RacketInfoValidator,
        "java-maven"                  => &JavaMavenValidator,
        "js-deno"                     => &JsDenoValidator,
        "cpp-vcpkg"                   => &CppVcpkgValidator,
        "python-conda"                => &PythonCondaValidator,
        "ada-alire"                   => &AdaAlireValidator,
        "java-gradle-kts"             => &JavaGradleKtsValidator,
        "cpp-cmake"                   => &CppCmakeValidator,
        "cpp-meson"                   => &CppMesonValidator,
        "cpp-conan"                   => &CppConanValidator,
        "haskell-cabal"               => &HaskellCabalValidator,
        "nim-nimble"                  => &NimNimbleValidator,
        "lua-rockspec"                => &LuaRockspecValidator,
        "r-description"               => &RDescriptionValidator,
        "python-pipenv"               => &PythonPipenvValidator,
        "github-action"               => &GithubActionValidator,
        _ => &SubstrateOnlyValidator,
    }
}

/// Convenience: validate a directory by auto-detecting its ecosystem
/// via discover::detect. Returns the matched ecosystem keyword +
/// the validation issues. Returns None when no ecosystem matched.
pub fn validate_dir(path: &Path) -> Option<(String, Vec<ValidationIssue>)> {
    let detected = crate::discover::detect(path)?;
    let validator = validator_for(detected.ecosystem);
    Some((detected.ecosystem.to_string(), validator.validate(path)))
}

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

    fn mk(files: &[(&str, &str)]) -> tempdir::TempDir {
        let tmp = tempdir::TempDir::new("validator").expect("tempdir");
        for (n, b) in files {
            if let Some(parent) = Path::new(n).parent() {
                let _ = std::fs::create_dir_all(tmp.path().join(parent));
            }
            std::fs::write(tmp.path().join(n), b).expect("write");
        }
        tmp
    }

    fn well_formed_rust() -> Vec<(&'static str, &'static str)> {
        vec![
            ("Cargo.toml", "[package]\nname = \"x\"\nedition = \"2024\"\n"),
            (".github/workflows/auto-release.yml",
                "jobs:\n  release:\n    uses: pleme-io/substrate/.github/workflows/auto-release.yml@main\n"),
            (".pleme-io-release.toml", "[bump]\ndefault-type = \"patch\"\n"),
            ("x.caixa.lisp", "(defcaixa x)\n"),
        ]
    }

    #[test]
    fn rust_single_crate_clean_passes() {
        let dir = mk(&well_formed_rust());
        let issues = RustSingleCrateValidator.validate(dir.path());
        assert!(issues.is_empty(), "expected clean, got: {issues:?}");
    }

    #[test]
    fn missing_autorelease_yml_fails_with_typed_kind() {
        let mut files = well_formed_rust();
        files.retain(|(n, _)| *n != ".github/workflows/auto-release.yml");
        let dir = mk(&files);
        let issues = RustSingleCrateValidator.validate(dir.path());
        assert!(!issues.is_empty());
        assert!(issues.iter().any(|i| i.kind == IssueKind::MissingFile),
            "expected MissingFile issue; got: {issues:?}");
    }

    #[test]
    fn substrate_wiring_marker_required_in_autorelease_yml() {
        let mut files = well_formed_rust();
        files.iter_mut().for_each(|f| {
            if f.0 == ".github/workflows/auto-release.yml" {
                f.1 = "name: bogus\n";
            }
        });
        let dir = mk(&files);
        let issues = RustSingleCrateValidator.validate(dir.path());
        assert!(issues.iter().any(|i| i.kind == IssueKind::SubstrateWiring));
    }

    #[test]
    fn npm_validator_checks_name_and_version_keys() {
        let files = vec![
            ("package.json", "{\"name\":\"x\",\"version\":\"1.0\"}"),
            (".github/workflows/auto-release.yml",
                "jobs:\n  release:\n    uses: pleme-io/substrate/.github/workflows/auto-release.yml@main\n"),
            (".pleme-io-release.toml", "[bump]\ndefault-type = \"patch\"\n"),
            ("x.caixa.lisp", "(defcaixa x)\n"),
        ];
        let dir = mk(&files);
        let issues = NpmValidator.validate(dir.path());
        assert!(issues.is_empty(), "expected clean npm, got: {issues:?}");
    }

    #[test]
    fn validate_dir_auto_detects_ecosystem() {
        let dir = mk(&well_formed_rust());
        let (eco, issues) = validate_dir(dir.path()).expect("must detect");
        assert_eq!(eco, "rust-single-crate");
        assert!(issues.is_empty());
    }

    #[test]
    fn validate_dir_returns_none_for_undetectable() {
        let dir = mk(&[("README.md", "no manifest")]);
        assert!(validate_dir(dir.path()).is_none());
    }

    #[test]
    fn unknown_ecosystem_falls_back_to_substrate_only_validator() {
        // SubstrateOnlyValidator checks the wiring + spec; no
        // per-manifest assertions.
        let v = validator_for("some-future-ecosystem");
        let files = vec![
            (".github/workflows/auto-release.yml",
                "jobs:\n  release:\n    uses: pleme-io/substrate/.github/workflows/auto-release.yml@main\n"),
            (".pleme-io-release.toml", "[bump]\ndefault-type = \"patch\"\n"),
            ("x.caixa.lisp", "(defcaixa x)\n"),
        ];
        let dir = mk(&files);
        let issues = v.validate(dir.path());
        assert!(issues.is_empty(), "substrate-only floor should pass; got: {issues:?}");
    }
}