Skip to main content

artifactize_core/diagnostics/
doctor.rs

1#[cfg(test)]
2mod tests;
3
4use std::path::{Path, PathBuf};
5
6use serde::Serialize;
7
8use crate::{
9    auth,
10    config::{Backend, Provider, read_workspace_config},
11    llm, release, store, workspace,
12};
13
14#[derive(Debug, Serialize)]
15#[serde(rename_all = "camelCase")]
16pub struct DoctorReport {
17    pub ok: bool,
18    #[serde(with = "crate::platform::path_serde")]
19    pub state_dir: PathBuf,
20    pub checks: Vec<Check>,
21}
22
23#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
24#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
25pub enum CheckStatus {
26    Pass,
27    Warn,
28    Fail,
29}
30impl CheckStatus {
31    fn ready(self) -> bool {
32        match self {
33            Self::Pass | Self::Warn => true,
34            Self::Fail => false,
35        }
36    }
37}
38impl std::fmt::Display for CheckStatus {
39    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
40        formatter.write_str(match self {
41            Self::Pass => "PASS",
42            Self::Warn => "WARN",
43            Self::Fail => "FAIL",
44        })
45    }
46}
47
48#[derive(Debug, Serialize)]
49pub struct Check {
50    pub name: &'static str,
51    pub status: CheckStatus,
52    pub message: String,
53    pub details: Details,
54}
55
56/// A readiness check's finite data domains; JSON is produced only by serialization.
57#[derive(Debug, Serialize)]
58#[serde(untagged)]
59pub enum Details {
60    None,
61    Config {
62        artifacts: usize,
63        evals: usize,
64    },
65    State {
66        writable: bool,
67    },
68    Schema {
69        schema: Option<u32>,
70    },
71    UnsupportedSchema {
72        schema: u32,
73        supported: u32,
74    },
75    Limits {
76        backends: std::collections::BTreeMap<Backend, u32>,
77    },
78    ApiKey {
79        present: bool,
80        #[serde(rename = "testEndpoint", skip_serializing_if = "Option::is_none")]
81        test_endpoint: Option<llm::TestEndpoint>,
82    },
83    Providers {
84        custom: std::collections::BTreeMap<
85            crate::config::CustomBackendName,
86            auth::providers::CustomView,
87        >,
88    },
89    NoRemote {
90        configured: bool,
91    },
92    Remote {
93        configured: bool,
94        url: url::Url,
95        share: auth::remote::Share,
96        #[serde(rename = "tokenSource")]
97        token_source: auth::remote::TokenSource,
98    },
99    Sessions {
100        enabled: bool,
101        sessions: usize,
102        bytes: u64,
103        #[serde(rename = "maxBytes")]
104        max_bytes: u64,
105        #[serde(rename = "targetBytes")]
106        target_bytes: u64,
107        #[serde(with = "crate::platform::path_serde")]
108        directory: PathBuf,
109        #[serde(rename = "stateId")]
110        state_id: Option<crate::types::StateId>,
111    },
112    Release {
113        channel: release::Channel,
114        running: semver::Version,
115        #[serde(skip_serializing_if = "Option::is_none")]
116        latest: Option<semver::Version>,
117        #[serde(skip_serializing_if = "Option::is_none")]
118        update: Option<release::Update>,
119    },
120    Codex {
121        #[serde(flatten)]
122        status: auth::codex::Status,
123        #[serde(rename = "testEndpoint", skip_serializing_if = "Option::is_none")]
124        test_endpoint: Option<llm::TestEndpoint>,
125        #[serde(rename = "testAuthEndpoint", skip_serializing_if = "Option::is_none")]
126        test_auth_endpoint: Option<llm::TestEndpoint>,
127    },
128    /// Claude Code's executable on `PATH`, or `null` without one.
129    ClaudeAgent {
130        #[serde(with = "crate::platform::path_serde::option")]
131        program: Option<PathBuf>,
132    },
133    /// The installed desktop app, or `null` without one.
134    Desktop {
135        #[serde(with = "crate::platform::path_serde::option")]
136        path: Option<PathBuf>,
137    },
138}
139
140/// Where a person without the desktop app installs it.
141const DESKTOP_INSTALL_PAGE: &str = "https://artifactize.dev/#start";
142
143impl DoctorReport {
144    fn add(&mut self, name: &'static str, status: CheckStatus, message: &str, details: Details) {
145        self.ok &= status.ready();
146        self.checks.push(Check {
147            name,
148            status,
149            message: message.into(),
150            details,
151        });
152    }
153}
154
155/// Local readiness, and whether a newer release is out. Missing optional backends and an
156/// older release are warnings, not failed reviews.
157pub async fn doctor(state: Option<&Path>, repo: Option<&Path>) -> Result<DoctorReport, String> {
158    let state = store::state_dir(state)?;
159    let mut report = DoctorReport {
160        ok: true,
161        state_dir: state.clone(),
162        checks: Vec::new(),
163    };
164    let config = repo.map(read_workspace_config).transpose();
165    if repo.is_some() {
166        match &config {
167            Ok(Some(config)) => report.add(
168                "config",
169                CheckStatus::Pass,
170                "Folder configuration is valid.",
171                Details::Config {
172                    artifacts: config.artifacts.len(),
173                    evals: config.evals.len(),
174                },
175            ),
176            Err(error) => report.add(
177                "config",
178                CheckStatus::Fail,
179                &error.to_string(),
180                Details::None,
181            ),
182            _ => unreachable!(),
183        }
184    }
185    let writable = (|| {
186        let state = workspace::canonical_target(&state)?;
187        if let Some(repo) = repo {
188            let repo = workspace::canonical_target(repo)?;
189            let repo = if crate::platform::paths::target_is_file(&repo) {
190                repo.parent().unwrap()
191            } else {
192                &repo
193            };
194            workspace::outside_workspace(repo, &state)?;
195        } else {
196            workspace::outside_artifact_workspaces(&state)?;
197        }
198        crate::platform::paths::probe_writable(&state)
199    })();
200    match writable {
201        Ok(()) => report.add(
202            "state",
203            CheckStatus::Pass,
204            "State directory is writable or can be created.",
205            Details::State { writable: true },
206        ),
207        Err(error) => report.add(
208            "state",
209            CheckStatus::Fail,
210            &error.to_string(),
211            Details::State { writable: false },
212        ),
213    }
214    // Existing-state preflight upgrades supported schemas without creating an absent database.
215    let current = store::STATE_SCHEMA_VERSION;
216    match store::state_schema(&state) {
217        Ok(None) => report.add(
218            "schema",
219            CheckStatus::Pass,
220            "No state database yet.",
221            Details::Schema { schema: None },
222        ),
223        Ok(Some(0)) => report.add(
224            "schema",
225            CheckStatus::Pass,
226            "The state database is not initialized yet.",
227            Details::Schema { schema: Some(0) },
228        ),
229        Ok(Some(found)) if found == current => report.add(
230            "schema",
231            CheckStatus::Pass,
232            &format!("State database schema {current}."),
233            Details::Schema {
234                schema: Some(current),
235            },
236        ),
237        Ok(Some(found)) => report.add(
238            "schema",
239            CheckStatus::Fail,
240            &store::schema_error(found),
241            Details::UnsupportedSchema {
242                schema: found,
243                supported: current,
244            },
245        ),
246        Err(error) => report.add("schema", CheckStatus::Fail, &error, Details::None),
247    }
248    match crate::limits::Limits::read(&state) {
249        Ok(limits) if limits.backends().is_empty() => report.add(
250            "limits",
251            CheckStatus::Pass,
252            "No backend capacity limits (limits.json).",
253            Details::Limits {
254                backends: Default::default(),
255            },
256        ),
257        Ok(limits) => report.add(
258            "limits",
259            CheckStatus::Pass,
260            &format!(
261                "Backend capacity on this machine: {}.",
262                limits
263                    .backends()
264                    .iter()
265                    .map(|(backend, slots)| format!("{backend} {slots}"))
266                    .collect::<Vec<_>>()
267                    .join(", ")
268            ),
269            Details::Limits {
270                backends: limits.backends().clone(),
271            },
272        ),
273        Err(error) => report.add("limits", CheckStatus::Fail, &error, Details::None),
274    }
275    let (status, message, details) = sessions(&state);
276    report.add("sessions", status, &message, details);
277    let providers = auth::providers::list(Some(&state), repo);
278    let keys = match &providers {
279        Ok(providers) => providers.keys.clone(),
280        Err(_) => Vec::new(),
281    };
282    for status in keys {
283        let backend = status.provider();
284        let (name, variable, source) = (backend.as_str(), status.variable(), status.source());
285        let present = source != auth::providers::KeySource::Absent;
286        let key = match source {
287            auth::providers::KeySource::Saved => format!(
288                "{variable} is absent; a saved {name} key is present (not validated with the provider)"
289            ),
290            _ => format!(
291                "{variable} is {} (not validated with the provider)",
292                if present { "present" } else { "absent" }
293            ),
294        };
295        match llm::test_endpoint(backend.into()) {
296            Ok(None) => report.add(
297                name,
298                if present {
299                    CheckStatus::Pass
300                } else {
301                    CheckStatus::Warn
302                },
303                &format!("{key}."),
304                Details::ApiKey { present, test_endpoint: None },
305            ),
306            // A test endpoint is never a production setup, so it always warns.
307            Ok(Some(endpoint)) => report.add(
308                name,
309                CheckStatus::Warn,
310                &format!(
311                    "{key}; {} sends this backend's requests to the local test endpoint {endpoint}.",
312                    llm::base_url_variable(backend.into()).unwrap_or_default()
313                ),
314                Details::ApiKey { present, test_endpoint: Some(endpoint) },
315            ),
316            Err(error) => report.add(
317                name,
318                CheckStatus::Fail,
319                &error,
320                Details::ApiKey {
321                    present,
322                    test_endpoint: None,
323                },
324            ),
325        }
326    }
327    match providers {
328        // Like Codex: nothing is stored there yet, so the refusal is advice.
329        Ok(auth::providers::Providers {
330            refused: Some(refusal),
331            custom,
332            ..
333        }) => report.add(
334            "providers",
335            CheckStatus::Warn,
336            &refusal,
337            Details::Providers { custom },
338        ),
339        Ok(providers) if providers.custom.is_empty() => report.add(
340            "providers",
341            CheckStatus::Pass,
342            "No custom providers are set up.",
343            Details::Providers {
344                custom: providers.custom,
345            },
346        ),
347        Ok(providers) => report.add(
348            "providers",
349            CheckStatus::Pass,
350            &format!(
351                "Custom providers on this machine: {}.",
352                providers
353                    .custom
354                    .iter()
355                    .map(|(name, custom)| match custom {
356                        auth::providers::CustomView::Alias { provider } => {
357                            format!("{name} (alias of {provider})")
358                        }
359                        auth::providers::CustomView::Endpoint { url, .. } => {
360                            format!("{name} ({})", url.as_str())
361                        }
362                    })
363                    .collect::<Vec<_>>()
364                    .join(", ")
365            ),
366            Details::Providers {
367                custom: providers.custom,
368            },
369        ),
370        Err(error) => report.add("providers", CheckStatus::Fail, &error, Details::None),
371    }
372    let (status, message, details) = codex();
373    report.add("codex", status, &message, details);
374    // Offline: only where `claude` is; its login and version are checked when a review or a
375    // model listing starts it.
376    match crate::platform::program::resolve(
377        std::path::Path::new(llm::claude_agent::command::PROGRAM),
378        &crate::platform::temporary_directory(),
379    ) {
380        Ok(program) => report.add(
381            "claude",
382            CheckStatus::Pass,
383            &format!(
384                "Claude Code is on PATH: {}; it signs in on its own (`claude auth status`).",
385                crate::platform::path_text(&program)
386            ),
387            Details::ClaudeAgent {
388                program: Some(program),
389            },
390        ),
391        Err(_) => report.add(
392            "claude",
393            CheckStatus::Warn,
394            "Claude Code (`claude`) is not on PATH; the claude backend needs it, signed in with `claude auth login`.",
395            Details::ClaudeAgent { program: None },
396        ),
397    }
398    // Offline: configuration and token storage only; `remote status` checks reachability.
399    match auth::remote::remote(Some(&state), repo) {
400        Ok(None) => report.add(
401            "remote",
402            CheckStatus::Pass,
403            "No remote review store is configured.",
404            Details::NoRemote { configured: false },
405        ),
406        Ok(Some(remote)) => {
407            let details = Details::Remote {
408                configured: true,
409                url: remote.url().clone(),
410                share: remote.share,
411                token_source: remote.token_source(),
412            };
413            if remote.token_source() == auth::remote::TokenSource::None {
414                report.add(
415                    "remote",
416                    CheckStatus::Warn,
417                    "No remote token; run `artifactize remote login URL` or set ARTIFACTIZE_REMOTE_TOKEN.",
418                    details,
419                );
420            } else {
421                report.add(
422                    "remote",
423                    CheckStatus::Pass,
424                    "Remote review store is configured; `remote status` checks reachability.",
425                    details,
426                );
427            }
428        }
429        Err(error) => report.add("remote", CheckStatus::Fail, &error, Details::None),
430    }
431    // The commands work without the app, so a missing app only warns.
432    match crate::platform::desktop_app::installed() {
433        Some(path) => report.add(
434            "desktop",
435            CheckStatus::Pass,
436            &format!(
437                "The desktop app is installed: {}.",
438                crate::platform::path_text(&path)
439            ),
440            Details::Desktop { path: Some(path) },
441        ),
442        None => report.add(
443            "desktop",
444            CheckStatus::Warn,
445            &format!("The desktop app is not installed; install it from {DESKTOP_INSTALL_PAGE}."),
446            Details::Desktop { path: None },
447        ),
448    }
449    let (status, message, details) = release_check(release::check(&state).await);
450    report.add("release", status, &message, details);
451    Ok(report)
452}
453
454/// Whether a newer release is out and how to update to it. Never a hard error: an older
455/// copy still works, and a failed lookup is asked again later.
456fn release_check(checked: release::Status) -> (CheckStatus, String, Details) {
457    use release::{Outcome, Unchecked, Update};
458    let release::Status {
459        running,
460        channel,
461        outcome,
462    } = checked;
463    let (status, message, latest, update) = match outcome {
464        Outcome::Unchecked(Unchecked::Store) => (
465            CheckStatus::Pass,
466            format!("The Microsoft Store keeps artifactize {running} up to date."),
467            None,
468            None,
469        ),
470        Outcome::Unchecked(Unchecked::Off) => (
471            CheckStatus::Pass,
472            format!(
473                "{} is set; releases are not looked up.",
474                release::OFF_VARIABLE
475            ),
476            None,
477            None,
478        ),
479        Outcome::Unchecked(Unchecked::Development) => (
480            CheckStatus::Pass,
481            format!("artifactize {running} is a development build; releases are not looked up."),
482            None,
483            None,
484        ),
485        Outcome::Latest(latest) => (
486            CheckStatus::Pass,
487            format!("artifactize {running} is up to date; the latest release is {latest}."),
488            Some(latest),
489            None,
490        ),
491        Outcome::Newer { latest, update } => {
492            let how = match &update {
493                Update::Command { command } => format!("run `{command}`"),
494                Update::Download { url, command: None } => format!("download and install {url}"),
495                Update::Download {
496                    url,
497                    command: Some(command),
498                } => format!("download {url}, then run `{command}`"),
499                Update::Page { url } => format!("see {url}"),
500            };
501            (
502                CheckStatus::Warn,
503                format!("artifactize {latest} is out (this is {running}); to update, {how}."),
504                Some(latest),
505                Some(update),
506            )
507        }
508        Outcome::Failed(error) => (
509            CheckStatus::Warn,
510            format!("Cannot look up the latest release: {error}"),
511            None,
512            None,
513        ),
514    };
515    (
516        status,
517        message,
518        Details::Release {
519            channel,
520            running,
521            latest,
522            update,
523        },
524    )
525}
526
527/// The saved Agent conversations: whether new ones are saved, the store's size against its
528/// bounds, and the state id their references name.
529fn sessions(state: &Path) -> (CheckStatus, String, Details) {
530    let bounds = match crate::limits::Limits::read(state) {
531        Ok(limits) => limits.agent_sessions(),
532        Err(_) => {
533            return (
534                CheckStatus::Fail,
535                "limits.json is invalid; see limits.".into(),
536                Details::None,
537            );
538        }
539    };
540    let usage = match crate::agent::session::usage(state) {
541        Ok(usage) => usage,
542        Err(error) => return (CheckStatus::Fail, error, Details::None),
543    };
544    // A database the schema check refuses has no id to report here.
545    let state_id = store::read_state_id(state).ok().flatten();
546    // Session storage uses binary mebibytes (2^20 bytes), not decimal megabytes.
547    const BYTES_PER_MIB: u64 = 1_048_576;
548    let mib = |bytes: u64| format!("{:.1} MiB", bytes as f64 / BYTES_PER_MIB as f64);
549    let message = format!(
550        "{} Agent session{} take {} of {}; a collection brings them down to {}.{}",
551        usage.sessions,
552        if usage.sessions == 1 { "" } else { "s" },
553        mib(usage.bytes),
554        mib(bounds.max_bytes()),
555        mib(bounds.target_bytes()),
556        if bounds.enabled() {
557            ""
558        } else {
559            " Saving is off (limits.json agentSessions.enabled)."
560        }
561    );
562    let details = Details::Sessions {
563        enabled: bounds.enabled(),
564        sessions: usage.sessions,
565        bytes: usage.bytes,
566        max_bytes: bounds.max_bytes(),
567        target_bytes: bounds.target_bytes(),
568        directory: crate::agent::session::directory(state),
569        state_id,
570    };
571    (CheckStatus::Pass, message, details)
572}
573
574/// The Codex CLI's sign-in, read offline from its store: no lock, refresh or network.
575fn codex() -> (CheckStatus, String, Details) {
576    let endpoints = llm::test_endpoint(Provider::Codex).and_then(|base| {
577        Ok((
578            base,
579            llm::variable_endpoint(auth::codex::AUTH_URL_VARIABLE)?,
580        ))
581    });
582    let ((base, sign_in), status) = match (endpoints, auth::codex::status()) {
583        (Err(error), _) | (_, Err(error)) => return (CheckStatus::Fail, error, Details::None),
584        (Ok(endpoints), Ok(status)) => (endpoints, status),
585    };
586    use auth::codex::{FileExpiry, Status};
587    let (mut level, mut message) = match &status {
588        Status::Absent => (
589            CheckStatus::Warn,
590            "The Codex CLI is not signed in; run `codex login`.".to_owned(),
591        ),
592        Status::File {
593            path,
594            expiry: FileExpiry::Usable { .. },
595        } => (
596            CheckStatus::Pass,
597            format!(
598                "The Codex CLI's sign-in in {} is used, and refreshed there when it expires.",
599                crate::platform::path_text(path)
600            ),
601        ),
602        Status::File {
603            path,
604            expiry: FileExpiry::Expired,
605        } => (
606            CheckStatus::Warn,
607            format!(
608                "The Codex CLI's sign-in in {} has expired; run `codex login` again.",
609                crate::platform::path_text(path)
610            ),
611        ),
612    };
613    for (variable, endpoint) in [
614        (
615            llm::base_url_variable(Provider::Codex).expect("Codex has a test endpoint"),
616            &base,
617        ),
618        (auth::codex::AUTH_URL_VARIABLE, &sign_in),
619    ] {
620        if let Some(endpoint) = endpoint {
621            level = CheckStatus::Warn;
622            message.push_str(&format!(
623                " {variable} points at the local test endpoint {endpoint}."
624            ));
625        }
626    }
627    let details = Details::Codex {
628        status,
629        test_endpoint: base,
630        test_auth_endpoint: sign_in,
631    };
632    (level, message, details)
633}