pleme-doc-gen 0.1.54

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
//! caixa-forge discovery — the "consume the OSS world" primitive.
//!
//! Sniffs an arbitrary directory's manifest files and infers the
//! ecosystem keyword + best-guess package name. Closes the loop:
//!
//!   operator points at any OSS clone ──► detect() ──► ScaffoldSpec
//!//!//!                            scaffold::build → caixa::render → forge
//!
//! Combined with `gh-publish`, this turns "I found this useful OSS
//! library" into a single CLI invocation that ships a typed caixa
//! wrapper into the pleme-io ecosystem and publishes it to the
//! upstream registry within minutes — no per-call YAML hand-typing.
//!
//! Detection rules are a typed table — `RULES` — ordered most-specific-
//! first (workspace before single-crate, pnpm before npm). Each rule
//! pairs a predicate over the directory contents with the canonical
//! ecosystem keyword that the scaffold module's `defaults_for()` knows.

use std::path::Path;

/// What discover figured out about a directory.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Detected {
    /// Ecosystem keyword that scaffold::ScaffoldSpec accepts.
    pub ecosystem: &'static str,
    /// Best-guess package name (manifest field or directory basename).
    pub name: String,
    /// Source of the name guess — "manifest" or "dir-basename".
    pub name_source: &'static str,
}

/// A detection rule. `matches` returns true iff the directory looks
/// like this ecosystem; `ecosystem` is the keyword to map to.
struct Rule {
    ecosystem: &'static str,
    matches: fn(&Path) -> bool,
}

/// Convenience: directory contains a file with this exact name.
fn has(dir: &Path, name: &str) -> bool {
    dir.join(name).is_file()
}

/// Convenience: directory contains any file whose name ends with the
/// given suffix (e.g. `.csproj`, `.gemspec`, `.cabal`).
fn has_suffix(dir: &Path, suffix: &str) -> bool {
    std::fs::read_dir(dir)
        .ok()
        .map(|entries| entries.flatten().any(|e| {
            e.file_name().to_str()
                .map(|n| n.ends_with(suffix))
                .unwrap_or(false)
        }))
        .unwrap_or(false)
}

/// True iff `Cargo.toml` has a `[workspace]` header.
/// True when Cargo.toml is a rust workspace the
/// `rust-workspace-bump` action can actually bump — needs
/// `[workspace.package].version` as the shared bumpable value.
///
/// Pattern matrix:
///   no [workspace]                       → rust-single-crate
///   [workspace] without [workspace.package]
///                                        → rust-single-crate (the root or
///                                            members each carry their own
///                                            version; bumper can't operate)
///   [workspace.package] without version  → rust-single-crate (rayon
///                                            pattern — shared categories /
///                                            edition only; root still
///                                            owns the version)
///   [workspace.package].version = ".."   → rust-workspace (engenho /
///                                            forged-default — true shared-
///                                            version workspace, bumper-
///                                            compatible whether or not
///                                            root [package] exists)
fn cargo_is_workspace(dir: &Path) -> bool {
    let cargo = dir.join("Cargo.toml");
    if !cargo.is_file() { return false; }
    let Ok(text) = std::fs::read_to_string(&cargo) else { return false; };
    workspace_package_has_version(&text)
}

/// True when the Cargo.toml text has a `[workspace.package]` section
/// whose body contains a top-level `version = "..."` key (i.e. the
/// `rust-workspace-bump` target). Section ends at the next `[...]`
/// header line. Tolerates whitespace + comment lines.
fn workspace_package_has_version(text: &str) -> bool {
    let mut in_section = false;
    for raw in text.lines() {
        let line = raw.trim();
        if line.starts_with('[') && line.ends_with(']') {
            in_section = line == "[workspace.package]";
            continue;
        }
        if !in_section { continue; }
        // Strip inline comment
        let without_comment = line.split('#').next().unwrap_or("").trim();
        if let Some((key, _)) = without_comment.split_once('=') {
            if key.trim() == "version" { return true; }
        }
    }
    false
}

/// Ordered detection rules — first match wins. Most-specific first.
const RULES: &[Rule] = &[
    // ── Rust ──
    Rule { ecosystem: "rust-workspace",   matches: cargo_is_workspace },
    Rule { ecosystem: "rust-single-crate", matches: |d| has(d, "Cargo.toml") },
    // ── Node / JS / TS — pnpm + deno are MORE specific than plain npm ──
    Rule { ecosystem: "js-pnpm",          matches: |d| has(d, "pnpm-workspace.yaml") },
    Rule { ecosystem: "js-deno",          matches: |d| has(d, "deno.json") || has(d, "deno.jsonc") },
    Rule { ecosystem: "npm",              matches: |d| has(d, "package.json") },
    // ── Python — pipenv + conda + pdm are MORE specific than pyproject ──
    Rule { ecosystem: "python-pipenv",    matches: |d| has(d, "Pipfile") },
    Rule { ecosystem: "python-conda",     matches: |d| has(d, "meta.yaml") },
    Rule { ecosystem: "python-pdm",       matches: |d| has(d, "pdm.lock") },
    Rule { ecosystem: "python",           matches: |d| has(d, "pyproject.toml") || has(d, "setup.py") },
    // ── Helm / GH Action ──
    Rule { ecosystem: "helm",             matches: |d| has(d, "Chart.yaml") },
    Rule { ecosystem: "github-action",    matches: |d| has(d, "action.yml") || has(d, "action.yaml") },
    // ── Compiled ──
    Rule { ecosystem: "go",               matches: |d| has(d, "go.mod") },
    Rule { ecosystem: "zig",              matches: |d| has(d, "build.zig") || has(d, "build.zig.zon") },
    Rule { ecosystem: "fortran-fpm",      matches: |d| has(d, "fpm.toml") },
    // ── JVM ──
    Rule { ecosystem: "java-gradle-kts",  matches: |d| has(d, "build.gradle.kts") || has(d, "settings.gradle.kts") },
    Rule { ecosystem: "java-maven",       matches: |d| has(d, "pom.xml") },
    Rule { ecosystem: "scala-sbt",        matches: |d| has(d, "build.sbt") },
    Rule { ecosystem: "clojure-deps",     matches: |d| has(d, "deps.edn") },
    // ── .NET / Swift / Functional ──
    Rule { ecosystem: "dotnet-csproj",    matches: |d| has_suffix(d, ".csproj") },
    Rule { ecosystem: "swift-spm",        matches: |d| has(d, "Package.swift") },
    Rule { ecosystem: "ocaml-dune",       matches: |d| has(d, "dune-project") },
    Rule { ecosystem: "haskell-cabal",    matches: |d| has_suffix(d, ".cabal") },
    Rule { ecosystem: "gleam",            matches: |d| has(d, "gleam.toml") },
    Rule { ecosystem: "racket-info",      matches: |d| has(d, "info.rkt") },
    // ── BEAM / Ruby / Lua / Nim ──
    Rule { ecosystem: "elixir-mix",       matches: |d| has(d, "mix.exs") },
    Rule { ecosystem: "ruby-gem",         matches: |d| has_suffix(d, ".gemspec") },
    Rule { ecosystem: "lua-rockspec",     matches: |d| has_suffix(d, ".rockspec") },
    Rule { ecosystem: "nim-nimble",       matches: |d| has_suffix(d, ".nimble") },
    // ── Polyglot / data ──
    Rule { ecosystem: "crystal",          matches: |d| has(d, "shard.yml") },
    Rule { ecosystem: "dart",             matches: |d| has(d, "pubspec.yaml") },
    Rule { ecosystem: "composer",         matches: |d| has(d, "composer.json") },
    Rule { ecosystem: "julia",            matches: |d| has(d, "Project.toml") },
    Rule { ecosystem: "r-description",    matches: |d| has(d, "DESCRIPTION") },
    // ── Ada (alire-<name>.toml — name-dependent) ──
    Rule { ecosystem: "ada-alire",        matches: |d| {
        std::fs::read_dir(d).ok().map(|es| es.flatten().any(|e|
            e.file_name().to_str().map(|n|
                n.starts_with("alire-") && n.ends_with(".toml")
            ).unwrap_or(false)
        )).unwrap_or(false)
    }},
    // ── C / C++ ──
    Rule { ecosystem: "cpp-conan",        matches: |d| has(d, "conanfile.py") || has(d, "conanfile.txt") },
    Rule { ecosystem: "cpp-vcpkg",        matches: |d| has(d, "vcpkg.json") },
    Rule { ecosystem: "cpp-meson",        matches: |d| has(d, "meson.build") },
    Rule { ecosystem: "cpp-cmake",        matches: |d| has(d, "CMakeLists.txt") },
    // ── Nix flake — LAST so it only fires when nothing else matched.
    // Many real repos (Rust crates, Go modules, etc) carry a flake.nix
    // for dev shells; we want their primary ecosystem to win first.
    Rule { ecosystem: "nix-flake",        matches: |d| has(d, "flake.nix") },
    // ── Tatara-lisp library: any dir with a `stdlib.tlisp` or `*.tlisp`
    // at root + no other manifest. Covers _tlisp-stdlib-shaped repos.
    Rule { ecosystem: "tlisp-library",    matches: |d| {
        std::fs::read_dir(d).ok().map(|es| es.flatten().any(|e|
            e.file_name().to_str().map(|n| n.ends_with(".tlisp")).unwrap_or(false)
        )).unwrap_or(false)
    }},
];

/// Inspect `dir` and return the inferred ecosystem + name, or None
/// when nothing matched.
pub fn detect(dir: &Path) -> Option<Detected> {
    if !dir.is_dir() { return None; }
    for rule in RULES {
        if (rule.matches)(dir) {
            let (name, source) = detect_name(dir, rule.ecosystem);
            return Some(Detected {
                ecosystem: rule.ecosystem,
                name,
                name_source: source,
            });
        }
    }
    None
}

/// Detect the ecosystem of a GitHub repo WITHOUT cloning, by reading
/// the root directory listing via the supplied GithubClient. Falls
/// back to None when the client returns None or no rule matches.
///
/// The slug format is `owner/repo`. The substrate uses the same
/// RULES table as the local-path detector, so detection results are
/// consistent across local and remote sources.
///
/// Name resolution for URL mode: pulls the repo basename from the
/// slug (matches GitHub convention; operators can override with
/// `--name` on downstream subcommands).
pub fn detect_github_url(slug: &str) -> Option<Detected> {
    detect_github_url_with(slug, &crate::github_client::GhCliClient)
}

/// Same as `detect_github_url` but accepts an arbitrary client.
/// Enables matrix-style tests against `MockClient` + future gh-API
/// implementations that aren't the gh CLI.
pub fn detect_github_url_with(
    slug: &str,
    client: &dyn crate::github_client::GithubClient,
) -> Option<Detected> {
    let names = client.list_root_filenames(slug)?;
    // Build a virtual directory by name-set lookup. RULES that test
    // file presence by name work; RULES that test file CONTENT
    // (e.g. cargo_is_workspace looking for [workspace] header) need
    // a content fetch. For accuracy on Cargo.toml, peek inside.
    let has_name = |n: &str| names.iter().any(|f| f == n);
    let has_suffix = |s: &str| names.iter().any(|f| f.ends_with(s));
    let has_alire = || names.iter().any(|f|
        f.starts_with("alire-") && f.ends_with(".toml"));

    // Order: most-specific-first, mirroring RULES for consistency.
    let eco: Option<&'static str> = if has_name("Cargo.toml") {
        // Workspace check requires content fetch — gracefully fall
        // back to single-crate when the content read fails.
        let is_ws = client.fetch_file_text(slug, "Cargo.toml")
            .map(|s| s.contains("[workspace]"))
            .unwrap_or(false);
        Some(if is_ws { "rust-workspace" } else { "rust-single-crate" })
    } else if has_name("pnpm-workspace.yaml") { Some("js-pnpm") }
    else if has_name("deno.json") || has_name("deno.jsonc") { Some("js-deno") }
    else if has_name("package.json") { Some("npm") }
    else if has_name("Pipfile") { Some("python-pipenv") }
    else if has_name("meta.yaml") { Some("python-conda") }
    else if has_name("pdm.lock") { Some("python-pdm") }
    else if has_name("pyproject.toml") || has_name("setup.py") { Some("python") }
    else if has_name("Chart.yaml") { Some("helm") }
    else if has_name("action.yml") || has_name("action.yaml") { Some("github-action") }
    else if has_name("go.mod") { Some("go") }
    else if has_name("build.zig") || has_name("build.zig.zon") { Some("zig") }
    else if has_name("fpm.toml") { Some("fortran-fpm") }
    else if has_name("build.gradle.kts") || has_name("settings.gradle.kts") {
        Some("java-gradle-kts")
    }
    else if has_name("pom.xml") { Some("java-maven") }
    else if has_name("build.sbt") { Some("scala-sbt") }
    else if has_name("deps.edn") { Some("clojure-deps") }
    else if has_suffix(".csproj") { Some("dotnet-csproj") }
    else if has_name("Package.swift") { Some("swift-spm") }
    else if has_name("dune-project") { Some("ocaml-dune") }
    else if has_suffix(".cabal") { Some("haskell-cabal") }
    else if has_name("gleam.toml") { Some("gleam") }
    else if has_name("info.rkt") { Some("racket-info") }
    else if has_name("mix.exs") { Some("elixir-mix") }
    else if has_suffix(".gemspec") { Some("ruby-gem") }
    else if has_suffix(".rockspec") { Some("lua-rockspec") }
    else if has_suffix(".nimble") { Some("nim-nimble") }
    else if has_name("shard.yml") { Some("crystal") }
    else if has_name("pubspec.yaml") { Some("dart") }
    else if has_name("composer.json") { Some("composer") }
    else if has_name("Project.toml") { Some("julia") }
    else if has_name("DESCRIPTION") { Some("r-description") }
    else if has_alire() { Some("ada-alire") }
    else if has_name("conanfile.py") || has_name("conanfile.txt") { Some("cpp-conan") }
    else if has_name("vcpkg.json") { Some("cpp-vcpkg") }
    else if has_name("meson.build") { Some("cpp-meson") }
    else if has_name("CMakeLists.txt") { Some("cpp-cmake") }
    else { None };

    let eco = eco?;
    // Name: slug's repo segment (matches dir-basename convention).
    let name = slug.rsplit('/').next().unwrap_or(slug).to_string();
    Some(Detected { ecosystem: eco, name, name_source: "github-slug" })
}

// gh CLI shell-out + base64 decoding moved to crate::github_client —
// the typed GithubClient trait + GhCliClient + base64_decode_lite all
// live there so future gh-API consumers (PR creation, issue ops,
// deeper discover signals) share one surface.

/// Try to read the package name out of the matched manifest. Falls
/// back to the directory basename if the manifest parse fails or the
/// ecosystem doesn't have a single canonical "name" field.
fn detect_name(dir: &Path, eco: &str) -> (String, &'static str) {
    if let Some(n) = read_manifest_name(dir, eco) {
        return (n, "manifest");
    }
    let basename = dir.file_name()
        .and_then(|s| s.to_str())
        .map(String::from)
        .unwrap_or_else(|| "unknown".to_string());
    (basename, "dir-basename")
}

/// Per-ecosystem manifest name extraction. Best-effort — operator can
/// override with `--name` on the CLI.
fn read_manifest_name(dir: &Path, eco: &str) -> Option<String> {
    let try_toml_name = |path: &Path, header: &str| -> Option<String> {
        let text = std::fs::read_to_string(path).ok()?;
        let mut in_section = false;
        for line in text.lines() {
            let trim = line.trim();
            if trim.starts_with('[') {
                in_section = trim == header;
                continue;
            }
            if in_section && trim.starts_with("name") {
                let after_eq = trim.split_once('=')?.1.trim();
                let stripped = after_eq.trim_matches('"').trim_matches('\'');
                return Some(stripped.to_string());
            }
        }
        None
    };
    let try_json_name = |path: &Path| -> Option<String> {
        let text = std::fs::read_to_string(path).ok()?;
        for line in text.lines() {
            let trim = line.trim();
            if let Some(rest) = trim.strip_prefix("\"name\"") {
                let val = rest.trim_start_matches(':').trim();
                let stripped = val.trim_end_matches(',').trim().trim_matches('"');
                return Some(stripped.to_string());
            }
        }
        None
    };

    match eco {
        "rust-single-crate" | "rust-workspace" => try_toml_name(&dir.join("Cargo.toml"), "[package]")
            .or_else(|| try_toml_name(&dir.join("Cargo.toml"), "[workspace.package]")),
        "npm" | "js-pnpm" => try_json_name(&dir.join("package.json")),
        "js-deno" => try_json_name(&dir.join("deno.json"))
            .or_else(|| try_json_name(&dir.join("deno.jsonc"))),
        "python" | "python-pdm" => try_toml_name(&dir.join("pyproject.toml"), "[project]"),
        "go" => {
            // module github.com/user/name — last path segment
            let text = std::fs::read_to_string(dir.join("go.mod")).ok()?;
            let line = text.lines().find(|l| l.starts_with("module "))?;
            line.trim_start_matches("module ").trim().rsplit('/').next().map(String::from)
        }
        "fortran-fpm" => try_toml_name(&dir.join("fpm.toml"), ""),
        "gleam" => try_toml_name(&dir.join("gleam.toml"), ""),
        _ => None,
    }
}

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

    fn mk_dir(files: &[(&str, &str)]) -> tempdir::TempDir {
        let tmp = tempdir::TempDir::new("discover").expect("tempdir");
        for (name, body) in files {
            std::fs::write(tmp.path().join(name), body).expect("write fixture");
        }
        tmp
    }

    #[test]
    fn detects_rust_single_crate_with_name() {
        let dir = mk_dir(&[("Cargo.toml", "[package]\nname = \"demo\"\nversion = \"0.1.0\"\n")]);
        let det = detect(dir.path()).expect("must detect");
        assert_eq!(det.ecosystem, "rust-single-crate");
        assert_eq!(det.name, "demo");
        assert_eq!(det.name_source, "manifest");
    }

    #[test]
    fn workspace_beats_single_crate() {
        // Pure workspace with shared [workspace.package].version —
        // engenho / forged-default pattern; rust-workspace-bump-compatible.
        let cargo = "[workspace]\nmembers = []\n\n[workspace.package]\nversion = \"0.1.0\"\n";
        let dir = mk_dir(&[("Cargo.toml", cargo)]);
        let det = detect(dir.path()).expect("must detect");
        assert_eq!(det.ecosystem, "rust-workspace");
    }

    #[test]
    fn hybrid_workspace_with_root_routes_as_single_crate() {
        // sui / lapce / thiserror / parking_lot pattern — root [package]
        // is the publishable artifact; the bumper can't operate against
        // a missing [workspace.package].version. Route to cargo-auto-release.
        let cargo = "[package]\nname = \"x\"\nversion = \"0.1.0\"\n\n[workspace]\nmembers = [\"impl\"]\n";
        let dir = mk_dir(&[("Cargo.toml", cargo)]);
        let det = detect(dir.path()).expect("must detect");
        assert_eq!(det.ecosystem, "rust-single-crate");
    }

    #[test]
    fn workspace_package_without_version_routes_as_single_crate() {
        // rayon pattern — [workspace.package] sets shared inheritable
        // fields (rust-version, edition) but NOT version. Bumper needs
        // [workspace.package].version explicitly.
        let cargo = "[package]\nname = \"x\"\nversion = \"1.12.0\"\n\n[workspace]\nmembers = [\"core\"]\n\n[workspace.package]\nrust-version = \"1.85\"\n";
        let dir = mk_dir(&[("Cargo.toml", cargo)]);
        let det = detect(dir.path()).expect("must detect");
        assert_eq!(det.ecosystem, "rust-single-crate");
    }

    #[test]
    fn pnpm_beats_npm() {
        let dir = mk_dir(&[
            ("package.json", "{\"name\":\"thing\"}"),
            ("pnpm-workspace.yaml", "packages:\n  - 'packages/*'\n"),
        ]);
        assert_eq!(detect(dir.path()).unwrap().ecosystem, "js-pnpm");
    }

    #[test]
    fn pipenv_beats_python() {
        let dir = mk_dir(&[("pyproject.toml", "[project]\nname = \"x\"\n"), ("Pipfile", "")]);
        assert_eq!(detect(dir.path()).unwrap().ecosystem, "python-pipenv");
    }

    #[test]
    fn detects_helm() {
        let dir = mk_dir(&[("Chart.yaml", "apiVersion: v2\nname: x\n")]);
        assert_eq!(detect(dir.path()).unwrap().ecosystem, "helm");
    }

    #[test]
    fn detects_github_action() {
        let dir = mk_dir(&[("action.yml", "name: x\nruns: { using: composite }\n")]);
        assert_eq!(detect(dir.path()).unwrap().ecosystem, "github-action");
    }

    #[test]
    fn detects_swift_spm() {
        let dir = mk_dir(&[("Package.swift", "// swift-tools-version:5.9\n")]);
        assert_eq!(detect(dir.path()).unwrap().ecosystem, "swift-spm");
    }

    #[test]
    fn detects_ruby_gem_by_suffix() {
        let dir = mk_dir(&[("demo.gemspec", "Gem::Specification.new {}\n")]);
        assert_eq!(detect(dir.path()).unwrap().ecosystem, "ruby-gem");
    }

    #[test]
    fn detects_csproj_by_suffix() {
        let dir = mk_dir(&[("Demo.csproj", "<Project Sdk=\"x\" />\n")]);
        assert_eq!(detect(dir.path()).unwrap().ecosystem, "dotnet-csproj");
    }

    #[test]
    fn empty_dir_returns_none() {
        let dir = mk_dir(&[]);
        assert!(detect(dir.path()).is_none());
    }

    #[test]
    fn name_falls_back_to_basename_when_manifest_unparseable() {
        // gleam.toml with a name field outside any header
        let dir = mk_dir(&[("Chart.yaml", "apiVersion: v2\n")]);
        let det = detect(dir.path()).unwrap();
        // Helm doesn't have a typed-name reader path; falls back.
        assert_eq!(det.ecosystem, "helm");
        assert_eq!(det.name_source, "dir-basename");
    }

    #[test]
    fn go_name_is_last_segment_of_module_path() {
        let dir = mk_dir(&[("go.mod", "module github.com/pleme-io/thing\n\ngo 1.22\n")]);
        let det = detect(dir.path()).unwrap();
        assert_eq!(det.ecosystem, "go");
        assert_eq!(det.name, "thing");
    }

    // ── URL-mode detection matrix via MockClient ────────────────
    //
    // Per the ★★ CLOSED-LOOP MASS-SYNTHESIS directive Rule 1
    // (verification matrix as forcing function): every URL-mode
    // detection signal gets a mock-driven test. Failures aggregate
    // so one matrix run reports every broken signal.

    use crate::github_client::MockClient;

    fn assert_url_detect(files: &[&str], expected_eco: &str) {
        let client = MockClient::new().with_files(files.iter().copied());
        let det = detect_github_url_with("any/repo", &client)
            .unwrap_or_else(|| panic!("expected detection from {files:?}"));
        assert_eq!(det.ecosystem, expected_eco,
            "files {files:?} should detect as {expected_eco}, got {}", det.ecosystem);
        assert_eq!(det.name_source, "github-slug");
    }

    #[test]
    fn url_mode_detects_rust_single_crate() {
        assert_url_detect(&["Cargo.toml", "src"], "rust-single-crate");
    }

    #[test]
    fn url_mode_detects_rust_workspace_via_content_peek() {
        // Cargo.toml present + [workspace] in content → workspace.
        let client = MockClient::new()
            .with_files(["Cargo.toml"])
            .with_file_content("o/r", "Cargo.toml", "[workspace]\nmembers = []\n");
        let det = detect_github_url_with("o/r", &client).unwrap();
        assert_eq!(det.ecosystem, "rust-workspace");
    }

    #[test]
    fn url_mode_pnpm_beats_npm() {
        assert_url_detect(&["package.json", "pnpm-workspace.yaml"], "js-pnpm");
    }

    #[test]
    fn url_mode_pipenv_beats_python() {
        assert_url_detect(&["pyproject.toml", "Pipfile"], "python-pipenv");
    }

    #[test]
    fn url_mode_matrix_covers_each_unique_signal() {
        // Each row: a minimal file-set + the expected ecosystem.
        // Failures aggregate so one run reports every broken signal.
        let matrix: &[(&[&str], &str)] = &[
            (&["package.json"], "npm"),
            (&["deno.json"], "js-deno"),
            (&["pyproject.toml"], "python"),
            (&["meta.yaml"], "python-conda"),
            (&["pdm.lock"], "python-pdm"),
            (&["Chart.yaml"], "helm"),
            (&["action.yml"], "github-action"),
            (&["go.mod"], "go"),
            (&["build.zig"], "zig"),
            (&["fpm.toml"], "fortran-fpm"),
            (&["build.gradle.kts"], "java-gradle-kts"),
            (&["pom.xml"], "java-maven"),
            (&["build.sbt"], "scala-sbt"),
            (&["deps.edn"], "clojure-deps"),
            (&["Demo.csproj"], "dotnet-csproj"),
            (&["Package.swift"], "swift-spm"),
            (&["dune-project"], "ocaml-dune"),
            (&["foo.cabal"], "haskell-cabal"),
            (&["gleam.toml"], "gleam"),
            (&["info.rkt"], "racket-info"),
            (&["mix.exs"], "elixir-mix"),
            (&["demo.gemspec"], "ruby-gem"),
            (&["demo-1.0.rockspec"], "lua-rockspec"),
            (&["demo.nimble"], "nim-nimble"),
            (&["shard.yml"], "crystal"),
            (&["pubspec.yaml"], "dart"),
            (&["composer.json"], "composer"),
            (&["Project.toml"], "julia"),
            (&["DESCRIPTION"], "r-description"),
            (&["alire-demo.toml"], "ada-alire"),
            (&["conanfile.py"], "cpp-conan"),
            (&["vcpkg.json"], "cpp-vcpkg"),
            (&["meson.build"], "cpp-meson"),
            (&["CMakeLists.txt"], "cpp-cmake"),
        ];
        let mut failures: Vec<String> = vec![];
        for (files, expected) in matrix {
            let client = MockClient::new().with_files(files.iter().copied());
            match detect_github_url_with("o/r", &client) {
                Some(d) if d.ecosystem == *expected => {}
                Some(d) => failures.push(format!(
                    "{files:?} → got {}, expected {expected}", d.ecosystem
                )),
                None => failures.push(format!(
                    "{files:?} → no detection (expected {expected})"
                )),
            }
        }
        assert!(failures.is_empty(),
            "{} URL-mode signals broken:\n  - {}",
            failures.len(), failures.join("\n  - "));
    }
}