skillpack 0.8.5

Generate and verify the agent-distribution layer for any OSS project (Claude Code, Cursor, Codex, OpenCode, GitHub Copilot).
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
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
//! Repo introspection. Produces a [`ProjectProfile`] from pure filesystem
//! reads, plus one guarded `--help` spawn when a CLI binary is detected.
//!
//! Design §6.3: "No side effects. Pure filesystem reads. Spawns `--help` only
//! when a CLI binary is detected ... guarded by a hard timeout and runs in a
//! working directory restricted to the project root."
//!
//! The five supported ecosystems (design §11): Rust, npm, Python, Go, Ruby.
//! Detection order is deliberate: if both a `Cargo.toml` and a `package.json`
//! exist we pick the one most likely to *ship a CLI* (Rust, then node), which
//! matches the polyglot-monorepo reality.

use std::fs;
use std::path::Path;
use std::process::{Command, Stdio};
use std::time::Duration;

use anyhow::Result;

use crate::types::{DiagTrace, Language, ProjectProfile};
mod cli_candidates;
mod manifest;

// Re-export the symbols the rest of `introspect` (orchestrators + tests)
// reaches by the flat path: `detect_cli`/`spawn_candidate`/tests use
// `CliCandidate`/`DetectCli`/`primary_cli_candidate`/`which_on_path`;
// `verify::discovery` uses `project_manifest_version`, and
// `csharp_cli_candidate` (now in `cli_candidates`) uses `select_csproj`.
// The re-exports keep those call sites unchanged after the split.
#[cfg(test)]
pub(crate) use cli_candidates::which_on_path;
pub(crate) use cli_candidates::{primary_cli_candidate, CliCandidate, DetectCli};
pub(crate) use manifest::{project_manifest_version, select_csproj};
#[cfg(test)]
use std::path::PathBuf;

/// We only read the first slice of the README to bound cost.
const README_HEAD_LINES: usize = 500;

/// Introspect the project at `root`. `root` must be the OSS project root
/// (the directory containing the language manifest).
pub fn introspect(root: &Path) -> Result<ProjectProfile> {
    anyhow::ensure!(root.is_dir(), "{} is not a directory", root.display());

    let mut diag = DiagTrace::default();

    let language = detect_language(root, &mut diag);
    let mut manifest_name = manifest::project_manifest_name(root, language);
    // A workspace-only root (no [package]) has no name of its own; its CLI
    // lives in a member. Probe the first member with a name so `detect_cli`
    // (which needs a name to probe candidates) actually walks the workspace
    // rather than bailing at the name gate. The member name also becomes the
    // profile name — the tool the agent discovers — so downstream files key
    // off the right binary.
    if manifest_name.is_none() {
        if language == Language::Rust && is_cargo_workspace_only(root) {
            manifest_name = first_cargo_member_name(root, &mut diag);
        } else if language == Language::Node && is_npm_workspace_only(root) {
            manifest_name = first_npm_member_name(root, &mut diag);
        }
    }
    let repo_url = detect_repo_url(root);
    let license = detect_license(root).or_else(|| manifest::manifest_license(root, language));
    let version = manifest::project_manifest_version(root, language);
    let authors = manifest::project_manifest_authors(root, language);
    let description_hint = read_readme_hint(root);
    let d = detect_cli(root, language, manifest_name.clone(), &mut diag);
    let has_cli = d.has_cli;
    let cli_command = d.command;
    let cli_help_output = d.help_output;
    let cli_subcommand_help = d.subcommand_help;

    let name = manifest_name
        .or_else(|| repo_url_name(&repo_url))
        .unwrap_or_else(|| {
            // Last resort: the directory name itself. Canonicalize first so a
            // bare `--root .` (the documented default) resolves to the real cwd
            // tail instead of `Path::new(".").file_name() == None` → "unknown-tool".
            std::fs::canonicalize(root)
                .ok()
                .and_then(|c| c.file_name().map(|n| n.to_string_lossy().to_string()))
                .or_else(|| {
                    std::env::current_dir()
                        .ok()
                        .and_then(|c| c.file_name().map(|n| n.to_string_lossy().to_string()))
                })
                .unwrap_or_else(|| "unknown-tool".to_string())
        });

    Ok(ProjectProfile {
        name,
        language,
        has_cli,
        cli_command,
        cli_help_output,
        cli_subcommand_help,
        diag,
        repo_url,
        license,
        version,
        authors,
        description_hint,
    })
}

/// Detect the dominant language by checking for known manifests. Each falsy
/// branch (manifest absent) pushes a `DiagNote` so `skillpack doctor` can
/// explain why an `Unknown` language came out, and the workspace-only edge
/// case (a `Cargo.toml` with `[workspace]` members but no `[package]`)
/// surfaces as a note pointing at member walking.
pub(crate) fn detect_language(root: &Path, diag: &mut DiagTrace) -> Language {
    if root.join("Cargo.toml").exists() {
        // A workspace-only `Cargo.toml` (no `[package]`) has no binary of its
        // own; its members may. Push a note so doctor explains the walk below.
        let is_workspace_only = is_cargo_workspace_only(root);
        if is_workspace_only {
            diag.push(
                "detect_language.rust",
                "Cargo.toml found but it is workspace-only (no [package]); ".to_string()
                    + "CLI detection will probe workspace members next",
            );
        }
        Language::Rust
    } else if root.join("package.json").exists() {
        if is_npm_workspace_only(root) {
            diag.push(
                "detect_language.node",
                "package.json found but it declares `workspaces` with no root bin; ".to_string()
                    + "CLI detection will probe workspace packages next",
            );
        }
        Language::Node
    } else if root.join("pyproject.toml").exists()
        || root.join("setup.py").exists()
        || root.join("setup.cfg").exists()
    {
        Language::Python
    } else if root.join("go.mod").exists() {
        Language::Go
    } else if root.join("composer.json").exists() {
        Language::Php
    } else if root.join("pom.xml").exists()
        || root.join("build.gradle").exists()
        || root.join("build.gradle.kts").exists()
    {
        Language::Jvm
    } else if has_csproj(root) {
        Language::CSharp
    } else if root.join("Gemfile").exists() || has_gemspec(root) {
        Language::Ruby
    } else {
        diag.push(
            "detect_language",
            "no known manifest found (none of: Cargo.toml, package.json, ".to_string()
                + "pyproject.toml, setup.py, setup.cfg, go.mod, composer.json, "
                + "pom.xml, build.gradle, build.gradle.kts, Gemfile, *.gemspec, "
                + "*.csproj); "
                + "language detected as Unknown",
        );
        Language::Unknown
    }
}

/// True iff `Cargo.toml` at `root` has a `[workspace]` table but no
/// `[package]` table. A pure workspace root ships no binary of its own;
/// its members may. Used by the diag-trace path, not detection itself.
fn is_cargo_workspace_only(root: &Path) -> bool {
    let Ok(raw) = fs::read_to_string(root.join("Cargo.toml")) else {
        return false;
    };
    let Ok(v) = toml::from_str::<toml::Value>(&raw) else {
        return false;
    };
    v.get("workspace").is_some() && v.get("package").is_none()
}

/// True iff `package.json` at `root` has a `workspaces` field but no `bin`.
fn is_npm_workspace_only(root: &Path) -> bool {
    let Some(raw) = fs::read_to_string(root.join("package.json")).ok() else {
        return false;
    };
    let Ok(v) = serde_json::from_str::<serde_json::Value>(&raw) else {
        return false;
    };
    v.get("workspaces").is_some() && v.get("bin").is_none()
}
/// True iff `pyproject.toml` at `root` has a `[tool.<name>]` table.
/// Detects uv (`[tool.uv]`) and poetry (`[tool.poetry]`) managed monorepos
/// so doctor can explain the "not yet walked" gap.
fn pyproject_has_tool(root: &Path, name: &str) -> bool {
    let Some(raw) = fs::read_to_string(root.join("pyproject.toml")).ok() else {
        return false;
    };
    let Ok(v) = toml::from_str::<toml::Value>(&raw) else {
        return false;
    };
    v.get("tool").and_then(|t| t.get(name)).is_some()
}
/// First `[package].name` from a Cargo workspace member dir. Mirrors the
/// parse in [`walk_cargo_workspace`] but stops at name resolution (no
/// candidate/spawn probe) — used by [`introspect`] so `detect_cli` gets a
/// name to probe. Returns `None` if no member has a `[package].name`.
fn first_cargo_member_name(root: &Path, diag: &mut DiagTrace) -> Option<String> {
    let raw = fs::read_to_string(root.join("Cargo.toml")).ok()?;
    let v = toml::from_str::<toml::Value>(&raw).ok()?;
    let members = v.get("workspace")?.get("members")?.as_array()?;
    for m in members {
        let Some(rel) = m.as_str() else { continue };
        let member_root = root.join(rel);
        let name = fs::read_to_string(member_root.join("Cargo.toml"))
            .ok()
            .and_then(|r| toml::from_str::<toml::Value>(&r).ok())
            .and_then(|mv| {
                mv.get("package")
                    .and_then(|p| p.get("name"))
                    .and_then(|n| n.as_str())
                    .map(String::from)
            });
        if let Some(n) = name {
            diag.push(
                "detect_language.rust.workspace",
                format!("workspace member `{rel}` supplied tool name `{n}`"),
            );
            return Some(n);
        }
    }
    diag.push(
        "detect_language.rust.workspace",
        "no workspace member has a [package].name — name fell back to dir tail".to_string(),
    );
    None
}

/// First `name` from an npm workspace member `package.json`. Mirrors
/// [`walk_npm_workspace`] but stops at name resolution. Returns `None` if no
/// member has a `name` field.
fn first_npm_member_name(root: &Path, diag: &mut DiagTrace) -> Option<String> {
    let raw = fs::read_to_string(root.join("package.json")).ok()?;
    let v = serde_json::from_str::<serde_json::Value>(&raw).ok()?;
    let ws = v.get("workspaces")?;
    let paths: Vec<String> = match ws {
        serde_json::Value::String(s) => vec![s.clone()],
        serde_json::Value::Array(arr) => arr
            .iter()
            .filter_map(|e| e.as_str().map(String::from))
            .collect(),
        _ => return None,
    };
    for rel in paths {
        let pkg = root.join(&rel).join("package.json");
        let name = fs::read_to_string(&pkg)
            .ok()
            .and_then(|r| serde_json::from_str::<serde_json::Value>(&r).ok())
            .and_then(|mv| mv.get("name").and_then(|n| n.as_str()).map(String::from));
        if let Some(n) = name {
            diag.push(
                "detect_language.node.workspace",
                format!("workspace member `{rel}` supplied tool name `{n}`"),
            );
            return Some(n);
        }
    }
    diag.push(
        "detect_language.node.workspace",
        "no workspace member has a package.json `name` — name fell back to dir tail".to_string(),
    );
    None
}

/// Walk a Cargo workspace's members looking for a crate with a CLI binary.
/// Parses `Cargo.toml` `[workspace].members` (literal paths only — globs
/// not expanded, keeping V1 simple), then for each `members/<m>` probes
/// `primary_cli_candidate` against the member's `[package].name`. Pushes a
/// diag note per member tried so doctor explains the walk; returns `Some`
/// on the first member that yields a runnable CLI, `None` if none do.
fn walk_cargo_workspace(root: &Path, _name: &str, diag: &mut DiagTrace) -> Option<DetectCli> {
    let raw = fs::read_to_string(root.join("Cargo.toml")).ok()?;
    let v = toml::from_str::<toml::Value>(&raw).ok()?;
    let members = v.get("workspace")?.get("members")?.as_array()?;
    diag.push(
        "detect_cli.rust.workspace",
        format!(
            "Cargo workspace root — {} member(s) to probe",
            members.len()
        ),
    );
    for m in members {
        let Some(member_rel) = m.as_str() else {
            continue;
        };
        let member_root = root.join(member_rel);
        if !member_root.join("Cargo.toml").is_file() {
            diag.push(
                "detect_cli.rust.workspace",
                format!("member `{member_rel}` has no Cargo.toml — skipped"),
            );
            continue;
        }
        // Prefer the member's own [package].name; fall back to the dir tail.
        let manifest_name = fs::read_to_string(member_root.join("Cargo.toml"))
            .ok()
            .and_then(|r| toml::from_str::<toml::Value>(&r).ok())
            .and_then(|v| {
                v.get("package")
                    .and_then(|p| p.get("name"))
                    .and_then(|n| n.as_str())
                    .map(String::from)
            });
        let Some(member_name) = manifest_name.or_else(|| {
            member_root
                .file_name()
                .map(|f| f.to_string_lossy().into_owned())
        }) else {
            diag.push(
                "detect_cli.rust.workspace",
                format!("member `{member_rel}` has no name in manifest, skipping"),
            );
            continue;
        };
        match primary_cli_candidate(&member_root, Language::Rust, &member_name) {
            Some(candidate) => {
                diag.push(
                    "detect_cli.rust.workspace",
                    format!(
                        "member `{member_rel}` yielded candidate `{}`",
                        candidate.argv.join(" ")
                    ),
                );
                return Some(spawn_candidate(&candidate, diag));
            }
            None => diag.push(
                "detect_cli.rust.workspace",
                format!("member `{member_rel}` (`{member_name}`): no built/installed artifact"),
            ),
        }
    }
    diag.push(
        "detect_cli.rust.workspace",
        "no workspace member yielded a runnable CLI — has_cli=false \
         (run `skillpack init` inside the member crate that ships the binary)"
            .to_string(),
    );
    None
}

/// Walk an npm workspace's members (literal `workspaces` paths, no globs)
/// looking for a package with a `bin`. Parses `package.json` `workspaces`
/// (string or array of strings). Returns `Some` on the first member that
/// yields a runnable CLI; `None` otherwise. Pushes a diag note per member.
fn walk_npm_workspace(root: &Path, _name: &str, diag: &mut DiagTrace) -> Option<DetectCli> {
    let raw = fs::read_to_string(root.join("package.json")).ok()?;
    let v = serde_json::from_str::<serde_json::Value>(&raw).ok()?;
    let ws = v.get("workspaces")?;
    let paths: Vec<String> = match ws {
        serde_json::Value::String(s) => vec![s.clone()],
        serde_json::Value::Array(arr) => arr
            .iter()
            .filter_map(|e| e.as_str().map(String::from))
            .collect(),
        _ => return None,
    };
    diag.push(
        "detect_cli.node.workspace",
        format!("npm workspace root — {} member(s) to probe", paths.len()),
    );
    for member_rel in paths {
        let member_root = root.join(&member_rel);
        let pkg_json = member_root.join("package.json");
        if !pkg_json.is_file() {
            diag.push(
                "detect_cli.node.workspace",
                format!("member `{member_rel}` has no package.json — skipped"),
            );
            continue;
        }
        let Ok(mraw) = fs::read_to_string(&pkg_json) else {
            continue;
        };
        let Ok(mv) = serde_json::from_str::<serde_json::Value>(&mraw) else {
            continue;
        };
        let Some(member_name) = mv
            .get("name")
            .and_then(|n| n.as_str())
            .map(String::from)
            .or_else(|| {
                member_root
                    .file_name()
                    .map(|f| f.to_string_lossy().into_owned())
            })
        else {
            diag.push(
                "detect_cli.node.workspace",
                format!("member `{member_rel}` has no name in manifest, skipping"),
            );
            continue;
        };
        if mv.get("bin").is_none() {
            diag.push(
                "detect_cli.node.workspace",
                format!("member `{member_rel}` (`{member_name}`): no `bin` field — skipped"),
            );
            continue;
        }
        match primary_cli_candidate(&member_root, Language::Node, &member_name) {
            Some(candidate) => {
                diag.push(
                    "detect_cli.node.workspace",
                    format!(
                        "member `{member_rel}` yielded candidate `{}`",
                        candidate.argv.join(" ")
                    ),
                );
                return Some(spawn_candidate(&candidate, diag));
            }
            None => diag.push(
                "detect_cli.node.workspace",
                format!("member `{member_rel}` (`{member_name}`): candidate None (node missing?)"),
            ),
        }
    }
    diag.push(
        "detect_cli.node.workspace",
        "no workspace member yielded a runnable CLI — has_cli=false \
         (run `skillpack init` inside the member package that ships the bin)"
            .to_string(),
    );
    None
}

/// True if the root contains any `*.gemspec` file.
fn has_gemspec(root: &Path) -> bool {
    fs::read_dir(root).is_ok_and(|entries| {
        entries
            .flatten()
            .any(|e| e.path().extension().and_then(|x| x.to_str()) == Some("gemspec"))
    })
}

/// True if the root contains any `*.csproj` file. Solution-only repos (`.sln`
/// at root, csproj in subdirs) are not detected — same limitation class as
/// Cargo workspace-only roots. ponytail: add .sln directory walk when needed.
fn has_csproj(root: &Path) -> bool {
    fs::read_dir(root).is_ok_and(|entries| {
        entries
            .flatten()
            .any(|e| e.path().extension().and_then(|x| x.to_str()) == Some("csproj"))
    })
}

/// Detect whether the project ships an invokable CLI, and if so capture its
/// `--help` output under a hard timeout. Returns
/// `(has_cli, command, output, subcommand_help)`.
///
/// `command` is the full multi-token `--help` argv the verifier re-spawns (e.g.
/// `["node","/abs/bin/cli.js","--help"]`, `["go","run",".","--help"]`). The
/// bare human-facing invocation that SKILL.md publishes is derived separately
/// from the profile name + interview — this is the internal, machine-specific
/// spawn argv (design §5.1, §6.3).
///
/// `subcommand_help` holds `<cli> <sub> --help` per subcommand (clap-style),
/// in declaration order, so the generated SKILL.md can document the real
/// command surface and `verify` can drift-check it. Empty for non-subcommand
/// CLIs — a flat `--help` yields no `Commands:` section.
///
/// Every falsy branch (no name, no root candidate, spawn failure) pushes a
/// `DiagNote` so `skillpack doctor` explains why `has_cli=false` rather than
/// silently reporting it. Workspace-only roots (Cargo `[workspace]` only,
/// npm `workspaces` no `bin`) trigger a member walk before giving up.
fn detect_cli(
    root: &Path,
    language: Language,
    name: Option<String>,
    diag: &mut DiagTrace,
) -> DetectCli {
    let Some(name) = name else {
        diag.push(
            "detect_cli",
            "no tool name derivable from the manifest or repo; ".to_string()
                + "cannot probe for a CLI without a name",
        );
        return DetectCli::none();
    };

    let Some(candidate) = primary_cli_candidate(root, language, &name) else {
        // The root didn't yield a runnable CLI. For workspace roots the binary
        // lives in a member crate/package; walk members before reporting a
        // final `has_cli=false`. uv/poetry monorepos are NOT walked yet —
        // doctor notes the gap so the maintainer can run init in the member.
        if language == Language::Rust && is_cargo_workspace_only(root) {
            if let Some(d) = walk_cargo_workspace(root, &name, diag) {
                return d;
            }
        }
        if language == Language::Node && is_npm_workspace_only(root) {
            if let Some(d) = walk_npm_workspace(root, &name, diag) {
                return d;
            }
        }
        diag.push(
            "detect_cli",
            format!(
                "primary_cli_candidate for language `{}` returned None — \
                 runtime may be missing, no build artifact present, or no bin \
                 entry point. Run `skillpack doctor --verbose` to see the raw \
                 profile; if this is a monorepo member, try running \
                 `skillpack init` inside the member directory.",
                language.as_str()
            ),
        );
        // uv / poetry Python monorepo: explicitly NOT walked yet.
        if language == Language::Python
            && (root.join("uv.toml").exists()
                || pyproject_has_tool(root, "uv")
                || pyproject_has_tool(root, "poetry"))
        {
            diag.push(
                "detect_cli.python",
                "uv/poetry workspace detected; member walking not yet \
                 implemented — run `skillpack init` in the member package dir"
                    .to_string(),
            );
        }
        return DetectCli::none();
    };
    spawn_candidate(&candidate, diag)
}

/// Build the `--help` command from `candidate`, spawn it under the hard
/// timeout, and map the outcome to a `DetectCli`. Pushes a diag note on
/// every non-clean outcome so `doctor` explains timeouts/non-zero/missing.
/// Returns `DetectCli::none()` when the spawn can't run at all (NotFound /
/// SpawnFailed), `has_cli=true` with `help_output=None` on a RanNonZero or
/// TimedOut result (the binary exists and responded — it's a CLI — but the
/// help text wasn't captured).
fn spawn_candidate(candidate: &CliCandidate, diag: &mut DiagTrace) -> DetectCli {
    // Build the spawn command from the multi-token argv (program + args, minus
    // `--help`), then append `--help` for the help capture.
    let mut command = candidate.argv.clone();
    command.push("--help".to_string());

    let mut cmd = Command::new(&candidate.argv[0]);
    for arg in &candidate.argv[1..] {
        cmd.arg(arg);
    }
    cmd.arg("--help")
        .current_dir(&candidate.spawn_cwd)
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped());

    match spawn_with_timeout(&mut cmd, HELP_TIMEOUT) {
        SpawnOutcome::RanClean(output) => {
            // A subcommand CLI advertises its subcommands in the top-level
            // `--help`; capture each one's `--help` so the generated SKILL.md
            // documents the real surface (init/verify + their flags, not the
            // global flags). Best-effort: a subcommand that fails/times out is
            // omitted here — `verify` surfaces the gap if the skill documents
            // a subcommand we couldn't capture.
            let subs = capture_subcommand_help(candidate, &output);
            DetectCli {
                has_cli: true,
                command: Some(command),
                help_output: Some(output),
                subcommand_help: subs,
            }
        }
        SpawnOutcome::RanNonZero => {
            diag.push(
                "detect_cli",
                format!(
                    "`{} --help` exited non-zero; help output not captured",
                    command.join(" ")
                ),
            );
            DetectCli {
                has_cli: true,
                command: Some(command),
                help_output: None,
                subcommand_help: Vec::new(),
            }
        }
        SpawnOutcome::TimedOut => {
            diag.push(
                "detect_cli",
                format!(
                    "`{} --help` timed out after {HELP_TIMEOUT:?}",
                    command.join(" ")
                ),
            );
            DetectCli {
                has_cli: true,
                command: Some(command),
                help_output: None,
                subcommand_help: Vec::new(),
            }
        }
        SpawnOutcome::NotFound => {
            diag.push(
                "detect_cli",
                format!(
                    "spawn failed — `{}` binary not found on PATH",
                    command.first().unwrap_or(&candidate.argv[0])
                ),
            );
            DetectCli::none()
        }
        // ponytail: permission-denied etc. are rare; mapping to `none()`
        // means `has_cli=false` (pure-library path) rather than crashing.
        // verify's spawn will then surface the gap downstream if the CLI IS
        // documented. The honest path for V1 — doesn't crash.
        SpawnOutcome::SpawnFailed(_) => {
            diag.push(
                "detect_cli",
                "spawn failed (permission-denied or OS error); treated as has_cli=false"
                    .to_string(),
            );
            DetectCli::none()
        }
    }
}

/// For a subcommand CLI, spawn `<candidate.argv> <sub> --help` per subcommand
/// advertised in the top-level `--help`, returning `(sub, help)` in declaration
/// order. Reuses the same guarded spawn + timeout as the top-level capture.
/// Failures are omitted silently (introspect is best-effort).
fn capture_subcommand_help(
    candidate: &CliCandidate,
    top_level_help: &str,
) -> Vec<(String, String)> {
    let subs = crate::verify::invocation::extract_subcommands(top_level_help);
    let mut out = Vec::with_capacity(subs.len());
    for sub in subs {
        let mut cmd = Command::new(&candidate.argv[0]);
        for arg in &candidate.argv[1..] {
            cmd.arg(arg);
        }
        cmd.arg(&sub)
            .arg("--help")
            .current_dir(&candidate.spawn_cwd)
            .stdin(Stdio::null())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped());
        if let SpawnOutcome::RanClean(help) = spawn_with_timeout(&mut cmd, HELP_TIMEOUT) {
            out.push((sub, help));
        }
    }
    out
}

use crate::spawn::{self, SpawnOutcome, HELP_TIMEOUT};

fn spawn_with_timeout(cmd: &mut Command, timeout: Duration) -> SpawnOutcome {
    spawn::run(cmd, timeout)
}

/// `git remote get-url origin`, best-effort. Never errors the caller.
fn detect_repo_url(root: &Path) -> Option<String> {
    let mut cmd = Command::new("git");
    cmd.args(["remote", "get-url", "origin"]).current_dir(root);
    match spawn_with_timeout(&mut cmd, Duration::from_secs(3)) {
        SpawnOutcome::RanClean(out) => Some(out.trim().to_string()),
        _ => None,
    }
}

/// Heuristic: read LICENSE, look for the SPDX id text.
fn detect_license(root: &Path) -> Option<String> {
    for filename in &["LICENSE", "LICENSE.md", "LICENSE.txt", "COPYING"] {
        let p = root.join(filename);
        if let Ok(raw) = fs::read_to_string(&p) {
            let head = raw.split('\n').take(3).collect::<Vec<_>>().join("\n");
            let lower = head.to_lowercase();
            if lower.contains("mit license") || lower.contains("permission is hereby granted") {
                return Some("MIT".to_string());
            }
            if lower.contains("apache license") {
                return Some("Apache-2.0".to_string());
            }
            if lower.contains("bsd 3-clause") || lower.contains("neither the name") {
                return Some("BSD-3-Clause".to_string());
            }
            if lower.contains("gnu general public license") {
                return Some("GPL-3.0".to_string());
            }
        }
    }
    None
}

/// First paragraph(s) of the README, capped for cost. Used only as a *hint*
/// surfaced under `--verbose`; the interview is the source of truth.
fn read_readme_hint(root: &Path) -> Option<String> {
    for filename in &["README.md", "README", "readme.md"] {
        let p = root.join(filename);
        if let Ok(raw) = fs::read_to_string(&p) {
            let head: String = raw
                .lines()
                .take(README_HEAD_LINES)
                .collect::<Vec<_>>()
                .join("\n");
            // Find the first non-heading, non-empty prose paragraph.
            let paragraph = head
                .lines()
                .skip_while(|l| {
                    let t = l.trim();
                    t.is_empty() || t.starts_with('#') || t.starts_with('!')
                })
                .take_while(|l| !l.trim().is_empty())
                .collect::<Vec<_>>()
                .join(" ");
            let trimmed = paragraph.trim();
            if !trimmed.is_empty() {
                return Some(trimmed.to_string());
            }
        }
    }
    None
}

fn repo_url_name(repo_url: &Option<String>) -> Option<String> {
    let url = repo_url.as_ref()?;
    let last = url.rsplit('/').next()?.trim_end();
    let stem = last.strip_suffix(".git").unwrap_or(last);
    Some(stem.to_string())
}

#[cfg(test)]
impl ProjectProfile {
    /// Test helper: a profile with everything falsy, for assembling fixtures.
    pub fn test_default() -> Self {
        Self {
            name: "test-tool".to_string(),
            language: Language::Unknown,
            has_cli: false,
            cli_command: None,
            cli_help_output: None,
            cli_subcommand_help: Vec::new(),
            diag: DiagTrace::default(),
            repo_url: None,
            license: None,
            version: None,
            authors: None,
            description_hint: None,
        }
    }
}

#[cfg(test)]
mod candidate_tests {
    //! Tests for per-language CLI candidate *resolution* (not spawning). These
    //! assert the argv we'd spawn without running a subprocess, so they stay
    //! green on machines that don't have every runtime installed.

    use super::*;
    use crate::types::Language;

    /// Build a throwaway project root under the temp dir, lay down `files`,
    /// and return its path. Each call gets a unique directory — Rust runs unit
    /// tests concurrently in threads, so a shared scratch path would race and
    /// see its files overwritten or removed by a sibling test.
    fn scratch_root(files: &[(&str, &str)]) -> PathBuf {
        static SEQ: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
        let n = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        let root = std::env::temp_dir()
            .join(format!("skillpack-test-{}-{}", std::process::id(), n))
            .join("proj");
        let _ = std::fs::remove_dir_all(&root);
        std::fs::create_dir_all(&root).unwrap();
        for (rel, contents) in files {
            let p = root.join(rel);
            if let Some(parent) = p.parent() {
                std::fs::create_dir_all(parent).unwrap();
            }
            std::fs::write(&p, contents).unwrap();
        }
        root
    }

    fn cleanup(root: &Path) {
        let _ = std::fs::remove_dir_all(root);
    }

    #[test]
    fn node_cli_detected_via_bin_absolute_argv() {
        // A `package.json` with a `bin` → script maps to `node <abs script>`.
        if which_on_path("node").is_none() {
            // node isn't on PATH on this machine; the candidate honestly
            // returns None. Assert that rather than skipping, so we still
            // exercise the runtime-present/absent branch.
            let root = scratch_root(&[
                ("package.json", r#"{"bin":{"sample-node":"./bin/cli.js"}}"#),
                ("bin/cli.js", "#!/usr/bin/env node\nconsole.log('x')\n"),
            ]);
            assert!(primary_cli_candidate(&root, Language::Node, "sample-node").is_none());
            cleanup(&root);
            return;
        }
        let root = scratch_root(&[
            ("package.json", r#"{"bin":{"sample-node":"./bin/cli.js"}}"#),
            ("bin/cli.js", "#!/usr/bin/env node\nconsole.log('x')\n"),
        ]);
        let cand = primary_cli_candidate(&root, Language::Node, "sample-node").unwrap();
        assert_eq!(cand.argv.len(), 2, "argv should be [node, <abs script>]");
        let node_stem = Path::new(&cand.argv[0])
            .file_stem()
            .and_then(|s| s.to_str())
            .unwrap_or("");
        assert!(
            node_stem.eq_ignore_ascii_case("node"),
            "got: {:?}",
            cand.argv
        );
        // the script path must be absolute and end with `bin/cli.js`. Use
        // Path component comparison (ends_with) so it holds cross-platform —
        // Windows separators are `\` so a string suffix check would miss.
        let script = Path::new(&cand.argv[1]);
        assert!(
            script.is_absolute() && script.ends_with("bin/cli.js"),
            "expected absolute script path, got {}",
            cand.argv[1]
        );
        assert_eq!(cand.spawn_cwd, root);
        cleanup(&root);
    }

    #[test]
    fn node_cli_string_bin_form() {
        if which_on_path("node").is_none() {
            return;
        }
        // `bin` as a bare string: {"bin": "./cli.js"}.
        let root = scratch_root(&[
            ("package.json", r#"{"bin":"./cli.js"}"#),
            ("cli.js", "console.log('x')\n"),
        ]);
        let cand = primary_cli_candidate(&root, Language::Node, "anything").unwrap();
        assert_eq!(cand.argv.len(), 2);
        assert!(cand.argv[1].ends_with("cli.js"));
        cleanup(&root);
    }

    #[test]
    fn go_candidate_none_when_go_missing() {
        // If `go` is on PATH (a CI machine) this branch isn't exercised; skip
        // rather than assert, so the test stays green where the runtime exists.
        if which_on_path("go").is_some() {
            return;
        }
        // Missing runtime AND a real main.go → None (honest has_cli=false).
        let root = scratch_root(&[("main.go", "package main\nfunc main(){}\n")]);
        assert!(primary_cli_candidate(&root, Language::Go, "sample-go").is_none());
        cleanup(&root);
    }

    #[test]
    fn go_candidate_uses_run_dot_when_go_present() {
        if which_on_path("go").is_none() {
            return;
        }
        let root = scratch_root(&[("main.go", "package main\nfunc main(){}\n")]);
        let cand = primary_cli_candidate(&root, Language::Go, "sample-go").unwrap();
        assert_eq!(cand.argv, vec!["go", "run", "."]);
        assert_eq!(cand.spawn_cwd, root);
        cleanup(&root);
    }

    #[test]
    fn go_candidate_none_without_package_main() {
        if which_on_path("go").is_none() {
            return;
        }
        // A library module (package foo, no main) is not a runnable CLI.
        let root = scratch_root(&[("main.go", "package foo\nfunc main(){}\n")]);
        assert!(primary_cli_candidate(&root, Language::Go, "sample-go").is_none());
        cleanup(&root);
    }

    #[test]
    fn python_candidate_uses_m_module_when_importable() {
        if which_on_path("python")
            .or_else(|| which_on_path("python3"))
            .is_none()
        {
            return;
        }
        let root = scratch_root(&[
            (
                "pyproject.toml",
                "[project]\nname = \"sample-python\"\n[project.scripts]\nsample-python = \"sample_python.cli:main\"\n",
            ),
            ("sample_python/__init__.py", ""),
            ("sample_python/cli.py", "def main(): pass\n"),
        ]);
        let cand = primary_cli_candidate(&root, Language::Python, "sample-python").unwrap();
        assert_eq!(cand.argv.len(), 3, "got: {:?}", cand.argv);
        let stem = Path::new(&cand.argv[0])
            .file_stem()
            .and_then(|s| s.to_str())
            .unwrap_or("");
        assert!(
            stem.eq_ignore_ascii_case("python"),
            "expected python interpreter, got {}",
            cand.argv[0]
        );
        assert_eq!(cand.argv[1], "-m");
        assert_eq!(cand.argv[2], "sample_python");
        assert_eq!(cand.spawn_cwd, root);
        cleanup(&root);
    }

    #[test]
    fn ruby_candidate_none_without_runtime() {
        if which_on_path("ruby")
            .or_else(|| which_on_path("bundle"))
            .is_some()
        {
            return;
        }
        // No binstub AND no runtime → None.
        let root = scratch_root(&[("Gemfile", "source \"https://rubygems.org\"\n")]);
        assert!(primary_cli_candidate(&root, Language::Ruby, "sample-ruby").is_none());
        cleanup(&root);
    }

    #[test]
    fn rust_candidate_fallback_to_path_probe() {
        // No built artifact in this scratch root → falls back to PATH, which
        // won't find a "totally-fake-bin-xyz" → None (honest).
        let root = scratch_root(&[("Cargo.toml", "[package]\nname = \"totally-fake-bin-xyz\"\n")]);
        let cand = primary_cli_candidate(&root, Language::Rust, "totally-fake-bin-xyz");
        assert!(cand.is_none());
        cleanup(&root);
    }

    /// A crate may rename its binary via `[[bin]] name = "..."` (e.g. fd-find
    /// publishes the `fd` binary). `rust_cli_candidate` must probe the
    /// `[[bin]].name` artifact, not just the package-name artifact.
    #[test]
    fn rust_candidate_probes_bin_name_not_package_name() {
        let root = scratch_root(&[(
            "Cargo.toml",
            "[package]\nname = \"fd-find\"\n[[bin]]\nname = \"fd\"\n",
        )]);
        // Pre-built artifact named after [[bin]].name, NOT package name.
        let bin_dir = root.join("target").join("release");
        std::fs::create_dir_all(&bin_dir).unwrap();
        let bin_name = if cfg!(windows) { "fd.exe" } else { "fd" };
        std::fs::write(bin_dir.join(bin_name), "#!/bin/sh\necho fd\n").unwrap();
        let cand = primary_cli_candidate(&root, Language::Rust, "fd-find");
        assert!(cand.is_some(), "expected [[bin]].name artifact probed");
        let cand = cand.unwrap();
        assert!(
            cand.argv[0].ends_with(bin_name),
            "expected argv to target [[bin]] artifact, got {}",
            cand.argv[0]
        );
        // Package-name artifact must NOT be probed first when [[bin]] differs.
        assert!(!cand.argv[0].ends_with("fd-find"));
        cleanup(&root);
    }

    #[test]
    fn csharp_candidate_uses_dotnet_run_with_dash_dash_separator() {
        if which_on_path("dotnet").is_none() {
            return;
        }
        let csproj = r#"<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0</TargetFramework>
  </PropertyGroup>
</Project>
"#;
        let root = scratch_root(&[("sample.csproj", csproj)]);
        let cand = primary_cli_candidate(&root, Language::CSharp, "sample").unwrap();
        // The trailing "--" separates dotnet's flags from the app's argv
        // so an appended --help reaches the app, not dotnet.
        assert_eq!(cand.argv[0], "dotnet");
        assert_eq!(cand.argv[1], "run");
        assert_eq!(cand.argv[2], "--project");
        assert!(cand.argv[3].ends_with("sample.csproj"));
        assert_eq!(cand.argv[4], "--");
        assert_eq!(cand.spawn_cwd, root);
        cleanup(&root);
    }
}

#[cfg(test)]
mod parse_tests {
    //! Orchestrator tests that stayed in `introspect.rs` after the manifest-
    //! parsing tests moved to `super::manifest`: directory-tail fallback
    //! (Bug #3: canonicalize a bare `--root .`), workspace walking past
    //! CLI-less members, and the `which_on_path` real-exercise check.

    use super::*;

    fn scratch(files: &[(&str, &str)]) -> PathBuf {
        static SEQ: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
        let n = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        let root = std::env::temp_dir()
            .join(format!("skillpack-parse-{}-{}", std::process::id(), n))
            .join("proj");
        let _ = std::fs::remove_dir_all(&root);
        std::fs::create_dir_all(&root).unwrap();
        for (rel, contents) in files {
            std::fs::write(root.join(rel), contents).unwrap();
        }
        root
    }

    fn cleanup(root: &Path) {
        let _ = std::fs::remove_dir_all(root);
    }

    // Bug #3: a manifest with no name field and no git remote used to fall back
    // to the directory tail via `Path::new(".").file_name()` — which returns
    // None for `.` — emitting the literal "unknown-tool". Now we canonicalize
    // first, so a bare `--root .` resolves to the real cwd tail.
    #[test]
    fn unknown_root_dot_falls_back_to_canonicalized_dir_name() {
        let root = scratch(&[("package.json", "{}")]);
        let p = introspect(&root).unwrap();
        assert_ne!(
            p.name, "unknown-tool",
            "a real dir must resolve to its tail, not the unknown-tool sentinel"
        );
        assert_eq!(p.name, "proj");
        cleanup(&root);
    }

    // Bug #3 at the real boundary: introspect(".") must canonicalize to the cwd
    // tail, not return "unknown-tool" (Path::new(".").file_name() == None).
    #[test]
    fn introspect_dot_yields_cwd_tail_not_unknown_tool() {
        let p = introspect(Path::new(".")).unwrap();
        assert_ne!(p.name, "unknown-tool");
        let cwd_tail = std::env::current_dir()
            .ok()
            .and_then(|c| c.file_name().map(|n| n.to_string_lossy().to_string()))
            .unwrap_or_default();
        assert_eq!(p.name, cwd_tail);
    }
    // ponytail: walk_*_workspace skip branch (member with no name in manifest
    // AND dir-tail file_name() None) is unreachable for non-root member paths —
    // the path-tail fallback always yields a name. These tests assert the
    // observable contract we DO hit: the walk continues past every member to the
    // end, not aborting on the first no-artifact member. Skip-and-continue vs
    // early-return-None is indistinguishable here only if a name resolution
    // failure occured; the `?`→`continue` fix guards that pathological case.
    #[test]
    fn walk_cargo_workspace_continues_past_no_artifact_member() {
        let root = std::env::temp_dir().join(format!(
            "skillpack-walk-cargo-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        let _ = std::fs::remove_dir_all(&root);
        std::fs::create_dir_all(root.join("members/m1")).unwrap();
        std::fs::create_dir_all(root.join("members/m2")).unwrap();
        std::fs::write(
            root.join("Cargo.toml"),
            "[workspace]\nmembers = [\"members/m1\", \"members/m2\"]\n",
        )
        .unwrap();
        std::fs::write(
            root.join("members/m1/Cargo.toml"),
            "[package]\nname = \"m1\"\n",
        )
        .unwrap();
        std::fs::write(
            root.join("members/m2/Cargo.toml"),
            "[package]\nname = \"m2\"\n",
        )
        .unwrap();
        let mut diag = DiagTrace::default();
        let res = walk_cargo_workspace(&root, "ws", &mut diag);
        assert!(res.is_none(), "no member has a built artifact → None");
        let notes: Vec<&str> = diag.0.iter().map(|d| d.note.as_str()).collect();
        assert!(
            notes.iter().any(|n| n.contains("m1")),
            "m1 probed: {notes:?}"
        );
        assert!(
            notes.iter().any(|n| n.contains("m2")),
            "m2 probed: {notes:?}"
        );
        cleanup(&root);
    }

    #[test]
    fn walk_npm_workspace_continues_past_no_cli_member() {
        let root = std::env::temp_dir().join(format!(
            "skillpack-walk-npm-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        let _ = std::fs::remove_dir_all(&root);
        std::fs::create_dir_all(root.join("members/m1")).unwrap();
        std::fs::create_dir_all(root.join("members/m2")).unwrap();
        std::fs::write(
            root.join("package.json"),
            "{ \"workspaces\": [\"members/m1\", \"members/m2\"] }",
        )
        .unwrap();
        std::fs::write(
            root.join("members/m1/package.json"),
            "{ \"name\": \"m1\", \"bin\": {} }",
        )
        .unwrap();
        std::fs::write(
            root.join("members/m2/package.json"),
            "{ \"name\": \"m2\", \"bin\": {} }",
        )
        .unwrap();
        let mut diag = DiagTrace::default();
        let res = walk_npm_workspace(&root, "ws", &mut diag);
        assert!(res.is_none(), "bin:{{}} → both candidate None → walk None");
        let notes: Vec<&str> = diag.0.iter().map(|d| d.note.as_str()).collect();
        assert!(
            notes.iter().any(|n| n.contains("m1")),
            "m1 probed: {notes:?}"
        );
        assert!(
            notes.iter().any(|n| n.contains("m2")),
            "m2 probed: {notes:?}"
        );
        cleanup(&root);
    }

    #[test]
    fn which_on_path_returns_existing_file() {
        // Real-exercise check: whatever PATH lookup finds must be an existing
        // file. Probes a binary present on every CI OS we run. PATHEXT enum
        // is exercised end-to-end by the windows-latest CI matrix entry
        // (real `node.exe` / `cmd.exe` lookup), not a synthetic env mutation
        // that would race other parallel tests mutating process-global PATH.
        let probe = if cfg!(windows) {
            which_on_path("cmd")
        } else {
            which_on_path("ls")
        };
        if let Some(p) = probe {
            assert!(p.is_file(), "which_on_path returned non-file: {p:?}");
        }
    }
}