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