Skip to main content

bynk/
doctor.rs

1//! `bynk doctor` — the capability model, the checks, and the exit-code
2//! contract.
3//!
4//! Probes are **grouped by the capability they unlock**, not listed flat, so a
5//! compile-only user is never told they are "unhealthy" for lacking `wrangler`.
6//! The exit-code contract turns on *what an invocation asks about* (ADR: the
7//! doctor output / exit-code contract):
8//!
9//! - **Bare `bynk doctor`** is informational. It surveys everything but treats
10//!   only the *compile floor* (the linked-in compiler) as
11//!   required, so it exits `0` even with `test`/`dev` unavailable.
12//! - **`--only <capability>`** promotes that capability's tools to required.
13//! - **`--strict`** promotes *all* warnings (optional gaps, `npx`
14//!   provisionability, minor skew) to failures, for an all-green CI gate.
15
16use std::path::PathBuf;
17
18use bynk_driver::npm_install::PackageManager;
19
20use crate::probe::{self, DetectOpts, Probe, Provenance, Toolbox};
21
22/// A unit of work a user might want to do, and the tools it needs.
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub enum Capability {
25    /// Compile / check / fmt. Always satisfiable: the compiler is linked in.
26    Compile,
27    /// `bynk test` — Node and one of `tsc`/`tsx` (the runner ladder).
28    Test,
29    /// `dev` / deploy to Cloudflare — Node and `wrangler`.
30    Deploy,
31    /// Editor support — `bynk-lsp`. Optional; never a failure (except strict).
32    Editor,
33    /// Build Bynk from source — a Rust toolchain. Contributor-only; reported
34    /// only inside the Bynk repo.
35    BuildFromSource,
36}
37
38impl Capability {
39    pub fn token(self) -> &'static str {
40        match self {
41            Capability::Compile => "compile",
42            Capability::Test => "test",
43            Capability::Deploy => "deploy",
44            Capability::Editor => "editor",
45            Capability::BuildFromSource => "build",
46        }
47    }
48
49    /// Optional capabilities never fail a run on their own — they note, and
50    /// `--strict` escalates.
51    pub fn is_optional(self) -> bool {
52        matches!(self, Capability::Editor | Capability::BuildFromSource)
53    }
54}
55
56/// Health of a single row or a whole capability. Ordered: `Ok < Warn < Fail`.
57#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
58pub enum Level {
59    Ok,
60    Warn,
61    Fail,
62}
63
64/// One rendered line under a capability: a tool (or an any-of group like
65/// `tsc | tsx`), its health, a human detail, and a remedy when it is not `Ok`.
66#[derive(Debug, Clone)]
67pub struct Row {
68    pub label: String,
69    pub level: Level,
70    pub detail: String,
71    pub remedy: Option<String>,
72}
73
74/// A capability and its rows, with the aggregated health.
75#[derive(Debug, Clone)]
76pub struct CapabilityReport {
77    pub capability: Capability,
78    pub optional: bool,
79    pub rows: Vec<Row>,
80    pub level: Level,
81}
82
83/// The whole `doctor` result.
84#[derive(Debug, Clone)]
85pub struct Report {
86    pub driver_version: String,
87    pub capabilities: Vec<CapabilityReport>,
88}
89
90/// User-facing knobs.
91#[derive(Debug, Clone, Default)]
92pub struct DoctorOptions {
93    /// Scope the gate to one capability (promotes its tools to required).
94    pub only: Option<Capability>,
95    /// Escalate every warning to a failure.
96    pub strict: bool,
97}
98
99/// Environment facts the caller supplies (real values in `main`, fixed values
100/// in tests).
101#[derive(Debug, Clone)]
102pub struct Context {
103    /// Discovered project root (`bynk.toml`), for project-local resolution.
104    pub project_root: Option<PathBuf>,
105    /// Whether to include the contributor `build` capability.
106    pub in_repo: bool,
107    /// Minimum supported Node `(major, minor)` (single-sourced from
108    /// `bynk_emit::NODE_FLOOR`).
109    pub node_floor: (u32, u32),
110}
111
112impl Report {
113    /// Should the process exit non-zero, given the options?
114    ///
115    /// Non-zero iff a *required* capability has a hard failure, or — under
116    /// `--strict` — any capability is less than `Ok`. The compile floor is
117    /// always required; `--only <cap>` adds that capability.
118    pub fn exit_nonzero(&self, opts: &DoctorOptions) -> bool {
119        for cap in &self.capabilities {
120            let required =
121                cap.capability == Capability::Compile || opts.only == Some(cap.capability);
122            if required && cap.level == Level::Fail {
123                return true;
124            }
125        }
126        if opts.strict && self.capabilities.iter().any(|c| c.level != Level::Ok) {
127            return true;
128        }
129        false
130    }
131
132    /// One-word overall summary for the human header.
133    pub fn is_all_ok(&self) -> bool {
134        self.capabilities.iter().all(|c| c.level == Level::Ok)
135    }
136}
137
138/// Run the checks against a toolbox.
139pub fn diagnose(tb: &dyn Toolbox, ctx: &Context, opts: &DoctorOptions) -> Report {
140    let root = ctx.project_root.as_deref();
141    let mut compile = compile_report();
142    // #2240: a project with git dependencies needs `git` to fetch them.
143    if root.is_some_and(has_git_dependencies) {
144        compile.rows.push(detect_plain(
145            tb,
146            "git",
147            "install git — this project has git dependencies, which `bynk fetch` clones",
148        ));
149        compile.level = compile
150            .rows
151            .iter()
152            .map(|r| r.level)
153            .max()
154            .unwrap_or(Level::Ok);
155    }
156    let mut capabilities = vec![compile];
157
158    // Only build the capability the user scoped to (plus the always-on compile
159    // floor), so `--only test` doesn't probe Cloudflare. With no filter, build
160    // them all.
161    let want = |cap: Capability| opts.only.is_none() || opts.only == Some(cap);
162
163    if want(Capability::Test) {
164        let node = detect_node(tb, root, ctx.node_floor);
165        let runner = detect_runner(tb, root);
166        let packages = detect_package_manager(tb, root);
167        capabilities.push(capability(Capability::Test, vec![node, runner, packages]));
168    }
169    if want(Capability::Deploy) {
170        let node = detect_node(tb, root, ctx.node_floor);
171        let wrangler = detect_wrangler(tb, root);
172        let packages = detect_package_manager(tb, root);
173        let mut rows = vec![node, wrangler, packages];
174        // #3477: only a project that declares a container has a use for Docker,
175        // so only its report carries the row.
176        if root.is_some_and(declares_container) {
177            rows.push(detect_docker(tb));
178        }
179        capabilities.push(capability(Capability::Deploy, rows));
180    }
181    if want(Capability::Editor) {
182        let lsp = detect_plain(
183            tb,
184            "bynk-lsp",
185            "install bynk-lsp (or download from releases)",
186        );
187        capabilities.push(capability(Capability::Editor, vec![lsp]));
188    }
189    if ctx.in_repo && want(Capability::BuildFromSource) {
190        let cargo = detect_plain(tb, "cargo", "install Rust via https://rustup.rs");
191        capabilities.push(capability(Capability::BuildFromSource, vec![cargo]));
192    }
193
194    Report {
195        driver_version: crate::DRIVER_VERSION.to_string(),
196        capabilities,
197    }
198}
199
200/// Compile/check/fmt/test. The compiler is **linked in-process** (ADR 0101), so it
201/// is always available and cannot skew against itself — the always-ok row. There
202/// is no external compiler to resolve or report on (#2998, ADR 0736).
203fn compile_report() -> CapabilityReport {
204    CapabilityReport {
205        capability: Capability::Compile,
206        optional: false,
207        rows: vec![Row {
208            label: "compiler".into(),
209            level: Level::Ok,
210            detail: "in-process".into(),
211            remedy: None,
212        }],
213        level: Level::Ok,
214    }
215}
216
217/// Aggregate a capability from its rows (worst row wins).
218fn capability(cap: Capability, rows: Vec<Row>) -> CapabilityReport {
219    let level = rows.iter().map(|r| r.level).max().unwrap_or(Level::Ok);
220    CapabilityReport {
221        capability: cap,
222        optional: cap.is_optional(),
223        rows,
224        level,
225    }
226}
227
228fn detect_node(tb: &dyn Toolbox, root: Option<&std::path::Path>, floor: (u32, u32)) -> Row {
229    // A runtime is never npx-provisionable.
230    let probe = probe::detect(
231        tb,
232        "node",
233        DetectOpts {
234            project_root: root,
235            allow_npx: false,
236            manager: None,
237        },
238    );
239    let shown = format!("{}.{}", floor.0, floor.1);
240    let remedy = format!("install Node.js ≥ {shown} from https://nodejs.org");
241    if probe.is_missing() {
242        return Row {
243            label: "node".into(),
244            level: Level::Fail,
245            detail: "missing".into(),
246            remedy: Some(remedy),
247        };
248    }
249    let below = probe
250        .version
251        .map(|v| (v.major, v.minor) < floor)
252        .unwrap_or(false);
253    if below {
254        let v = probe.version.unwrap();
255        return Row {
256            label: "node".into(),
257            level: Level::Warn,
258            detail: format!("v{v} below floor (≥ {shown})"),
259            remedy: Some(remedy),
260        };
261    }
262    Row {
263        label: "node".into(),
264        level: Level::Ok,
265        detail: present_detail(&probe),
266        remedy: None,
267    }
268}
269
270/// The `tsc | tsx` runner requirement — satisfied by the *better* of the two.
271fn detect_runner(tb: &dyn Toolbox, root: Option<&std::path::Path>) -> Row {
272    let manager = tool_manager(tb, root);
273    let opts = DetectOpts {
274        project_root: root,
275        allow_npx: true,
276        manager: Some(manager),
277    };
278    let tsc = probe::detect(tb, "tsc", opts);
279    let tsx = probe::detect(tb, "tsx", opts);
280    let best = pick_better(&tsc, &tsx);
281    let tested = bynk_emit::TYPESCRIPT_MAJOR_TESTED;
282    // #1672: lead with the TypeScript that is verified, and the one that
283    // type-checks; `tsx` only runs the emitted code.
284    let remedy = format!(
285        "{} (or `{}`, which runs tests without type-checking)",
286        manager.global_install(&bynk_driver::tools::pins::typescript_spec()),
287        manager.global_install(bynk_driver::tools::pins::TSX_SPEC)
288    );
289    match best {
290        // #1672, #3420: a `tsc` below the supported major is unsupported, a real defect
291        // in this environment, so it warns. One above the tested major is
292        // *reported* as untested but stays `ok`: it is a statement about this
293        // repo's verification coverage, not a fault the user has, and a
294        // warning would turn `doctor --strict` red for everyone the day a new
295        // TypeScript major ships, with advice to downgrade a likely-working
296        // toolchain.
297        Some(p) if p.is_present() && p.tool == "tsc" => {
298            let detail = format!("{} {}", p.tool, present_detail(p));
299            match p.version.map(|v| v.major) {
300                Some(major) if major < tested => Row {
301                    label: "tsc | tsx".into(),
302                    level: Level::Warn,
303                    detail: format!("{detail}, below supported (≥ {tested})"),
304                    remedy: Some(remedy),
305                },
306                Some(major) if major > tested => Row {
307                    label: "tsc | tsx".into(),
308                    level: Level::Ok,
309                    detail: format!("{detail}, untested (verified up to {tested})"),
310                    remedy: None,
311                },
312                _ => Row {
313                    label: "tsc | tsx".into(),
314                    level: Level::Ok,
315                    detail,
316                    remedy: None,
317                },
318            }
319        }
320        Some(p) if p.is_present() => Row {
321            label: "tsc | tsx".into(),
322            level: Level::Ok,
323            detail: format!("{} {}", p.tool, present_detail(p)),
324            remedy: None,
325        },
326        Some(p) => Row {
327            // provisionable through the package manager's runner
328            label: "tsc | tsx".into(),
329            level: Level::Warn,
330            detail: format!(
331                "{} provisionable via {} (not installed)",
332                p.tool,
333                p.provenance.runner_label().unwrap_or("npx")
334            ),
335            remedy: Some(remedy),
336        },
337        None => Row {
338            label: "tsc | tsx".into(),
339            level: Level::Fail,
340            detail: "missing".into(),
341            remedy: Some(remedy),
342        },
343    }
344}
345
346/// #1732: an installed wrangler older than [`bynk_emit::WRANGLER_MIN`], whose
347/// `workerd` may therefore refuse the pinned [`bynk_emit::COMPATIBILITY_DATE`].
348/// `false` for an npx-provisioned or unversioned wrangler, which can't be
349/// judged without running it. Shared by `doctor`'s row and `bynk dev`'s notice.
350pub fn wrangler_below_min(probe: &Probe) -> bool {
351    let min = probe::Version::parse(bynk_emit::WRANGLER_MIN).expect("WRANGLER_MIN is a version");
352    probe.is_present()
353        && probe
354            .version
355            .is_some_and(|v| (v.major, v.minor, v.patch) < (min.major, min.minor, min.patch))
356}
357
358/// #1732: how to upgrade a too-old wrangler, for where it came from. A
359/// project's own wrangler (which the driver prefers over `PATH`) is upgraded in
360/// the project, since a global install wouldn't change what runs. Shared by
361/// `doctor`'s row and `bynk dev`'s notice so the two can't disagree. No version
362/// in it: it shows in every `--format short` line and the goldens.
363pub fn wrangler_upgrade_remedy(probe: &Probe, manager: PackageManager) -> String {
364    match probe.provenance {
365        Provenance::ProjectLocal(_) => {
366            format!(
367                "{} (in the project)",
368                manager.dev_install(bynk_driver::tools::pins::WRANGLER_SPEC)
369            )
370        }
371        _ => manager.global_install(bynk_driver::tools::pins::WRANGLER_SPEC),
372    }
373}
374
375/// The package manager the toolchain's tool fallbacks and hints follow for the
376/// project at `root`: the detected one, or npm with no project.
377fn tool_manager(tb: &dyn Toolbox, root: Option<&std::path::Path>) -> PackageManager {
378    root.map_or(PackageManager::Npm, |r| {
379        bynk_driver::npm_install::manager_in(r, tb)
380    })
381}
382
383/// #1732: wrangler, checked against [`bynk_emit::WRANGLER_MIN`], the oldest this
384/// release supports (it serves the [`bynk_emit::COMPATIBILITY_DATE`] every
385/// generated `wrangler.toml` pins). An older one's `workerd` may refuse the date,
386/// so `bynk dev` fails. Below it, `bynk deploy` also refuses to push a Durable
387/// Object class (`deploy::plan::wrangler_floor_refusal`), since an older wrangler
388/// is untested against the generated configuration (#1796: it reads the `exports`
389/// map only from 4.107.0). A project with no agent still deploys (Cloudflare
390/// accepts any past date).
391/// Doctor doesn't know which kind of project it is, so this stays a warning,
392/// not a failure, and `doctor --only deploy` doesn't go red on a toolchain
393/// that deploys an agent-free project. An npx-provisioned wrangler's version isn't known
394/// without running npx (which may download), so its row keeps the usual
395/// "provisionable" warning, and the remedy says to clear a stale npx cache: one
396/// older than the minimum fails the same way, because npx keys the cache on the
397/// spec `wrangler@4`, not the version.
398fn detect_wrangler(tb: &dyn Toolbox, root: Option<&std::path::Path>) -> Row {
399    let min = bynk_emit::WRANGLER_MIN;
400    let date = bynk_emit::COMPATIBILITY_DATE;
401    // No version or date in a remedy: it shows in every `--format short` line
402    // (and the goldens), which a compatibility-date review shouldn't churn. The
403    // below-minimum detail names both. Each remedy fits where wrangler came
404    // from: a project's own wrangler is upgraded in the project, and only an npx
405    // one can be a stale cache.
406    let manager = tool_manager(tb, root);
407    let install = manager.global_install(bynk_driver::tools::pins::WRANGLER_SPEC);
408    let probe = probe::detect(
409        tb,
410        "wrangler",
411        DetectOpts {
412            project_root: root,
413            allow_npx: true,
414            manager: Some(manager),
415        },
416    );
417    if wrangler_below_min(&probe) {
418        let remedy = wrangler_upgrade_remedy(&probe, manager);
419        return Row {
420            label: "wrangler".into(),
421            level: Level::Warn,
422            detail: format!(
423                "{}, below {min}, the oldest this Bynk release supports: `bynk dev` may not serve compatibility date {date}, and agents can't deploy",
424                present_detail(&probe)
425            ),
426            remedy: Some(remedy),
427        };
428    }
429    let mut row = npm_row("wrangler", &probe, &install);
430    // Only npx keys a cache on the spec (`wrangler@4`), so only it can be stale.
431    if probe.provenance == Provenance::Runner(PackageManager::Npm) {
432        row.remedy = Some(format!(
433            "{install}, or clear a stale npx cache (~/.npm/_npx)"
434        ));
435    }
436    row
437}
438
439/// #2240: whether the project at `root` (or its workspace) declares a git
440/// dependency.
441fn has_git_dependencies(root: &std::path::Path) -> bool {
442    let Ok(text) = std::fs::read_to_string(root.join("bynk.toml")) else {
443        return false;
444    };
445    let Ok(doc) = text.parse::<toml::Table>() else {
446        return false;
447    };
448    ["dependencies", "dev-dependencies"].iter().any(|table| {
449        doc.get(*table).and_then(|v| v.as_table()).is_some_and(|t| {
450            t.values()
451                .any(|e| e.as_table().is_some_and(|e| e.contains_key("git")))
452        })
453    })
454}
455
456/// #3350: the package manager `bynk test`, `bynk dev` and `bynk deploy` install
457/// the generated project's npm packages with, and the rule that chose it.
458fn detect_package_manager(tb: &dyn Toolbox, root: Option<&std::path::Path>) -> Row {
459    use bynk_driver::npm_install::{self, Project};
460
461    /// The project root's files (none without a root) and the real environment.
462    struct View<'a>(Option<&'a std::path::Path>);
463    impl Project for View<'_> {
464        fn read(&self, name: &str) -> Option<String> {
465            self.0.and_then(|r| npm_install::RealProject(r).read(name))
466        }
467        fn exists(&self, name: &str) -> bool {
468            self.0
469                .is_some_and(|r| npm_install::RealProject(r).exists(name))
470        }
471        fn env(&self, key: &str) -> Option<String> {
472            std::env::var(key).ok().filter(|v| !v.trim().is_empty())
473        }
474    }
475
476    let setting = root.and_then(npm_install::configured_manager);
477    match npm_install::detect(&View(root), setting.as_deref(), tb) {
478        Ok(found) => Row {
479            label: "package manager".into(),
480            level: Level::Ok,
481            detail: format!("{} ({})", found.manager.name(), found.rule.describe()),
482            remedy: None,
483        },
484        // A package manager that cannot be chosen is a hard error for a run that
485        // needs to install, so an unknown explicit setting warns.
486        Err(e @ npm_install::DetectError::UnknownManager { .. }) => Row {
487            label: "package manager".into(),
488            level: Level::Warn,
489            detail: "unknown".into(),
490            remedy: Some(e.to_string()),
491        },
492        // Informational: only a project with npm dependencies needs one, so
493        // its absence is not a fault (it would turn `--strict` red for others).
494        Err(e) => Row {
495            label: "package manager".into(),
496            level: Level::Ok,
497            detail: format!("none found ({e})"),
498            remedy: None,
499        },
500    }
501}
502
503/// Whether the project declares a `Container` (`capability X = Container …`):
504/// a text scan of its `.bynk` files, which skips dependency, build and VCS
505/// directories. A comment that spells the declaration counts, which only makes
506/// the Docker row louder than it needs to be.
507pub(crate) fn declares_container(root: &std::path::Path) -> bool {
508    fn walk(dir: &std::path::Path, depth: usize) -> bool {
509        let Ok(entries) = std::fs::read_dir(dir) else {
510            return false;
511        };
512        entries.flatten().any(|entry| {
513            let path = entry.path();
514            let name = entry.file_name();
515            let name = name.to_string_lossy();
516            if path.is_dir() {
517                depth < 8
518                    && !matches!(
519                        name.as_ref(),
520                        "node_modules" | "target" | "out" | "dist" | ".git"
521                    )
522                    && walk(&path, depth + 1)
523            } else {
524                name.ends_with(".bynk")
525                    && std::fs::read_to_string(&path).is_ok_and(|text| {
526                        text.lines().any(|l| {
527                            l.trim_start().starts_with("capability ")
528                                && l.split_once("= Container").is_some_and(|(_, rest)| {
529                                    !rest.starts_with(|c: char| c.is_alphanumeric() || c == '_')
530                                })
531                        })
532                    })
533            }
534        })
535    }
536    walk(root, 0)
537}
538
539/// #3477: Docker, which `bynk deploy` needs only to build a `Container`'s image
540/// from its Dockerfile (an adopted image needs none). Listed only for a project
541/// that declares a container ([`declares_container`]); a missing or stopped
542/// Docker is a warning, not a failure, since the deploy may adopt an image
543/// instead. Worth knowing before a deploy that needs it.
544fn detect_docker(tb: &dyn Toolbox) -> Row {
545    const REMEDY: &str = "needed only to build a Container's image at deploy: start Docker, or adopt a prebuilt image in bynk.toml ([deploy.containers.<Capability>])";
546    let probe = probe::detect(
547        tb,
548        "docker",
549        DetectOpts {
550            project_root: None,
551            allow_npx: false,
552            manager: None,
553        },
554    );
555    let path = match &probe.provenance {
556        Provenance::Path(path) | Provenance::ProjectLocal(path) => Some(path.clone()),
557        _ => None,
558    };
559    let warn = |detail: String| Row {
560        label: "docker".into(),
561        level: Level::Warn,
562        detail,
563        remedy: Some(REMEDY.into()),
564    };
565    let Some(path) = path.filter(|_| probe.is_present()) else {
566        return warn("not found".into());
567    };
568    if tb.docker_daemon_running(&path) {
569        Row {
570            label: "docker".into(),
571            level: Level::Ok,
572            detail: format!("{} (daemon running)", present_detail(&probe)),
573            remedy: None,
574        }
575    } else {
576        warn(format!("{} (no daemon running)", present_detail(&probe)))
577    }
578}
579
580fn detect_plain(tb: &dyn Toolbox, tool: &str, remedy: &str) -> Row {
581    let probe = probe::detect(
582        tb,
583        tool,
584        DetectOpts {
585            project_root: None,
586            allow_npx: false,
587            manager: None,
588        },
589    );
590    if probe.is_present() {
591        Row {
592            label: tool.into(),
593            level: Level::Ok,
594            detail: present_detail(&probe),
595            remedy: None,
596        }
597    } else {
598        Row {
599            label: tool.into(),
600            level: Level::Fail,
601            detail: "missing".into(),
602            remedy: Some(remedy.into()),
603        }
604    }
605}
606
607fn npm_row(tool: &str, probe: &Probe, remedy: &str) -> Row {
608    if probe.is_present() {
609        Row {
610            label: tool.into(),
611            level: Level::Ok,
612            detail: present_detail(probe),
613            remedy: None,
614        }
615    } else if probe.is_provisionable() {
616        Row {
617            label: tool.into(),
618            level: Level::Warn,
619            detail: format!(
620                "provisionable via {} (not installed)",
621                probe.provenance.runner_label().unwrap_or("npx")
622            ),
623            remedy: Some(remedy.into()),
624        }
625    } else {
626        Row {
627            label: tool.into(),
628            level: Level::Fail,
629            detail: "missing".into(),
630            remedy: Some(remedy.into()),
631        }
632    }
633}
634
635/// `path`/`project-local` beats `npx` beats `missing`; among installed, prefer
636/// the first argument (caller order).
637fn pick_better<'a>(a: &'a Probe, b: &'a Probe) -> Option<&'a Probe> {
638    fn rank(p: &Probe) -> u8 {
639        if p.is_present() {
640            2
641        } else if p.is_provisionable() {
642            1
643        } else {
644            0
645        }
646    }
647    let (ra, rb) = (rank(a), rank(b));
648    if ra == 0 && rb == 0 {
649        None
650    } else if ra >= rb {
651        Some(a)
652    } else {
653        Some(b)
654    }
655}
656
657fn present_detail(probe: &Probe) -> String {
658    let ver = probe
659        .version
660        .map(|v| format!("v{v}"))
661        .unwrap_or_else(|| "installed".into());
662    format!("{ver} ({})", probe.provenance.token())
663}