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#[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 ClaudeAgent {
127 #[serde(with = "crate::platform::path_serde::option")]
128 program: Option<PathBuf>,
129 },
130 Desktop {
132 #[serde(with = "crate::platform::path_serde::option")]
133 path: Option<PathBuf>,
134 },
135}
136
137const DESKTOP_INSTALL_PAGE: &str = "https://artifactize.dev/#start";
139
140impl DoctorReport {
141 fn add(&mut self, name: &'static str, status: CheckStatus, message: &str, details: Details) {
142 self.ok &= status.ready();
143 self.checks.push(Check {
144 name,
145 status,
146 message: message.into(),
147 details,
148 });
149 }
150}
151
152pub async fn doctor(state: Option<&Path>, repo: Option<&Path>) -> Result<DoctorReport, String> {
155 let state = store::state_dir(state)?;
156 let mut report = DoctorReport {
157 ok: true,
158 state_dir: state.clone(),
159 checks: Vec::new(),
160 };
161 let config = repo.map(read_workspace_config).transpose();
162 if repo.is_some() {
163 match &config {
164 Ok(Some(config)) => report.add(
165 "config",
166 CheckStatus::Pass,
167 "Folder configuration is valid.",
168 Details::Config {
169 artifacts: config.artifacts.len(),
170 evals: config.evals.len(),
171 },
172 ),
173 Err(error) => report.add(
174 "config",
175 CheckStatus::Fail,
176 &error.to_string(),
177 Details::None,
178 ),
179 _ => unreachable!(),
180 }
181 }
182 let writable = (|| {
183 let state = workspace::canonical_target(&state)?;
184 if let Some(repo) = repo {
185 let repo = workspace::canonical_target(repo)?;
186 let repo = if repo.is_file() {
187 repo.parent().unwrap()
188 } else {
189 &repo
190 };
191 workspace::outside_workspace(repo, &state)?;
192 } else {
193 workspace::outside_artifact_workspaces(&state)?;
194 }
195 crate::platform::paths::probe_writable(&state)
196 })();
197 match writable {
198 Ok(()) => report.add(
199 "state",
200 CheckStatus::Pass,
201 "State directory is writable or can be created.",
202 Details::State { writable: true },
203 ),
204 Err(error) => report.add(
205 "state",
206 CheckStatus::Fail,
207 &error.to_string(),
208 Details::State { writable: false },
209 ),
210 }
211 let current = store::STATE_SCHEMA_VERSION;
213 match store::state_schema(&state) {
214 Ok(None) => report.add(
215 "schema",
216 CheckStatus::Pass,
217 "No state database yet.",
218 Details::Schema { schema: None },
219 ),
220 Ok(Some(0)) => report.add(
221 "schema",
222 CheckStatus::Pass,
223 "The state database is not initialized yet.",
224 Details::Schema { schema: Some(0) },
225 ),
226 Ok(Some(found)) if found == current => report.add(
227 "schema",
228 CheckStatus::Pass,
229 &format!("State database schema {current}."),
230 Details::Schema {
231 schema: Some(current),
232 },
233 ),
234 Ok(Some(found)) => report.add(
235 "schema",
236 CheckStatus::Fail,
237 &store::schema_error(found),
238 Details::UnsupportedSchema {
239 schema: found,
240 supported: current,
241 },
242 ),
243 Err(error) => report.add("schema", CheckStatus::Fail, &error, Details::None),
244 }
245 match crate::limits::Limits::read(&state) {
246 Ok(limits) if limits.backends().is_empty() => report.add(
247 "limits",
248 CheckStatus::Pass,
249 "No backend capacity limits (limits.json).",
250 Details::Limits {
251 backends: Default::default(),
252 },
253 ),
254 Ok(limits) => report.add(
255 "limits",
256 CheckStatus::Pass,
257 &format!(
258 "Backend capacity on this machine: {}.",
259 limits
260 .backends()
261 .iter()
262 .map(|(backend, slots)| format!("{backend} {slots}"))
263 .collect::<Vec<_>>()
264 .join(", ")
265 ),
266 Details::Limits {
267 backends: limits.backends().clone(),
268 },
269 ),
270 Err(error) => report.add("limits", CheckStatus::Fail, &error, Details::None),
271 }
272 let (status, message, details) = sessions(&state);
273 report.add("sessions", status, &message, details);
274 let providers = auth::providers::list(Some(&state), repo);
275 let keys = match &providers {
276 Ok(providers) => providers.keys.clone(),
277 Err(_) => Vec::new(),
278 };
279 for status in keys {
280 let backend = status.provider();
281 let (name, variable, source) = (backend.as_str(), status.variable(), status.source());
282 let present = source != auth::providers::KeySource::Absent;
283 let key = match source {
284 auth::providers::KeySource::Saved => format!(
285 "{variable} is absent; a saved {name} key is present (not validated with the provider)"
286 ),
287 _ => format!(
288 "{variable} is {} (not validated with the provider)",
289 if present { "present" } else { "absent" }
290 ),
291 };
292 match llm::test_endpoint(backend) {
293 Ok(None) => report.add(
294 name,
295 if present {
296 CheckStatus::Pass
297 } else {
298 CheckStatus::Warn
299 },
300 &format!("{key}."),
301 Details::ApiKey { present, test_endpoint: None },
302 ),
303 Ok(Some(endpoint)) => report.add(
305 name,
306 CheckStatus::Warn,
307 &format!(
308 "{key}; {} sends this backend's requests to the local test endpoint {endpoint}.",
309 llm::base_url_variable(backend).unwrap_or_default()
310 ),
311 Details::ApiKey { present, test_endpoint: Some(endpoint) },
312 ),
313 Err(error) => report.add(
314 name,
315 CheckStatus::Fail,
316 &error,
317 Details::ApiKey {
318 present,
319 test_endpoint: None,
320 },
321 ),
322 }
323 }
324 match providers {
325 Ok(auth::providers::Providers {
327 refused: Some(refusal),
328 custom,
329 ..
330 }) => report.add(
331 "providers",
332 CheckStatus::Warn,
333 &refusal,
334 Details::Providers { custom },
335 ),
336 Ok(providers) if providers.custom.is_empty() => report.add(
337 "providers",
338 CheckStatus::Pass,
339 "No custom providers are set up.",
340 Details::Providers {
341 custom: providers.custom,
342 },
343 ),
344 Ok(providers) => report.add(
345 "providers",
346 CheckStatus::Pass,
347 &format!(
348 "Custom providers on this machine: {}.",
349 providers
350 .custom
351 .iter()
352 .map(|(name, custom)| match custom {
353 auth::providers::CustomView::Alias { provider } => {
354 format!("{name} (alias of {provider})")
355 }
356 auth::providers::CustomView::Endpoint { url, .. } => {
357 format!("{name} ({})", url.as_str())
358 }
359 })
360 .collect::<Vec<_>>()
361 .join(", ")
362 ),
363 Details::Providers {
364 custom: providers.custom,
365 },
366 ),
367 Err(error) => report.add("providers", CheckStatus::Fail, &error, Details::None),
368 }
369 let (status, message, details) = codex(&state, repo);
370 report.add("codex", status, &message, details);
371 match crate::platform::program::resolve(
374 std::path::Path::new(llm::claude_agent::command::PROGRAM),
375 &crate::platform::temporary_directory(),
376 ) {
377 Ok(program) => report.add(
378 "claude-agent",
379 CheckStatus::Pass,
380 &format!(
381 "Claude Code is on PATH: {}; it signs in on its own (`claude auth status`).",
382 crate::platform::path_text(&program)
383 ),
384 Details::ClaudeAgent {
385 program: Some(program),
386 },
387 ),
388 Err(_) => report.add(
389 "claude-agent",
390 CheckStatus::Warn,
391 "Claude Code (`claude`) is not on PATH; the claude-agent backend needs it, signed in with `claude auth login`.",
392 Details::ClaudeAgent { program: None },
393 ),
394 }
395 match auth::remote::remote(Some(&state), repo) {
397 Ok(None) => report.add(
398 "remote",
399 CheckStatus::Pass,
400 "No remote review store is configured.",
401 Details::NoRemote { configured: false },
402 ),
403 Ok(Some(remote)) => {
404 let details = Details::Remote {
405 configured: true,
406 url: remote.url().clone(),
407 share: remote.share,
408 token_source: remote.token_source(),
409 };
410 if remote.token_source() == auth::remote::TokenSource::None {
411 report.add(
412 "remote",
413 CheckStatus::Warn,
414 "No remote token; run `artifactize remote login URL` or set ARTIFACTIZE_REMOTE_TOKEN.",
415 details,
416 );
417 } else {
418 report.add(
419 "remote",
420 CheckStatus::Pass,
421 "Remote review store is configured; `remote status` checks reachability.",
422 details,
423 );
424 }
425 }
426 Err(error) => report.add("remote", CheckStatus::Fail, &error, Details::None),
427 }
428 match crate::platform::desktop_app::installed() {
430 Some(path) => report.add(
431 "desktop",
432 CheckStatus::Pass,
433 &format!(
434 "The desktop app is installed: {}.",
435 crate::platform::path_text(&path)
436 ),
437 Details::Desktop { path: Some(path) },
438 ),
439 None => report.add(
440 "desktop",
441 CheckStatus::Warn,
442 &format!("The desktop app is not installed; install it from {DESKTOP_INSTALL_PAGE}."),
443 Details::Desktop { path: None },
444 ),
445 }
446 let (status, message, details) = release_check(release::check(&state).await);
447 report.add("release", status, &message, details);
448 Ok(report)
449}
450
451fn release_check(checked: release::Status) -> (CheckStatus, String, Details) {
454 use release::{Outcome, Unchecked, Update};
455 let release::Status {
456 running,
457 channel,
458 outcome,
459 } = checked;
460 let (status, message, latest, update) = match outcome {
461 Outcome::Unchecked(Unchecked::Store) => (
462 CheckStatus::Pass,
463 format!("The Microsoft Store keeps artifactize {running} up to date."),
464 None,
465 None,
466 ),
467 Outcome::Unchecked(Unchecked::Off) => (
468 CheckStatus::Pass,
469 format!(
470 "{} is set; releases are not looked up.",
471 release::OFF_VARIABLE
472 ),
473 None,
474 None,
475 ),
476 Outcome::Unchecked(Unchecked::Development) => (
477 CheckStatus::Pass,
478 format!("artifactize {running} is a development build; releases are not looked up."),
479 None,
480 None,
481 ),
482 Outcome::Latest(latest) => (
483 CheckStatus::Pass,
484 format!("artifactize {running} is up to date; the latest release is {latest}."),
485 Some(latest),
486 None,
487 ),
488 Outcome::Newer { latest, update } => {
489 let how = match &update {
490 Update::Command { command } => format!("run `{command}`"),
491 Update::Download { url, command: None } => format!("download and install {url}"),
492 Update::Download {
493 url,
494 command: Some(command),
495 } => format!("download {url}, then run `{command}`"),
496 Update::Page { url } => format!("see {url}"),
497 };
498 (
499 CheckStatus::Warn,
500 format!("artifactize {latest} is out (this is {running}); to update, {how}."),
501 Some(latest),
502 Some(update),
503 )
504 }
505 Outcome::Failed(error) => (
506 CheckStatus::Warn,
507 format!("Cannot look up the latest release: {error}"),
508 None,
509 None,
510 ),
511 };
512 (
513 status,
514 message,
515 Details::Release {
516 channel,
517 running,
518 latest,
519 update,
520 },
521 )
522}
523
524fn sessions(state: &Path) -> (CheckStatus, String, Details) {
527 let bounds = match crate::limits::Limits::read(state) {
528 Ok(limits) => limits.agent_sessions(),
529 Err(_) => {
530 return (
531 CheckStatus::Fail,
532 "limits.json is invalid; see limits.".into(),
533 Details::None,
534 );
535 }
536 };
537 let usage = match crate::agent::session::usage(state) {
538 Ok(usage) => usage,
539 Err(error) => return (CheckStatus::Fail, error, Details::None),
540 };
541 let state_id = store::read_state_id(state).ok().flatten();
543 const BYTES_PER_MIB: u64 = 1_048_576;
545 let mib = |bytes: u64| format!("{:.1} MiB", bytes as f64 / BYTES_PER_MIB as f64);
546 let message = format!(
547 "{} Agent session{} take {} of {}; a collection brings them down to {}.{}",
548 usage.sessions,
549 if usage.sessions == 1 { "" } else { "s" },
550 mib(usage.bytes),
551 mib(bounds.max_bytes()),
552 mib(bounds.target_bytes()),
553 if bounds.enabled() {
554 ""
555 } else {
556 " Saving is off (limits.json agentSessions.enabled)."
557 }
558 );
559 let details = Details::Sessions {
560 enabled: bounds.enabled(),
561 sessions: usage.sessions,
562 bytes: usage.bytes,
563 max_bytes: bounds.max_bytes(),
564 target_bytes: bounds.target_bytes(),
565 directory: crate::agent::session::directory(state),
566 state_id,
567 };
568 (CheckStatus::Pass, message, details)
569}
570
571fn codex(state: &Path, repo: Option<&Path>) -> (CheckStatus, String, Details) {
574 let endpoints = llm::test_endpoint(Provider::Codex).and_then(|base| {
575 Ok((
576 base,
577 llm::variable_endpoint(auth::codex::AUTH_URL_VARIABLE)?,
578 ))
579 });
580 let ((base, sign_in), status) = match (endpoints, auth::codex::status(Some(state), repo)) {
581 (Err(error), _) | (_, Err(error)) => return (CheckStatus::Fail, error, Details::None),
582 (Ok(endpoints), Ok(status)) => (endpoints, status),
583 };
584 use auth::codex::{FileExpiry, Status, StoredExpiry};
585 let (mut level, mut message) = match &status {
586 Status::Refused { reason } => (CheckStatus::Warn, reason.clone()),
587 Status::Absent => (
588 CheckStatus::Warn,
589 "No Codex sign-in; run `artifactize login codex` or set ARTIFACTIZE_CODEX_AUTH_FILE."
590 .to_owned(),
591 ),
592 Status::File {
593 path,
594 expiry: FileExpiry::Usable { .. },
595 } => (
596 CheckStatus::Pass,
597 format!(
598 "ARTIFACTIZE_CODEX_AUTH_FILE is read, never refreshed: {}.",
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 access token in {} has expired; sign in with Codex again.",
609 crate::platform::path_text(path)
610 ),
611 ),
612 Status::Stored {
613 expiry: StoredExpiry::Usable { .. },
614 } => (
615 CheckStatus::Pass,
616 "Codex sign-in is present; no provider validation or refresh was attempted.".to_owned(),
617 ),
618 Status::Stored {
619 expiry: StoredExpiry::Expired { .. },
620 } => (
621 CheckStatus::Pass,
622 "Codex sign-in is present; its access token has expired and is refreshed on next use."
623 .to_owned(),
624 ),
625 };
626 for (variable, endpoint) in [
627 (
628 llm::base_url_variable(Provider::Codex).expect("Codex has a test endpoint"),
629 &base,
630 ),
631 (auth::codex::AUTH_URL_VARIABLE, &sign_in),
632 ] {
633 if let Some(endpoint) = endpoint {
634 level = CheckStatus::Warn;
635 message.push_str(&format!(
636 " {variable} points at the local test endpoint {endpoint}."
637 ));
638 }
639 }
640 let details = Details::Codex {
641 status,
642 test_endpoint: base,
643 test_auth_endpoint: sign_in,
644 };
645 (level, message, details)
646}