Skip to main content

speccoder_runtime/
doctor.rs

1//! `speccoder doctor`: everything a run depends on, checked
2//! without writing anything — git, the repository, the spec project and
3//! its tool, the configuration, the model key, the sandbox, the state
4//! directory, the attestation signing key and the repository's
5//! instructions. A failure is a run that would fail or judge wrongly; a
6//! warning is less than it could be (unsigned evidence, no spec tool).
7
8use std::path::Path;
9use std::process::Command;
10
11use speccoder_core::{
12    CommandData, CommandResult, CommandStatus, DoctorCheck, DoctorLevel, DoctorReport,
13};
14
15use crate::git::Git;
16
17fn check(name: &str, level: DoctorLevel, detail: impl Into<String>) -> DoctorCheck {
18    DoctorCheck {
19        check: name.to_owned(),
20        level,
21        detail: detail.into(),
22        code: None,
23        fix: Vec::new(),
24        remedy: None,
25        tasks: Vec::new(),
26        commands: Vec::new(),
27    }
28}
29
30fn failed(name: &str, code: &str, detail: impl Into<String>, fix: &[&str]) -> DoctorCheck {
31    DoctorCheck {
32        code: Some(code.to_owned()),
33        fix: fix.iter().map(|f| (*f).to_owned()).collect(),
34        ..check(name, DoctorLevel::Fail, detail)
35    }
36}
37
38fn warned(name: &str, detail: impl Into<String>, fix: &[&str]) -> DoctorCheck {
39    DoctorCheck {
40        fix: fix.iter().map(|f| (*f).to_owned()).collect(),
41        ..check(name, DoctorLevel::Warn, detail)
42    }
43}
44
45/// The plan checks as doctor rows: `check: "plan"`, level `warn`, the
46/// code's catalog entry, the tasks, the fixes and, for behaviour planned
47/// early, the decision speccoder records as the remedy.
48#[must_use]
49pub fn plan_checks(
50    adapter: &dyn crate::format::Adapter,
51    snapshot: &speccoder_core::snapshot::ProjectSnapshot,
52    root: &Path,
53) -> Vec<DoctorCheck> {
54    let feature = snapshot
55        .feature
56        .as_ref()
57        .map(|f| f.feature.name.clone())
58        .unwrap_or_default();
59    crate::plan_lint::lints(adapter, snapshot, root)
60        .into_iter()
61        .map(|l| DoctorCheck {
62            code: Some(l.code.to_owned()),
63            fix: l.fix.clone(),
64            tasks: l.tasks.clone(),
65            remedy: l
66                .acceptance_at
67                .as_ref()
68                .map(|(task, story)| speccoder_core::Remedy {
69                    label: format!("Write {story}'s acceptance at {task}"),
70                    effect: format!("{task}'s tick can be verified on {story}'s scenarios"),
71                    command: format!("speccoder task acceptance-at {task} --story {story}"),
72                    undo: Some(format!(
73                        "speccoder task acceptance-at {task} --story {story} --revoke"
74                    )),
75                    history: false,
76                    run: speccoder_core::actions::Runnable::AcceptanceAt {
77                        feature: feature.clone(),
78                        story: story.clone(),
79                        task: task.clone(),
80                        revoke: false,
81                    },
82                }),
83            ..check("plan", DoctorLevel::Warn, l.detail)
84        })
85        .collect()
86}
87
88/// Whether the speccoder preset is active for the tasks template.
89fn preset_check(root: &Path) -> DoctorCheck {
90    let state = crate::preset::state(root);
91    let offer = |update: bool| speccoder_core::Remedy {
92        label: if update {
93            "Update the speccoder preset".to_owned()
94        } else {
95            "Add the speccoder preset".to_owned()
96        },
97        effect: "future task lists plan for evidence; no spec file changes".to_owned(),
98        command: "speccoder preset add --yes".to_owned(),
99        undo: Some("specify preset remove speccoder".to_owned()),
100        history: false,
101        run: speccoder_core::actions::Runnable::PresetAdd { update },
102    };
103    match (&state.installed, state.active_for_tasks_template) {
104        (Some(v), true) if v == &state.bundled || v == "unknown" => check(
105            "preset",
106            DoctorLevel::Pass,
107            format!("speccoder preset {v} active for tasks-template"),
108        ),
109        (Some(v), active) => DoctorCheck {
110            remedy: Some(offer(true)),
111            fix: vec!["speccoder preset add --yes".to_owned()],
112            ..check(
113                "preset",
114                DoctorLevel::Info,
115                format!(
116                    "speccoder preset {v} installed{} — this speccoder bundles {}",
117                    if active {
118                        ""
119                    } else {
120                        ", not active for tasks-template"
121                    },
122                    state.bundled
123                ),
124            )
125        },
126        (None, _) => DoctorCheck {
127            remedy: Some(offer(false)),
128            fix: vec!["speccoder preset add --yes".to_owned()],
129            ..check(
130                "preset",
131                DoctorLevel::Info,
132                "speccoder preset not installed (tasks-template from Spec Kit's core)",
133            )
134        },
135    }
136}
137
138/// The first line a program prints for `--version`, if it runs.
139fn version(program: &str) -> Option<String> {
140    let out = Command::new(program).arg("--version").output().ok()?;
141    out.status.success().then(|| {
142        String::from_utf8_lossy(&out.stdout)
143            .lines()
144            .next()
145            .unwrap_or_default()
146            .trim()
147            .to_owned()
148    })
149}
150
151/// Bedrock's `model key` row: the region and where the AWS chain will take
152/// credentials from, named offline (never a value, never a call); and a
153/// `model region` warning when `AWS_REGION` names another region than
154/// the file, which wins.
155fn bedrock_key(
156    m: &crate::substrate::model_config::ModelConfig,
157    env: &dyn Fn(&str) -> Option<String>,
158) -> Vec<DoctorCheck> {
159    let set = |k: &str| env(k).filter(|v| !v.is_empty());
160    let home = std::path::PathBuf::from(set("HOME").unwrap_or_default());
161    let region = m.region.clone().unwrap_or_default();
162    let mut out = vec![match crate::aws::detect(&set, &home) {
163        Some(source) => {
164            let mut detail = format!("bedrock {} · {region} · {}", m.model, source.describe());
165            if source.kind == crate::aws::Kind::ApiKey
166                && let Some(p) = crate::aws::profile(&set, &home)
167            {
168                detail.push_str(&format!(
169                    " (the API key is used; profile {} is not)",
170                    p.name
171                ));
172            }
173            check("model key", DoctorLevel::Pass, detail)
174        }
175        None => DoctorCheck {
176            code: Some("KEY-MISSING".to_owned()),
177            fix: crate::substrate::model_config::bedrock_fixes(),
178            ..check(
179                "model key",
180                DoctorLevel::Fail,
181                format!(
182                    "{} is not set and no AWS profile was found",
183                    crate::aws::API_KEY
184                ),
185            )
186        },
187    }];
188    if let Some(other) = set("AWS_REGION").filter(|r| r.trim() != region) {
189        out.push(check(
190            "model region",
191            DoctorLevel::Warn,
192            format!("{region} in speccoder.toml, AWS_REGION is {other} — the file is used"),
193        ));
194    }
195    out
196}
197
198/// Every check, in order, for the project at `path`.
199#[must_use]
200pub fn checks(
201    path: &Path,
202    feature: Option<&str>,
203    env: &dyn Fn(&str) -> Option<String>,
204) -> Vec<DoctorCheck> {
205    let mut out = Vec::new();
206    // git and the repository.
207    let git = version("git");
208    out.push(match &git {
209        Some(v) => check("git", DoctorLevel::Pass, v.clone()),
210        None => failed(
211            "git",
212            "GIT",
213            "git is not installed or does not run",
214            &["→ install git"],
215        ),
216    });
217    let top = Git::at(path).toplevel().ok().flatten();
218    let has_commit = top.as_ref().is_some_and(|t| {
219        Git::at(t)
220            .line(&["rev-parse", "--verify", "-q", "HEAD"])
221            .is_ok()
222    });
223    out.push(match (&top, has_commit) {
224        (Some(t), true) => check("repository", DoctorLevel::Pass, t.display().to_string()),
225        (Some(_), false) => failed(
226            "repository",
227            "NO-REPOSITORY",
228            "the repository has no commit yet",
229            &["git add -A && git commit -m init"],
230        ),
231        (None, _) => failed(
232            "repository",
233            "NO-REPOSITORY",
234            "not a git repository",
235            &["git init && git add -A && git commit -m init"],
236        ),
237    });
238    // The spec project, and its own tool.
239    let opened = crate::format::open(path, feature);
240    let root = match &opened {
241        Ok(o) => {
242            let kind = o.adapter.wording().name;
243            let feature = o
244                .snapshot
245                .feature
246                .as_ref()
247                .map(|f| format!(", feature {}", f.feature.name))
248                .unwrap_or_default();
249            out.push(check(
250                "project",
251                DoctorLevel::Pass,
252                format!("{kind} at {}{feature}", o.snapshot.root),
253            ));
254            out.push(current_check(o.adapter, &o.snapshot));
255            let name = o.snapshot.feature.as_ref().map(|f| f.feature.name.as_str());
256            if let Some(c) = untracked_check(Path::new(&o.snapshot.root), name) {
257                out.push(c);
258            }
259            if let Some((tool, install)) = o.adapter.tool() {
260                out.push(match version(tool) {
261                    Some(v) => check("spec tool", DoctorLevel::Pass, v),
262                    None => DoctorCheck {
263                        fix: vec![format!("→ {install}")],
264                        ..check(
265                            "spec tool",
266                            DoctorLevel::Warn,
267                            format!(
268                                "`{tool}` is not on PATH: planning skills and cross-checks need it"
269                            ),
270                        )
271                    },
272                });
273            }
274            // The speccoder preset, as Spec Kit reports it.
275            if o.adapter.kind() == speccoder_core::spec::FormatKind::Speckit
276                && version("specify").is_some()
277            {
278                out.push(preset_check(Path::new(&o.snapshot.root)));
279            }
280            out.extend(o.adapter.doctor_checks(Path::new(&o.snapshot.root), env));
281            // The plan checks of the selected feature: warnings.
282            if let Some(f) = o.snapshot.feature.as_ref() {
283                out.extend(plan_checks(
284                    o.adapter,
285                    &o.snapshot,
286                    Path::new(&o.snapshot.root),
287                ));
288                // Who does what: information, never a warning.
289                if let Some(l) =
290                    crate::status::lanes(Path::new(&o.snapshot.root), Some(&f.feature.name))
291                {
292                    out.push(DoctorCheck {
293                        tasks: l.planning.iter().chain(&l.yours).cloned().collect(),
294                        ..check("lanes", DoctorLevel::Pass, l.line())
295                    });
296                }
297            }
298            // Where speccoder's acceptance tests would go.
299            let root = std::path::PathBuf::from(&o.snapshot.root);
300            let layout = crate::layout::detect(&root, &crate::verify::check_argvs(&root));
301            if let Some(r) = layout.primary().filter(|r| r.story_dir.is_none()) {
302                out.push(warned(
303                    "tests",
304                    format!(
305                        "no place the runner collects new test files, so no acceptance test is written: {}",
306                        r.unknown.join("; ")
307                    ),
308                    &["→ let the runner collect a tests directory (Cargo: drop `autotests = false`; pytest: a `testpaths` entry that exists)"],
309                ));
310            }
311            root
312        }
313        Err(r) => {
314            let fix = speccoder_core::codes::lookup("NO-PROJECT")
315                .map(|e| speccoder_core::codes::fixes(e, "doctor", None, None))
316                .unwrap_or_default();
317            out.push(DoctorCheck {
318                code: Some("NO-PROJECT".to_owned()),
319                fix,
320                ..check("project", DoctorLevel::Fail, r.message.clone())
321            });
322            path.to_path_buf()
323        }
324    };
325    // The configuration: present, valid, committed.
326    let config_dir = crate::verify::find_config(&root);
327    let text = config_dir
328        .as_ref()
329        .and_then(|d| std::fs::read_to_string(d.join(crate::verify::config::FILE)).ok());
330    let mut run_config = None;
331    let mut model = None;
332    match (&config_dir, &text) {
333        (Some(dir), Some(text)) => {
334            let parsed = crate::verify::config::parse(text)
335                .map(|_| ())
336                .and_then(|()| crate::substrate::model_config::parse(text).map(|m| model = m))
337                .and_then(|()| {
338                    crate::substrate::run_config::parse(text).map(|c| run_config = Some(c))
339                });
340            match parsed {
341                Err(e) => out.push(failed(
342                    "config",
343                    "CONFIG-INVALID",
344                    e,
345                    &["→ fix the line the message names in speccoder.toml"],
346                )),
347                Ok(()) => {
348                    let file = dir.join(crate::verify::config::FILE);
349                    let g = Git::at(dir);
350                    let tracked = g
351                        .succeeds(&[
352                            "ls-files",
353                            "--error-unmatch",
354                            "--",
355                            crate::verify::config::FILE,
356                        ])
357                        .unwrap_or(false);
358                    let clean = g
359                        .succeeds(&["diff", "--quiet", "HEAD", "--", crate::verify::config::FILE])
360                        .unwrap_or(false);
361                    out.push(if tracked && clean {
362                        check("config", DoctorLevel::Pass, file.display().to_string())
363                    } else {
364                        failed(
365                            "config",
366                            "CONFIG-NOT-TRACKED",
367                            format!("{} is not committed as it is: speccoder reads committed files only", file.display()),
368                            &["git add speccoder.toml && git commit -m \"speccoder: config\""],
369                        )
370                    });
371                }
372            }
373        }
374        _ => out.push(failed(
375            "config",
376            "CONFIG-MISSING",
377            "no speccoder.toml",
378            &["speccoder init"],
379        )),
380    }
381    // The model, then its key.
382    if let Some(m) = &model {
383        out.push(check(
384            "model",
385            DoctorLevel::Pass,
386            format!("{}/{}", m.provider, m.model),
387        ));
388        let variable = m.key_variable().to_owned();
389        if m.provider == "bedrock" {
390            out.extend(bedrock_key(m, env));
391        } else {
392            out.push(
393                if variable.is_empty() || env(&variable).is_some_and(|v| !v.is_empty()) {
394                    check(
395                        "model key",
396                        DoctorLevel::Pass,
397                        format!("{} {}", m.provider, m.model),
398                    )
399                } else {
400                    DoctorCheck {
401                        code: Some("KEY-MISSING".to_owned()),
402                        fix: vec![format!("export {variable}=…")],
403                        ..check(
404                            "model key",
405                            DoctorLevel::Fail,
406                            format!("{variable} is not set"),
407                        )
408                    }
409                },
410            );
411        }
412    }
413    // The sandbox.
414    let sandbox = text
415        .as_deref()
416        .and_then(|t| crate::sandbox::parse(t).ok())
417        .unwrap_or_default();
418    out.push(match (crate::sandbox::backend(), sandbox.mode) {
419        (Ok(b), _) => check(
420            "sandbox",
421            DoctorLevel::Pass,
422            format!("{b:?}").to_lowercase(),
423        ),
424        (Err(e), crate::sandbox::Mode::Required) => failed(
425            "sandbox",
426            "SANDBOX-UNAVAILABLE",
427            e,
428            &["→ run where the OS sandbox exists, or set [sandbox] mode = \"auto\""],
429        ),
430        (Err(e), crate::sandbox::Mode::Off) => {
431            check("sandbox", DoctorLevel::Warn, format!("off ({e})"))
432        }
433        (Err(e), crate::sandbox::Mode::Auto) => warned(
434            "sandbox",
435            format!("not available, commands run unsandboxed: {e}"),
436            &["→ prefer a container or VM without your credentials"],
437        ),
438    });
439    // `[worktree] include` and `.worktreeinclude`: what a run's worktree
440    // gets copied — names only, nothing copied.
441    let worktree = text
442        .as_deref()
443        .and_then(|t| crate::prepare::parse(t).ok())
444        .unwrap_or_default();
445    if let Some(dir) = crate::verify::find_config(path)
446        && let Some(row) = include_check(&dir, &worktree.include)
447    {
448        out.push(row);
449    }
450    // The state directory.
451    out.push(match crate::worktree::state_dir() {
452        Some(dir) => {
453            // Probed without creating it: a check writes nothing of its
454            // own — the directory, or the nearest folder it would be made
455            // in. The nearest path that exists must be a folder: a file
456            // there (the directory itself, or a parent) blocks creating it.
457            let existing = dir.ancestors().find(|a| a.exists());
458            let writable = existing
459                .filter(|a| a.is_dir())
460                .is_some_and(|a| tempfile::tempfile_in(a).is_ok());
461            if writable {
462                check("state", DoctorLevel::Pass, dir.display().to_string())
463            } else {
464                failed(
465                    "state",
466                    "NO-STATE-DIR",
467                    format!("{} is not writable", dir.display()),
468                    &["export SPECCODER_STATE_DIR=\"$PWD/.speccoder-state\""],
469                )
470            }
471        }
472        None => failed(
473            "state",
474            "NO-STATE-DIR",
475            "no state directory (SPECCODER_STATE_DIR, XDG_STATE_HOME and HOME are unset)",
476            &["export SPECCODER_STATE_DIR=\"$PWD/.speccoder-state\""],
477        ),
478    });
479    // A person's decisions: a file from before decisions named objects is
480    // refused by every run (never read as "no decisions").
481    if let Some(dir) = crate::worktree::state_dir() {
482        let project = crate::worktree::project_state_dir(&dir, &root);
483        if let Err(e) = crate::approvals::Decisions::load(&project) {
484            out.push(failed(
485                "decisions",
486                "CONFIG-INVALID",
487                e,
488                &[&format!(
489                    "rm {}   (it predates this version; its decisions are not carried over)",
490                    project.join(crate::approvals::FILE).display()
491                )],
492            ));
493        }
494    }
495    // The attestation signing key.
496    let attest = run_config
497        .as_ref()
498        .map(|c| c.attest.clone())
499        .unwrap_or_default();
500    if attest.enabled {
501        let repo = top.clone().unwrap_or_else(|| root.clone());
502        out.push(match crate::attest::sign::signer(&repo, &attest) {
503            Ok(s) => check(
504                "signing",
505                DoctorLevel::Pass,
506                format!("attestations signed with {}", s.kind()),
507            ),
508            Err(e) => {
509                let fix = signing_fix(
510                    std::env::var_os("HOME")
511                        .map(std::path::PathBuf::from)
512                        .as_deref(),
513                );
514                // Optional: every tick is attested either way; a key signs it.
515                DoctorCheck {
516                    fix,
517                    ..check(
518                        "signing",
519                        DoctorLevel::Info,
520                        format!("attestations are not signed (optional): {e}"),
521                    )
522                }
523            }
524        });
525    }
526    // GitHub (issues, pull requests): offline — the host the remote names
527    // and where a token would come from; optional either way.
528    if let Ok(r) = crate::github::repo(&root, None) {
529        let ctx = crate::github::Ctx::from_env();
530        out.push(match ctx.token(&r.host) {
531            Some((_, source)) => check(
532                "github",
533                DoctorLevel::Pass,
534                format!("{} on {} (token from {})", r.slug(), r.host, source.word()),
535            ),
536            None => DoctorCheck {
537                fix: vec!["speccoder auth login --with-token".to_owned()],
538                ..check(
539                    "github",
540                    DoctorLevel::Info,
541                    format!(
542                        "not signed in to {} (optional: for issues and pull requests)",
543                        r.host
544                    ),
545                )
546            },
547        });
548    }
549    // The repository's instructions for agents.
550    let names = run_config
551        .as_ref()
552        .map(|c| c.instructions.clone())
553        .unwrap_or_else(|| vec!["AGENTS.md".to_owned()]);
554    let repo = top.unwrap_or_else(|| root.clone());
555    let given = crate::instructions::collect(&repo, &root, &[], &names);
556    out.push(if !given.is_empty() {
557        check(
558            "instructions",
559            DoctorLevel::Pass,
560            given
561                .iter()
562                .map(|i| i.path.clone())
563                .collect::<Vec<_>>()
564                .join(", "),
565        )
566    } else if repo.join("CLAUDE.md").is_file() && !names.iter().any(|n| n == "CLAUDE.md") {
567        warned(
568            "instructions",
569            "CLAUDE.md is here but not read: attempts get no repository instructions",
570            &["→ add [context] instructions = [\"AGENTS.md\", \"CLAUDE.md\"] to speccoder.toml"],
571        )
572    } else {
573        check("instructions", DoctorLevel::Pass, "none (no AGENTS.md)")
574    });
575    out
576}
577
578/// `speccoder doctor`: the checks; the status of the first failure (ok
579/// when nothing fails).
580#[must_use]
581pub fn run(path: &Path, feature: Option<&str>, look: Option<&str>) -> CommandResult {
582    report(path, feature, look, None)
583}
584
585/// `speccoder doctor --agents`: the checks and every agent's card; with
586/// `probe`, each installed one is asked for a session (never a prompt).
587#[must_use]
588pub fn agents(path: &Path, feature: Option<&str>, probe: bool) -> CommandResult {
589    report(path, feature, None, Some(probe))
590}
591
592/// The configured `[executor]` agent, if it is an ACP one.
593fn configured_agent(path: &Path) -> Option<crate::acp::agent::Agent> {
594    let text = crate::verify::find_config(path)
595        .and_then(|d| std::fs::read_to_string(d.join(crate::verify::config::FILE)).ok())?;
596    match crate::external::parse(&text).ok()??.kind {
597        crate::external::Kind::Acp(a) => Some(a),
598        crate::external::Kind::Command(_) => None,
599    }
600}
601
602/// The `executor` row: the configured agent's card, as known without
603/// starting it.
604fn executor_check(agent: &crate::acp::agent::Agent) -> DoctorCheck {
605    let on_path = |x: &str| crate::acp::agent::on_path(x);
606    let Some(p) = agent.preset() else {
607        let argv = agent.command(on_path);
608        let runs = argv.first().is_some_and(|a| on_path(a));
609        return if runs {
610            check(
611                "executor",
612                DoctorLevel::Pass,
613                format!(
614                    "{} over ACP · not known whether it asks before it acts",
615                    argv.join(" ")
616                ),
617            )
618        } else {
619            warned(
620                "executor",
621                format!(
622                    "`{}` is not on PATH",
623                    argv.first().map_or("", String::as_str)
624                ),
625                &[],
626            )
627        };
628    };
629    let c = crate::acp::ready::card(p, Some(agent), &on_path, false);
630    let word = |t: &speccoder_core::AgentTick| match t.state {
631        speccoder_core::TickState::Yes => "yes",
632        speccoder_core::TickState::No => "no",
633        speccoder_core::TickState::Unknown => "not known",
634    };
635    let detail = format!(
636        "{} · installed: {} ({}) · signed in: {} ({}) · asks first: {} ({})",
637        c.name,
638        word(&c.installed),
639        c.installed.detail,
640        word(&c.signed_in),
641        c.signed_in.detail,
642        word(&c.asks_first),
643        c.asks_first.detail
644    );
645    let bad = [&c.installed, &c.asks_first]
646        .into_iter()
647        .find(|t| t.state == speccoder_core::TickState::No);
648    match bad {
649        None => check("executor", DoctorLevel::Pass, detail),
650        Some(t) => DoctorCheck {
651            fix: t.fix.clone(),
652            commands: t.commands.clone(),
653            ..warned("executor", detail, &[])
654        },
655    }
656}
657
658fn report(
659    path: &Path,
660    feature: Option<&str>,
661    look: Option<&str>,
662    cards: Option<bool>,
663) -> CommandResult {
664    let mut checks = checks(path, feature, &|k| std::env::var(k).ok());
665    let chosen = configured_agent(path);
666    if let Some(a) = &chosen {
667        checks.push(executor_check(a));
668    }
669    if let Some(look) = look {
670        checks.push(check("look", DoctorLevel::Pass, look));
671    }
672    let failures: Vec<&DoctorCheck> = checks
673        .iter()
674        .filter(|c| c.level == DoctorLevel::Fail)
675        .collect();
676    let warnings = checks
677        .iter()
678        .filter(|c| c.level == DoctorLevel::Warn)
679        .count();
680    let optional = checks
681        .iter()
682        .filter(|c| c.level == DoctorLevel::Info)
683        .count();
684    let report = DoctorReport {
685        speccoder: env!("CARGO_PKG_VERSION").to_owned(),
686        os: format!("{} {}", std::env::consts::OS, std::env::consts::ARCH),
687        checks: checks.clone(),
688        agents: cards.map_or_else(Vec::new, |probe| {
689            crate::acp::ready::cards(chosen.as_ref(), probe)
690        }),
691    };
692    let result = match failures.first() {
693        None => CommandResult::ok(
694            "doctor",
695            &format!(
696                "{} checks passed, {warnings} warning(s){}",
697                checks.len() - warnings - optional,
698                if optional > 0 {
699                    format!(", {optional} optional")
700                } else {
701                    String::new()
702                }
703            ),
704        ),
705        Some(first) => {
706            let entry = first
707                .code
708                .as_deref()
709                .and_then(speccoder_core::codes::lookup);
710            let status = entry.map_or(CommandStatus::Error, |e| e.status);
711            let message = format!(
712                "{} problem(s): {}",
713                failures.len(),
714                failures
715                    .iter()
716                    .map(|f| f.check.as_str())
717                    .collect::<Vec<_>>()
718                    .join(", ")
719            );
720            let mut r = CommandResult::new("doctor", status, &message).with_fix(first.fix.clone());
721            if let Some(code) = &first.code {
722                r = r.with_code(code);
723            }
724            r
725        }
726    };
727    result.with_data(CommandData::Doctor(Box::new(report)))
728}
729
730/// The `worktree include` row: the git-ignored files a run's worktree gets
731/// copied from this checkout, by name; none when nothing names any.
732fn include_check(project: &Path, patterns: &[String]) -> Option<DoctorCheck> {
733    if patterns.is_empty() && !project.join(crate::include::FILE).is_file() {
734        return None;
735    }
736    let files = crate::include::matched(project, patterns);
737    let protected = crate::tools::paths::Protected::default();
738    let masked = files.iter().filter(|f| protected.is_secret(f)).count();
739    Some(if files.is_empty() {
740        warned(
741            "worktree include",
742            "nothing to copy: no git-ignored file matches [worktree] include or .worktreeinclude",
743            &[],
744        )
745    } else {
746        check(
747            "worktree include",
748            DoctorLevel::Pass,
749            format!(
750                "copied into each run's worktree: {}{}",
751                files.join(", "),
752                if masked == 0 {
753                    String::new()
754                } else {
755                    format!(
756                        " ({masked} secret file(s): never committed, secret-named values masked)"
757                    )
758                }
759            ),
760        )
761    })
762}
763
764/// Untracked configuration a worktree will not have: speccoder works on
765/// commits, so a check that reads `.config/nextest.toml` or an untracked
766/// `*.toml` passes here and cannot run there.
767fn untracked_check(root: &Path, feature: Option<&str>) -> Option<DoctorCheck> {
768    let out = Git::at(root)
769        // NUL-separated: a name is never quoted or split.
770        .run(&[
771            "status",
772            "--porcelain",
773            "-z",
774            "--untracked-files=normal",
775            ".",
776        ])
777        .ok()?;
778    // Output and caches are no configuration: a worktree makes its own.
779    const OUTPUT: &[&str] = &[
780        ".DS_Store",
781        ".speccoder",
782        ".venv",
783        "venv",
784        "node_modules",
785        "target",
786        "__pycache__",
787        ".pytest_cache",
788        ".mypy_cache",
789        ".ruff_cache",
790        ".tox",
791        ".nox",
792        ".coverage",
793        "dist",
794        "build",
795        ".next",
796        ".turbo",
797        ".gradle",
798        ".idea",
799        ".vscode",
800    ];
801    let config = |p: &str| {
802        let name = p.trim_end_matches('/').rsplit('/').next().unwrap_or(p);
803        if OUTPUT.contains(&name) {
804            return false;
805        }
806        name.starts_with('.')
807            || [".toml", ".json", ".yaml", ".yml", ".cfg", ".ini"]
808                .iter()
809                .any(|e| name.ends_with(e))
810    };
811    let found: Vec<String> = String::from_utf8_lossy(&out)
812        .split('\0')
813        .filter_map(|l| l.strip_prefix("?? "))
814        .filter(|p| config(p))
815        .map(str::to_owned)
816        .collect();
817    if found.is_empty() {
818        return None;
819    }
820    let list = found.join(" ");
821    // The paths are the repository's: argvs, never a line read back.
822    // Literal pathspecs: a name like `*.json` or `:(top)x` is that file.
823    let mut add = ["git", "--literal-pathspecs", "add", "--"]
824        .map(str::to_owned)
825        .to_vec();
826    add.extend(found.iter().cloned());
827    let commit = ["git", "commit", "-m", "Track project config"]
828        .map(str::to_owned)
829        .to_vec();
830    let commands = vec![vec![add, commit]];
831    Some(DoctorCheck {
832        fix: commands
833            .iter()
834            .map(|c| speccoder_core::step::render(c))
835            .collect(),
836        commands,
837        // What of it a run needs, speccoder commits itself.
838        remedy: crate::code::setup_remedy(root, feature),
839        ..check(
840            "untracked",
841            DoctorLevel::Warn,
842            format!(
843                "{list} — not committed, so a worktree does not have it; a check that needs it cannot run there"
844            ),
845        )
846    })
847}
848
849/// Which unit commands work on when none is named, and why — or what
850/// stops them from knowing (several units, a pointer to a gone one).
851fn current_check(
852    format: &'static dyn crate::format::Adapter,
853    snap: &speccoder_core::snapshot::ProjectSnapshot,
854) -> DoctorCheck {
855    let unit = format.messages().unit;
856    let problem = snap
857        .diagnostics
858        .iter()
859        .find(|d| d.code == "select.ambiguous" || d.code == "select.not-found");
860    match (&snap.feature, problem) {
861        (Some(f), _) => check(
862            "feature",
863            DoctorLevel::Pass,
864            format!(
865                "{} ({})",
866                f.feature.name,
867                crate::current::reason_text(snap.selection.reason, format)
868            ),
869        ),
870        (None, Some(d)) => DoctorCheck {
871            fix: vec!["→ speccoder feature".to_owned()]
872                .into_iter()
873                .chain(d.hint.iter().map(|h| format!("→ {h}")))
874                .collect(),
875            ..check("feature", DoctorLevel::Warn, d.message.clone())
876        },
877        (None, None) if snap.features.is_empty() => check(
878            "feature",
879            DoctorLevel::Pass,
880            format!("no {unit}s yet — `speccoder spec specify \"…\"` creates one"),
881        ),
882        (None, None) => DoctorCheck {
883            fix: vec!["→ speccoder feature".to_owned()],
884            ..check("feature", DoctorLevel::Warn, format!("no current {unit}"))
885        },
886    }
887}
888
889/// Replaces values that look like secrets and the home directory.
890#[must_use]
891pub fn redact(text: &str) -> String {
892    let home = std::env::var("HOME").ok().filter(|h| h.len() > 1);
893    let mut out = String::with_capacity(text.len());
894    for word in
895        text.split_inclusive(|c: char| c.is_whitespace() || c == '"' || c == '\'' || c == '=')
896    {
897        let core =
898            word.trim_end_matches(|c: char| c.is_whitespace() || c == '"' || c == '\'' || c == '=');
899        let secret = [
900            "sk-ant-",
901            "sk-proj-",
902            "sk-",
903            "ghp_",
904            "github_pat_",
905            "AKIA",
906            "xoxb-",
907            "glpat-",
908        ]
909        .iter()
910        .any(|p| core.starts_with(p) && core.len() > p.len() + 8);
911        if secret {
912            out.push_str("[redacted]");
913            out.push_str(&word[core.len()..]);
914        } else {
915            out.push_str(word);
916        }
917    }
918    let out = crate::secrets::mask(&out);
919    match home {
920        Some(h) => out.replace(&h, "~"),
921        None => out,
922    }
923}
924
925/// The bug report of `doctor`'s `result` for the project at `root`:
926/// versions, every check, and the configuration — in Markdown, ready for
927/// an issue, with secrets and the home directory taken out.
928#[must_use]
929pub fn bug_report(result: &CommandResult, root: &Path) -> String {
930    let Some(CommandData::Doctor(d)) = result.data() else {
931        return redact(result.message());
932    };
933    let mut out = format!(
934        "### speccoder doctor\n\n- speccoder {}\n- {}\n\n| Check | Result | Detail |\n|---|---|---|\n",
935        d.speccoder, d.os
936    );
937    for c in &d.checks {
938        let level = match c.level {
939            DoctorLevel::Pass => "ok",
940            DoctorLevel::Info => "optional",
941            DoctorLevel::Warn => "warning",
942            DoctorLevel::Fail => "**fail**",
943        };
944        out.push_str(&format!(
945            "| {} | {level}{} | {} |\n",
946            c.check,
947            c.code
948                .as_deref()
949                .map(|c| format!(" `{c}`"))
950                .unwrap_or_default(),
951            c.detail.replace('|', "\\|").replace('\n', " ")
952        ));
953    }
954    let config = std::fs::read_to_string(root.join("speccoder.toml")).ok();
955    if let Some(text) = config {
956        out.push_str("\n<details><summary>speccoder.toml</summary>\n\n```toml\n");
957        out.push_str(text.trim_end());
958        out.push_str("\n```\n\n</details>\n");
959    }
960    redact(&out)
961}
962
963#[cfg(test)]
964mod tests {
965    use super::*;
966
967    #[test]
968    fn secrets_and_home_are_redacted() {
969        let home = std::env::var("HOME").unwrap_or_default();
970        let text = format!(
971            "key sk-ant-api03-abcdefghijklmnop at {home}/x ghp_0123456789abcdefghij \"sk-proj-aaaaaaaaaaaaaaaa\""
972        );
973        let r = redact(&text);
974        assert!(
975            !r.contains("abcdefghijklmnop") && !r.contains("0123456789abcdef"),
976            "{r}"
977        );
978        assert!(!r.contains("sk-proj-aaaa"), "{r}");
979        if home.len() > 1 {
980            assert!(!r.contains(&home) && r.contains("~/x"), "{r}");
981        }
982        assert!(r.contains("[redacted]"));
983        assert_eq!(redact("sk-short"), "sk-short");
984    }
985
986    #[test]
987    fn the_files_a_worktree_gets_copied_are_named_and_nothing_is_copied() {
988        let dir = tempfile::tempdir().unwrap();
989        let r = dir.path();
990        let git = |args: &[&str]| {
991            assert!(
992                Command::new("git")
993                    .args([
994                        "-c",
995                        "user.name=t",
996                        "-c",
997                        "user.email=t@e",
998                        "-c",
999                        "commit.gpgsign=false"
1000                    ])
1001                    .args(args)
1002                    .current_dir(r)
1003                    .status()
1004                    .unwrap()
1005                    .success()
1006            );
1007        };
1008        std::fs::write(r.join(".gitignore"), ".env\n*.local\n").unwrap();
1009        std::fs::write(r.join("app.local"), "x").unwrap();
1010        std::fs::write(r.join("tracked.local"), "x").unwrap();
1011        git(&["init", "-q"]);
1012        git(&["add", "-A"]);
1013        git(&["add", "-f", "tracked.local"]);
1014        git(&["commit", "-qm", "init"]);
1015        std::fs::write(r.join(".env"), "TOKEN=abcdefgh123\n").unwrap();
1016        assert!(include_check(r, &[]).is_none());
1017        let row = include_check(r, &[".env".to_owned()]).unwrap();
1018        assert_eq!(row.level, DoctorLevel::Pass);
1019        assert_eq!(
1020            row.detail,
1021            "copied into each run's worktree: .env (1 secret file(s): never committed, secret-named values masked)"
1022        );
1023        assert!(!row.detail.contains("abcdefgh123"));
1024        // `.worktreeinclude` too; a tracked file never.
1025        std::fs::write(r.join(".worktreeinclude"), "*.local\n").unwrap();
1026        let row = include_check(r, &[]).unwrap();
1027        assert_eq!(row.detail, "copied into each run's worktree: app.local");
1028        let row = include_check(r, &["nothing-here".to_owned()]).unwrap();
1029        assert_eq!(row.detail, "copied into each run's worktree: app.local");
1030    }
1031
1032    #[test]
1033    fn outside_any_repository_every_problem_is_named_with_its_fix() {
1034        let dir = tempfile::tempdir().unwrap();
1035        let checks = checks(dir.path(), None, &|_| None);
1036        let failing: Vec<(&str, Option<&str>)> = checks
1037            .iter()
1038            .filter(|c| c.level == DoctorLevel::Fail)
1039            .map(|c| (c.check.as_str(), c.code.as_deref()))
1040            .collect();
1041        assert!(
1042            failing.contains(&("repository", Some("NO-REPOSITORY"))),
1043            "{failing:?}"
1044        );
1045        assert!(
1046            failing.contains(&("project", Some("NO-PROJECT"))),
1047            "{failing:?}"
1048        );
1049        assert!(
1050            failing.contains(&("config", Some("CONFIG-MISSING"))),
1051            "{failing:?}"
1052        );
1053        for c in checks.iter().filter(|c| c.level != DoctorLevel::Pass) {
1054            assert!(!c.fix.is_empty(), "{} has no fix", c.check);
1055        }
1056    }
1057}
1058
1059/// How to sign with SSH: with a public key the person has, the newest kind
1060/// first; without one, make one first. Never a key that does not exist.
1061fn signing_fix(home: Option<&Path>) -> Vec<String> {
1062    let found = home.and_then(|h| {
1063        [
1064            "id_ed25519.pub",
1065            "id_ecdsa.pub",
1066            "id_ed25519_sk.pub",
1067            "id_ecdsa_sk.pub",
1068            "id_rsa.pub",
1069        ]
1070        .iter()
1071        .find(|k| h.join(".ssh").join(k).is_file())
1072    });
1073    let mut fix = Vec::new();
1074    let key = match found {
1075        Some(k) => format!("~/.ssh/{k}"),
1076        None => {
1077            fix.push("ssh-keygen -t ed25519".to_owned());
1078            "~/.ssh/id_ed25519.pub".to_owned()
1079        }
1080    };
1081    fix.push("git config --global gpg.format ssh".to_owned());
1082    fix.push(format!("git config --global user.signingKey {key}"));
1083    fix
1084}
1085
1086#[cfg(test)]
1087mod signing_tests {
1088    use super::*;
1089
1090    #[test]
1091    fn the_signing_fix_names_a_key_that_exists() {
1092        let home = tempfile::tempdir().unwrap_or_else(|e| panic!("{e}"));
1093        let none = signing_fix(Some(home.path()));
1094        assert_eq!(none[0], "ssh-keygen -t ed25519");
1095        std::fs::create_dir_all(home.path().join(".ssh")).unwrap_or_else(|e| panic!("{e}"));
1096        std::fs::write(home.path().join(".ssh/id_rsa.pub"), "ssh-rsa AAAA")
1097            .unwrap_or_else(|e| panic!("{e}"));
1098        let rsa = signing_fix(Some(home.path()));
1099        assert_eq!(
1100            rsa.last().map(String::as_str),
1101            Some("git config --global user.signingKey ~/.ssh/id_rsa.pub")
1102        );
1103        assert!(!rsa.iter().any(|f| f.starts_with("ssh-keygen")));
1104    }
1105}