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    // What runs without asking.
440    let (fine, said) = crate::sandbox::contained_at(path);
441    out.push(check(
442        "contained",
443        if fine {
444            DoctorLevel::Pass
445        } else {
446            DoctorLevel::Warn
447        },
448        said,
449    ));
450    // `[worktree] include` and `.worktreeinclude`: what a run's worktree
451    // gets copied — names only, nothing copied.
452    let worktree = text
453        .as_deref()
454        .and_then(|t| crate::prepare::parse(t).ok())
455        .unwrap_or_default();
456    if let Some(dir) = crate::verify::find_config(path)
457        && let Some(row) = include_check(&dir, &worktree.include)
458    {
459        out.push(row);
460    }
461    // The state directory.
462    out.push(match crate::worktree::state_dir() {
463        Some(dir) => {
464            // Probed without creating it: a check writes nothing of its
465            // own — the directory, or the nearest folder it would be made
466            // in. The nearest path that exists must be a folder: a file
467            // there (the directory itself, or a parent) blocks creating it.
468            let existing = dir.ancestors().find(|a| a.exists());
469            let writable = existing
470                .filter(|a| a.is_dir())
471                .is_some_and(|a| tempfile::tempfile_in(a).is_ok());
472            if writable {
473                check("state", DoctorLevel::Pass, dir.display().to_string())
474            } else {
475                failed(
476                    "state",
477                    "NO-STATE-DIR",
478                    format!("{} is not writable", dir.display()),
479                    &["export SPECCODER_STATE_DIR=\"$PWD/.speccoder-state\""],
480                )
481            }
482        }
483        None => failed(
484            "state",
485            "NO-STATE-DIR",
486            "no state directory (SPECCODER_STATE_DIR, XDG_STATE_HOME and HOME are unset)",
487            &["export SPECCODER_STATE_DIR=\"$PWD/.speccoder-state\""],
488        ),
489    });
490    // A person's decisions: a file from before decisions named objects is
491    // refused by every run (never read as "no decisions").
492    if let Some(dir) = crate::worktree::state_dir() {
493        let project = crate::worktree::project_state_dir(&dir, &root);
494        if let Err(e) = crate::approvals::Decisions::load(&project) {
495            out.push(failed(
496                "decisions",
497                "CONFIG-INVALID",
498                e,
499                &[&format!(
500                    "rm {}   (it predates this version; its decisions are not carried over)",
501                    project.join(crate::approvals::FILE).display()
502                )],
503            ));
504        }
505    }
506    // The attestation signing key.
507    let attest = run_config
508        .as_ref()
509        .map(|c| c.attest.clone())
510        .unwrap_or_default();
511    if attest.enabled {
512        let repo = top.clone().unwrap_or_else(|| root.clone());
513        out.push(match crate::attest::sign::signer(&repo, &attest) {
514            Ok(s) => check(
515                "signing",
516                DoctorLevel::Pass,
517                format!("attestations signed with {}", s.kind()),
518            ),
519            Err(e) => {
520                let fix = signing_fix(
521                    std::env::var_os("HOME")
522                        .map(std::path::PathBuf::from)
523                        .as_deref(),
524                );
525                // Optional: every tick is attested either way; a key signs it.
526                DoctorCheck {
527                    fix,
528                    ..check(
529                        "signing",
530                        DoctorLevel::Info,
531                        format!("attestations are not signed (optional): {e}"),
532                    )
533                }
534            }
535        });
536    }
537    // GitHub (issues, pull requests): offline — the host the remote names
538    // and where a token would come from; optional either way.
539    if let Ok(r) = crate::github::repo(&root, None) {
540        let ctx = crate::github::Ctx::from_env();
541        out.push(match ctx.token(&r.host) {
542            Some((_, source)) => check(
543                "github",
544                DoctorLevel::Pass,
545                format!("{} on {} (token from {})", r.slug(), r.host, source.word()),
546            ),
547            None => DoctorCheck {
548                fix: vec!["speccoder auth login --with-token".to_owned()],
549                ..check(
550                    "github",
551                    DoctorLevel::Info,
552                    format!(
553                        "not signed in to {} (optional: for issues and pull requests)",
554                        r.host
555                    ),
556                )
557            },
558        });
559    }
560    // The repository's instructions for agents.
561    let names = run_config
562        .as_ref()
563        .map(|c| c.instructions.clone())
564        .unwrap_or_else(|| vec!["AGENTS.md".to_owned()]);
565    let repo = top.unwrap_or_else(|| root.clone());
566    let given = crate::instructions::collect(&repo, &root, &[], &names);
567    out.push(if !given.is_empty() {
568        check(
569            "instructions",
570            DoctorLevel::Pass,
571            given
572                .iter()
573                .map(|i| i.path.clone())
574                .collect::<Vec<_>>()
575                .join(", "),
576        )
577    } else if repo.join("CLAUDE.md").is_file() && !names.iter().any(|n| n == "CLAUDE.md") {
578        warned(
579            "instructions",
580            "CLAUDE.md is here but not read: attempts get no repository instructions",
581            &["→ add [context] instructions = [\"AGENTS.md\", \"CLAUDE.md\"] to speccoder.toml"],
582        )
583    } else {
584        check("instructions", DoctorLevel::Pass, "none (no AGENTS.md)")
585    });
586    out
587}
588
589/// `speccoder doctor`: the checks; the status of the first failure (ok
590/// when nothing fails).
591#[must_use]
592pub fn run(path: &Path, feature: Option<&str>, look: Option<&str>) -> CommandResult {
593    report(path, feature, look, None)
594}
595
596/// `speccoder doctor --agents`: the checks and every agent's card; with
597/// `probe`, each installed one is asked for a session (never a prompt).
598#[must_use]
599pub fn agents(path: &Path, feature: Option<&str>, probe: bool) -> CommandResult {
600    report(path, feature, None, Some(probe))
601}
602
603/// The configured `[executor]` agent, if it is an ACP one.
604fn configured_agent(path: &Path) -> Option<crate::acp::agent::Agent> {
605    let text = crate::verify::find_config(path)
606        .and_then(|d| std::fs::read_to_string(d.join(crate::verify::config::FILE)).ok())?;
607    match crate::external::parse(&text).ok()??.kind {
608        crate::external::Kind::Acp(a) => Some(a),
609        crate::external::Kind::Command(_) => None,
610    }
611}
612
613/// The `executor` row: the configured agent's card, as known without
614/// starting it.
615fn executor_check(agent: &crate::acp::agent::Agent) -> DoctorCheck {
616    let on_path = |x: &str| crate::acp::agent::on_path(x);
617    let Some(p) = agent.preset() else {
618        let argv = agent.command(on_path);
619        let runs = argv.first().is_some_and(|a| on_path(a));
620        return if runs {
621            check(
622                "executor",
623                DoctorLevel::Pass,
624                format!(
625                    "{} over ACP · not known whether it asks before it acts",
626                    argv.join(" ")
627                ),
628            )
629        } else {
630            warned(
631                "executor",
632                format!(
633                    "`{}` is not on PATH",
634                    argv.first().map_or("", String::as_str)
635                ),
636                &[],
637            )
638        };
639    };
640    let c = crate::acp::ready::card(p, Some(agent), &on_path, false);
641    let word = |t: &speccoder_core::AgentTick| match t.state {
642        speccoder_core::TickState::Yes => "yes",
643        speccoder_core::TickState::No => "no",
644        speccoder_core::TickState::Unknown => "not known",
645    };
646    let detail = format!(
647        "{} · installed: {} ({}) · signed in: {} ({}) · asks first: {} ({})",
648        c.name,
649        word(&c.installed),
650        c.installed.detail,
651        word(&c.signed_in),
652        c.signed_in.detail,
653        word(&c.asks_first),
654        c.asks_first.detail
655    );
656    let bad = [&c.installed, &c.asks_first]
657        .into_iter()
658        .find(|t| t.state == speccoder_core::TickState::No);
659    match bad {
660        None => check("executor", DoctorLevel::Pass, detail),
661        Some(t) => DoctorCheck {
662            fix: t.fix.clone(),
663            commands: t.commands.clone(),
664            ..warned("executor", detail, &[])
665        },
666    }
667}
668
669fn report(
670    path: &Path,
671    feature: Option<&str>,
672    look: Option<&str>,
673    cards: Option<bool>,
674) -> CommandResult {
675    let mut checks = checks(path, feature, &|k| std::env::var(k).ok());
676    let chosen = configured_agent(path);
677    if let Some(a) = &chosen {
678        checks.push(executor_check(a));
679    }
680    if let Some(look) = look {
681        checks.push(check("look", DoctorLevel::Pass, look));
682    }
683    let failures: Vec<&DoctorCheck> = checks
684        .iter()
685        .filter(|c| c.level == DoctorLevel::Fail)
686        .collect();
687    let warnings = checks
688        .iter()
689        .filter(|c| c.level == DoctorLevel::Warn)
690        .count();
691    let optional = checks
692        .iter()
693        .filter(|c| c.level == DoctorLevel::Info)
694        .count();
695    let report = DoctorReport {
696        speccoder: env!("CARGO_PKG_VERSION").to_owned(),
697        os: format!("{} {}", std::env::consts::OS, std::env::consts::ARCH),
698        checks: checks.clone(),
699        agents: cards.map_or_else(Vec::new, |probe| {
700            crate::acp::ready::cards(chosen.as_ref(), probe)
701        }),
702    };
703    let result = match failures.first() {
704        None => CommandResult::ok(
705            "doctor",
706            &format!(
707                "{} checks passed, {warnings} warning(s){}",
708                checks.len() - warnings - optional,
709                if optional > 0 {
710                    format!(", {optional} optional")
711                } else {
712                    String::new()
713                }
714            ),
715        ),
716        Some(first) => {
717            let entry = first
718                .code
719                .as_deref()
720                .and_then(speccoder_core::codes::lookup);
721            let status = entry.map_or(CommandStatus::Error, |e| e.status);
722            let message = format!(
723                "{} problem(s): {}",
724                failures.len(),
725                failures
726                    .iter()
727                    .map(|f| f.check.as_str())
728                    .collect::<Vec<_>>()
729                    .join(", ")
730            );
731            let mut r = CommandResult::new("doctor", status, &message).with_fix(first.fix.clone());
732            if let Some(code) = &first.code {
733                r = r.with_code(code);
734            }
735            r
736        }
737    };
738    result.with_data(CommandData::Doctor(Box::new(report)))
739}
740
741/// The `worktree include` row: the git-ignored files a run's worktree gets
742/// copied from this checkout, by name; none when nothing names any.
743fn include_check(project: &Path, patterns: &[String]) -> Option<DoctorCheck> {
744    if patterns.is_empty() && !project.join(crate::include::FILE).is_file() {
745        return None;
746    }
747    let files = crate::include::matched(project, patterns);
748    let protected = crate::tools::paths::Protected::default();
749    let masked = files.iter().filter(|f| protected.is_secret(f)).count();
750    Some(if files.is_empty() {
751        warned(
752            "worktree include",
753            "nothing to copy: no git-ignored file matches [worktree] include or .worktreeinclude",
754            &[],
755        )
756    } else {
757        check(
758            "worktree include",
759            DoctorLevel::Pass,
760            format!(
761                "copied into each run's worktree: {}{}",
762                files.join(", "),
763                if masked == 0 {
764                    String::new()
765                } else {
766                    format!(
767                        " ({masked} secret file(s): never committed, secret-named values masked)"
768                    )
769                }
770            ),
771        )
772    })
773}
774
775/// Untracked configuration a worktree will not have: speccoder works on
776/// commits, so a check that reads `.config/nextest.toml` or an untracked
777/// `*.toml` passes here and cannot run there.
778fn untracked_check(root: &Path, feature: Option<&str>) -> Option<DoctorCheck> {
779    let out = Git::at(root)
780        // NUL-separated: a name is never quoted or split.
781        .run(&[
782            "status",
783            "--porcelain",
784            "-z",
785            "--untracked-files=normal",
786            ".",
787        ])
788        .ok()?;
789    // Output and caches are no configuration: a worktree makes its own.
790    const OUTPUT: &[&str] = &[
791        ".DS_Store",
792        ".speccoder",
793        ".venv",
794        "venv",
795        "node_modules",
796        "target",
797        "__pycache__",
798        ".pytest_cache",
799        ".mypy_cache",
800        ".ruff_cache",
801        ".tox",
802        ".nox",
803        ".coverage",
804        "dist",
805        "build",
806        ".next",
807        ".turbo",
808        ".gradle",
809        ".idea",
810        ".vscode",
811    ];
812    let config = |p: &str| {
813        let name = p.trim_end_matches('/').rsplit('/').next().unwrap_or(p);
814        if OUTPUT.contains(&name) {
815            return false;
816        }
817        name.starts_with('.')
818            || [".toml", ".json", ".yaml", ".yml", ".cfg", ".ini"]
819                .iter()
820                .any(|e| name.ends_with(e))
821    };
822    let found: Vec<String> = String::from_utf8_lossy(&out)
823        .split('\0')
824        .filter_map(|l| l.strip_prefix("?? "))
825        .filter(|p| config(p))
826        .map(str::to_owned)
827        .collect();
828    if found.is_empty() {
829        return None;
830    }
831    let list = found.join(" ");
832    // The paths are the repository's: argvs, never a line read back.
833    // Literal pathspecs: a name like `*.json` or `:(top)x` is that file.
834    let mut add = ["git", "--literal-pathspecs", "add", "--"]
835        .map(str::to_owned)
836        .to_vec();
837    add.extend(found.iter().cloned());
838    let commit = ["git", "commit", "-m", "Track project config"]
839        .map(str::to_owned)
840        .to_vec();
841    let commands = vec![vec![add, commit]];
842    Some(DoctorCheck {
843        fix: commands
844            .iter()
845            .map(|c| speccoder_core::step::render(c))
846            .collect(),
847        commands,
848        // What of it a run needs, speccoder commits itself.
849        remedy: crate::code::setup_remedy(root, feature),
850        ..check(
851            "untracked",
852            DoctorLevel::Warn,
853            format!(
854                "{list} — not committed, so a worktree does not have it; a check that needs it cannot run there"
855            ),
856        )
857    })
858}
859
860/// Which unit commands work on when none is named, and why — or what
861/// stops them from knowing (several units, a pointer to a gone one).
862fn current_check(
863    format: &'static dyn crate::format::Adapter,
864    snap: &speccoder_core::snapshot::ProjectSnapshot,
865) -> DoctorCheck {
866    let unit = format.messages().unit;
867    let problem = snap
868        .diagnostics
869        .iter()
870        .find(|d| d.code == "select.ambiguous" || d.code == "select.not-found");
871    match (&snap.feature, problem) {
872        (Some(f), _) => check(
873            "feature",
874            DoctorLevel::Pass,
875            format!(
876                "{} ({})",
877                f.feature.name,
878                crate::current::reason_text(snap.selection.reason, format)
879            ),
880        ),
881        (None, Some(d)) => DoctorCheck {
882            fix: vec!["→ speccoder feature".to_owned()]
883                .into_iter()
884                .chain(d.hint.iter().map(|h| format!("→ {h}")))
885                .collect(),
886            ..check("feature", DoctorLevel::Warn, d.message.clone())
887        },
888        (None, None) if snap.features.is_empty() => check(
889            "feature",
890            DoctorLevel::Pass,
891            format!("no {unit}s yet — `speccoder spec specify \"…\"` creates one"),
892        ),
893        (None, None) => DoctorCheck {
894            fix: vec!["→ speccoder feature".to_owned()],
895            ..check("feature", DoctorLevel::Warn, format!("no current {unit}"))
896        },
897    }
898}
899
900/// Replaces values that look like secrets and the home directory.
901#[must_use]
902pub fn redact(text: &str) -> String {
903    let home = std::env::var("HOME").ok().filter(|h| h.len() > 1);
904    let mut out = String::with_capacity(text.len());
905    for word in
906        text.split_inclusive(|c: char| c.is_whitespace() || c == '"' || c == '\'' || c == '=')
907    {
908        let core =
909            word.trim_end_matches(|c: char| c.is_whitespace() || c == '"' || c == '\'' || c == '=');
910        let secret = [
911            "sk-ant-",
912            "sk-proj-",
913            "sk-",
914            "ghp_",
915            "github_pat_",
916            "AKIA",
917            "xoxb-",
918            "glpat-",
919        ]
920        .iter()
921        .any(|p| core.starts_with(p) && core.len() > p.len() + 8);
922        if secret {
923            out.push_str("[redacted]");
924            out.push_str(&word[core.len()..]);
925        } else {
926            out.push_str(word);
927        }
928    }
929    let out = crate::secrets::mask(&out);
930    match home {
931        Some(h) => out.replace(&h, "~"),
932        None => out,
933    }
934}
935
936/// The bug report of `doctor`'s `result` for the project at `root`:
937/// versions, every check, and the configuration — in Markdown, ready for
938/// an issue, with secrets and the home directory taken out.
939#[must_use]
940pub fn bug_report(result: &CommandResult, root: &Path) -> String {
941    let Some(CommandData::Doctor(d)) = result.data() else {
942        return redact(result.message());
943    };
944    let mut out = format!(
945        "### speccoder doctor\n\n- speccoder {}\n- {}\n\n| Check | Result | Detail |\n|---|---|---|\n",
946        d.speccoder, d.os
947    );
948    for c in &d.checks {
949        let level = match c.level {
950            DoctorLevel::Pass => "ok",
951            DoctorLevel::Info => "optional",
952            DoctorLevel::Warn => "warning",
953            DoctorLevel::Fail => "**fail**",
954        };
955        out.push_str(&format!(
956            "| {} | {level}{} | {} |\n",
957            c.check,
958            c.code
959                .as_deref()
960                .map(|c| format!(" `{c}`"))
961                .unwrap_or_default(),
962            c.detail.replace('|', "\\|").replace('\n', " ")
963        ));
964    }
965    let config = std::fs::read_to_string(root.join("speccoder.toml")).ok();
966    if let Some(text) = config {
967        out.push_str("\n<details><summary>speccoder.toml</summary>\n\n```toml\n");
968        out.push_str(text.trim_end());
969        out.push_str("\n```\n\n</details>\n");
970    }
971    redact(&out)
972}
973
974#[cfg(test)]
975mod tests {
976    use super::*;
977
978    #[test]
979    fn secrets_and_home_are_redacted() {
980        let home = std::env::var("HOME").unwrap_or_default();
981        let text = format!(
982            "key sk-ant-api03-abcdefghijklmnop at {home}/x ghp_0123456789abcdefghij \"sk-proj-aaaaaaaaaaaaaaaa\""
983        );
984        let r = redact(&text);
985        assert!(
986            !r.contains("abcdefghijklmnop") && !r.contains("0123456789abcdef"),
987            "{r}"
988        );
989        assert!(!r.contains("sk-proj-aaaa"), "{r}");
990        if home.len() > 1 {
991            assert!(!r.contains(&home) && r.contains("~/x"), "{r}");
992        }
993        assert!(r.contains("[redacted]"));
994        assert_eq!(redact("sk-short"), "sk-short");
995    }
996
997    #[test]
998    fn the_files_a_worktree_gets_copied_are_named_and_nothing_is_copied() {
999        let dir = tempfile::tempdir().unwrap();
1000        let r = dir.path();
1001        let git = |args: &[&str]| {
1002            assert!(
1003                Command::new("git")
1004                    .args([
1005                        "-c",
1006                        "user.name=t",
1007                        "-c",
1008                        "user.email=t@e",
1009                        "-c",
1010                        "commit.gpgsign=false"
1011                    ])
1012                    .args(args)
1013                    .current_dir(r)
1014                    .status()
1015                    .unwrap()
1016                    .success()
1017            );
1018        };
1019        std::fs::write(r.join(".gitignore"), ".env\n*.local\n").unwrap();
1020        std::fs::write(r.join("app.local"), "x").unwrap();
1021        std::fs::write(r.join("tracked.local"), "x").unwrap();
1022        git(&["init", "-q"]);
1023        git(&["add", "-A"]);
1024        git(&["add", "-f", "tracked.local"]);
1025        git(&["commit", "-qm", "init"]);
1026        std::fs::write(r.join(".env"), "TOKEN=abcdefgh123\n").unwrap();
1027        assert!(include_check(r, &[]).is_none());
1028        let row = include_check(r, &[".env".to_owned()]).unwrap();
1029        assert_eq!(row.level, DoctorLevel::Pass);
1030        assert_eq!(
1031            row.detail,
1032            "copied into each run's worktree: .env (1 secret file(s): never committed, secret-named values masked)"
1033        );
1034        assert!(!row.detail.contains("abcdefgh123"));
1035        // `.worktreeinclude` too; a tracked file never.
1036        std::fs::write(r.join(".worktreeinclude"), "*.local\n").unwrap();
1037        let row = include_check(r, &[]).unwrap();
1038        assert_eq!(row.detail, "copied into each run's worktree: app.local");
1039        let row = include_check(r, &["nothing-here".to_owned()]).unwrap();
1040        assert_eq!(row.detail, "copied into each run's worktree: app.local");
1041    }
1042
1043    #[test]
1044    fn outside_any_repository_every_problem_is_named_with_its_fix() {
1045        let dir = tempfile::tempdir().unwrap();
1046        let checks = checks(dir.path(), None, &|_| None);
1047        let failing: Vec<(&str, Option<&str>)> = checks
1048            .iter()
1049            .filter(|c| c.level == DoctorLevel::Fail)
1050            .map(|c| (c.check.as_str(), c.code.as_deref()))
1051            .collect();
1052        assert!(
1053            failing.contains(&("repository", Some("NO-REPOSITORY"))),
1054            "{failing:?}"
1055        );
1056        assert!(
1057            failing.contains(&("project", Some("NO-PROJECT"))),
1058            "{failing:?}"
1059        );
1060        assert!(
1061            failing.contains(&("config", Some("CONFIG-MISSING"))),
1062            "{failing:?}"
1063        );
1064        for c in checks.iter().filter(|c| c.level != DoctorLevel::Pass) {
1065            assert!(!c.fix.is_empty(), "{} has no fix", c.check);
1066        }
1067    }
1068}
1069
1070/// How to sign with SSH: with a public key the person has, the newest kind
1071/// first; without one, make one first. Never a key that does not exist.
1072fn signing_fix(home: Option<&Path>) -> Vec<String> {
1073    let found = home.and_then(|h| {
1074        [
1075            "id_ed25519.pub",
1076            "id_ecdsa.pub",
1077            "id_ed25519_sk.pub",
1078            "id_ecdsa_sk.pub",
1079            "id_rsa.pub",
1080        ]
1081        .iter()
1082        .find(|k| h.join(".ssh").join(k).is_file())
1083    });
1084    let mut fix = Vec::new();
1085    let key = match found {
1086        Some(k) => format!("~/.ssh/{k}"),
1087        None => {
1088            fix.push("ssh-keygen -t ed25519".to_owned());
1089            "~/.ssh/id_ed25519.pub".to_owned()
1090        }
1091    };
1092    fix.push("git config --global gpg.format ssh".to_owned());
1093    fix.push(format!("git config --global user.signingKey {key}"));
1094    fix
1095}
1096
1097#[cfg(test)]
1098mod signing_tests {
1099    use super::*;
1100
1101    #[test]
1102    fn the_signing_fix_names_a_key_that_exists() {
1103        let home = tempfile::tempdir().unwrap_or_else(|e| panic!("{e}"));
1104        let none = signing_fix(Some(home.path()));
1105        assert_eq!(none[0], "ssh-keygen -t ed25519");
1106        std::fs::create_dir_all(home.path().join(".ssh")).unwrap_or_else(|e| panic!("{e}"));
1107        std::fs::write(home.path().join(".ssh/id_rsa.pub"), "ssh-rsa AAAA")
1108            .unwrap_or_else(|e| panic!("{e}"));
1109        let rsa = signing_fix(Some(home.path()));
1110        assert_eq!(
1111            rsa.last().map(String::as_str),
1112            Some("git config --global user.signingKey ~/.ssh/id_rsa.pub")
1113        );
1114        assert!(!rsa.iter().any(|f| f.starts_with("ssh-keygen")));
1115    }
1116}