feat(cli): add codex doctor diagnostics (#22336)

## Why

Users and support need a single command that captures the local Codex
runtime, configuration, auth, terminal, network, and state shape without
asking the user to know which diagnostic depth to choose first. `codex
doctor` now runs the useful checks by default and makes the detailed
human output the default because the command is usually run when someone
already needs context.

The command also targets concrete support failure modes we have seen
while iterating on the design:

- update-target mismatches like #21956, where the installed package
manager target can differ from the running executable
- terminal and multiplexer issues that depend on `TERM`, tmux/zellij
state, color handling, and TTY metadata
- provider-specific HTTP/WebSocket connectivity, including ChatGPT
WebSocket handshakes and API-key/provider endpoint reachability
- local state/log SQLite integrity problems and large rollout
directories
- feedback reports that need an attached, redacted diagnostic snapshot
without asking the user to run a second command

## What Changed

- Adds `codex doctor` as a grouped CLI diagnostic report with default
detailed output and `--summary` for the compact view.
- Adds stable report sections for Environment, Configuration, Updates,
Connectivity, and Background Server, plus a top Notes block that
promotes anomalies such as available updates, large rollout directories,
optional MCP issues, and mixed auth signals.
- Adds runtime provenance, install consistency, bundled/system search
readiness, terminal/multiplexer metadata, `config.toml` parse status,
auth mode details, sandbox details, feature flag summaries, update
cache/latest-version state, app-server daemon state, SQLite integrity
checks, rollout statistics, and provider-aware network diagnostics.
- Adds ChatGPT WebSocket diagnostics that report the negotiated HTTP
upgrade as `HTTP 101 Switching Protocols` and include timeout, DNS,
auth, and provider context in detailed output.
- Makes reachability provider-aware: API-key OpenAI setups check the API
endpoint, ChatGPT auth checks the ChatGPT path, and custom/AWS/local
providers check configured HTTP endpoints when available.
- Adds structured, redacted JSON output where `checks` is keyed by check
id and `details` is a key/value object for support tooling.
- Integrates doctor with feedback uploads by attaching a best-effort
`codex-doctor-report.json` report and adding derived Sentry tags for
overall status and failing/warning checks.
- Updates the TUI feedback consent copy so users can see that the doctor
report is included when logs/diagnostics are uploaded.
- Updates the CLI bug issue template to ask reporters for `codex doctor
--json` and render pasted reports as JSON.

## Example Output

The examples below are sanitized from local smoke runs with `--no-color`
so the structure is reviewable in plain text.

### `codex doctor`

```text
Codex Doctor v0.0.0 · macos-aarch64

Notes
   ↑ updates      0.130.0 available (current 0.0.0, dismissed 0.128.0)
   ⚠ rollouts     1,526 active files · 2.53 GB on disk
   ⚠ mcp          MCP configuration has optional issues
   ⚠ auth         mixed auth signals: ChatGPT login plus API key env var; HTTP reachability uses API-key mode
─────────────────────────────────────────────────────────────

Environment
  ✓ runtime      local debug build
      version                  0.0.0
      install method           other
      commit                   unknown
      executable               ~/code/codex.fcoury-doct…x-rs/target/debug/codex
  ✓ install      consistent
      context                  other
      managed by               npm: no · bun: no · package root —
      PATH entries (2)         ~/.local/share/mise/installs/node/24/bin/codex
                               ~/.local/share/mise/shims/codex
  ✓ search       ripgrep 15.1.0 (system, `rg`)
  ✓ terminal     Ghostty 1.3.2-main-+b0f827665 · tmux 3.6a · TERM=xterm-256color
      terminal                 Ghostty
      TERM_PROGRAM             ghostty
      terminal version         1.3.2-main-+b0f827665
      TERM                     xterm-256color
      multiplexer              tmux 3.6a
      tmux extended-keys       on
      tmux allow-passthrough   on
      tmux set-clipboard       on
  ✓ state        databases healthy
      CODEX_HOME               ~/.codex (dir)
      state DB                 ~/.codex/state_5.sqlite (file) · integrity ok
      log DB                   ~/.codex/logs_2.sqlite (file) · integrity ok
      active rollouts          1,526 files · 2.53 GB (avg 1.70 MB)
      archived rollouts        8 files · 3.84 MB (avg 491.11 KB)

Configuration
  ✓ config       loaded
      model                    gpt-5.5 · openai
      cwd                      ~/code/codex.fcoury-doctor/codex-rs
      config.toml              ~/.codex/config.toml
      config.toml parse        ok
      MCP servers              1
      feature flags            36 enabled · 7 overridden (full list with --all)
      overrides                code_mode, code_mode_only, memories, chronicle, goals, remote_control, prevent_idle_sleep
  ✓ auth         auth is configured
      auth storage mode        File
      auth file                ~/.codex/auth.json
      auth env vars present    OPENAI_API_KEY
      stored auth mode         chatgpt
      stored API key           false
      stored ChatGPT tokens    true
      stored agent identity    false
  ⚠ mcp          MCP configuration has optional issues — Set the missing MCP env vars or disable the affected server.
      configured servers       1
      disabled servers         0
      streamable_http servers  1
      optional reachability    openaiDeveloperDocs: https://developers.openai.com/mcp (HEAD connect failed; GET connect failed)
  ✓ sandbox      restricted fs + restricted network · approval OnRequest
      approval policy          OnRequest
      filesystem sandbox       restricted
      network sandbox          restricted

Connectivity
  ✓ network      network-related environment looks readable
  ✓ websocket    connected (HTTP 101 Switching Protocols) · 15s timeout
      model provider           openai
      provider name            OpenAI
      wire API                 responses
      supports websockets      true
      connect timeout          15000 ms
      auth mode                chatgpt
      endpoint                 wss://chatgpt.com/backend-api/<redacted>
      DNS                      2 IPv4, 2 IPv6, first IPv6
      handshake result         HTTP 101 Switching Protocols
  ✗ reachability one or more required provider endpoints are unreachable over HTTP — Check proxy, VPN, firewall, DNS, and custom CA configuration.
      reachability mode        API key auth
      openai API               https://api.openai.com/v1 connect failed (required)

Background Server
  ○ app-server   not running (ephemeral mode)

─────────────────────────────────────────────────────────────
11 ok · 1 idle · 4 notes · 1 warn · 1 fail failed

--summary compact output           --all expand truncated lists
--json redacted report
```

### `codex doctor --summary`

```text
Codex Doctor v0.0.0 · macos-aarch64

Notes
   ↑ updates      0.130.0 available (current 0.0.0, dismissed 0.128.0)
   ⚠ rollouts     1,526 active files · 2.53 GB on disk
   ⚠ mcp          MCP configuration has optional issues
   ⚠ auth         mixed auth signals: ChatGPT login plus API key env var; HTTP reachability uses API-key mode
─────────────────────────────────────────────────────────────

Environment
  ✓ runtime      local debug build
  ✓ install      consistent
  ✓ search       ripgrep 15.1.0 (system, `rg`)
  ✓ terminal     Ghostty 1.3.2-main-+b0f827665 · tmux 3.6a · TERM=xterm-256color
  ✓ state        databases healthy

Configuration
  ✓ config       loaded
  ✓ auth         auth is configured
  ⚠ mcp          MCP configuration has optional issues — Set the missing MCP env vars or disable the affected server.
  ✓ sandbox      restricted fs + restricted network · approval OnRequest

Updates
  ✓ updates      update configuration is locally consistent

Connectivity
  ✓ network      network-related environment looks readable
  ✓ websocket    connected (HTTP 101 Switching Protocols) · 15s timeout
  ✗ reachability one or more required provider endpoints are unreachable over HTTP — Check proxy, VPN, firewall, DNS, and custom CA configuration.

Background Server
  ○ app-server   not running (ephemeral mode)

─────────────────────────────────────────────────────────────
11 ok · 1 idle · 4 notes · 1 warn · 1 fail failed

Run codex doctor without --summary for detailed diagnostics.
--all expand truncated lists       --json redacted report
```

### `codex doctor --json` shape

```json
{
  "schema_version": 1,
  "overall_status": "fail",
  "checks": {
    "runtime.provenance": {
      "id": "runtime.provenance",
      "category": "Environment",
      "status": "ok",
      "summary": "local debug build",
      "details": {
        "version": "0.0.0",
        "install method": "other",
        "commit": "unknown"
      }
    },
    "sandbox.helpers": {
      "id": "sandbox.helpers",
      "category": "Configuration",
      "status": "ok",
      "summary": "restricted fs + restricted network · approval OnRequest",
      "details": {
        "approval policy": "OnRequest",
        "filesystem sandbox": "restricted",
        "network sandbox": "restricted"
      }
    }
  }
}
```

### `/feedback` new sentry attachment

<img width="938" height="798" alt="CleanShot 2026-05-13 at 15 36 14"
src="https://github.com/user-attachments/assets/715e62e0-d7b4-4fea-a35a-fd5d5d33c4c0"
/>

### New section in CLI issue template

<img width="1164" height="435" alt="CleanShot 2026-05-13 at 15 47 24"
src="https://github.com/user-attachments/assets/9081dc25-a28c-4afa-8ba1-e299c2b4031d"
/>

## How to Test

1. Run `cargo run --bin codex -- doctor --no-color`.
2. Confirm the detailed report is the default and includes promoted
Notes, grouped sections, terminal details, state DB integrity, rollout
stats, provider reachability, WebSocket diagnostics, and app-server
status.
3. Run `cargo run --bin codex -- doctor --summary --no-color`.
4. Confirm the compact view keeps the same sections and summary counts
but omits detailed key/value rows.
5. Run `cargo run --bin codex -- doctor --json`.
6. Confirm the output is redacted JSON, `checks` is an object keyed by
check id, and each check's `details` is a key/value object.
7. Preview the CLI bug issue template and confirm the `Codex doctor
report` field appears after the terminal field, asks for `codex doctor
--json`, and renders pasted output as JSON.
8. Start a feedback flow that includes logs.
9. Confirm the upload consent copy lists `codex-doctor-report.json`
alongside the log attachments.

Targeted tests:

- `cargo test -p codex-cli doctor`
- `cargo test -p codex-app-server
doctor_report_tags_summarize_status_counts`
- `cargo test -p codex-feedback`
- `cargo test -p codex-tui feedback_view`
- `just argument-comment-lint`
- `git diff --check`
This commit is contained in:
Felipe Coury
2026-05-13 18:23:19 -03:00
committed by GitHub
Unverified
parent 5d7e6a2503
commit 9798eb377a
29 changed files with 7339 additions and 22 deletions
File diff suppressed because it is too large Load Diff
+150
View File
@@ -0,0 +1,150 @@
//! Reports app-server daemon state without starting or stopping the daemon.
//!
//! The background-server check is deliberately passive. It reads the daemon
//! state directory, PID files, settings file, and control socket path, then
//! attempts only a local socket connection when a socket already exists. That
//! keeps doctor safe to run while the user is debugging startup or update-loop
//! issues.
use std::path::Path;
use codex_core::config::Config;
use super::CheckStatus;
use super::DoctorCheck;
const STATE_DIR_NAME: &str = "app-server-daemon";
const SETTINGS_FILE_NAME: &str = "settings.json";
const PID_FILE_NAME: &str = "app-server.pid";
const UPDATE_PID_FILE_NAME: &str = "app-server-updater.pid";
/// Builds the app-server status row from existing daemon state.
///
/// Missing files are expected for the ephemeral/not-running case and should not
/// be treated as failures. A stale socket is a warning because it can explain
/// client connection problems without proving the daemon itself is broken.
pub(super) fn background_server_check(config: &Config) -> DoctorCheck {
let mut details = Vec::new();
let state_dir = config.codex_home.join(STATE_DIR_NAME);
details.push(format!("daemon state dir: {}", state_dir.display()));
push_file_detail(
&mut details,
"settings",
&state_dir.join(SETTINGS_FILE_NAME),
);
push_file_detail(&mut details, "pid file", &state_dir.join(PID_FILE_NAME));
push_file_detail(
&mut details,
"update-loop pid file",
&state_dir.join(UPDATE_PID_FILE_NAME),
);
let socket_path = match codex_app_server::app_server_control_socket_path(&config.codex_home) {
Ok(socket_path) => socket_path,
Err(err) => {
return DoctorCheck::new(
"app_server.status",
"app-server",
CheckStatus::Warning,
"background server socket path could not be resolved",
)
.details(details)
.detail(err.to_string());
}
};
details.push(format!("control socket: {}", socket_path.display()));
let status = socket_status(socket_path.as_path());
details.push(format!("status: {}", status.detail_label()));
details.push(format!("mode: {}", server_mode(&state_dir)));
let mut check = DoctorCheck::new(
"app_server.status",
"app-server",
status.check_status(),
status.summary(),
)
.details(details);
if status.check_status() == CheckStatus::Warning {
check = check.remediation("Run codex app-server daemon version for more details.");
}
check
}
fn push_file_detail(details: &mut Vec<String>, label: &str, path: &Path) {
match std::fs::metadata(path) {
Ok(metadata) if metadata.is_file() => {
details.push(format!("{label}: {} (file)", path.display()));
}
Ok(_) => {
details.push(format!("{label}: {} (not a file)", path.display()));
}
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
details.push(format!("{label}: {} (missing)", path.display()));
}
Err(err) => details.push(format!("{label}: {} ({err})", path.display())),
}
}
fn server_mode(state_dir: &Path) -> &'static str {
if state_dir.join(SETTINGS_FILE_NAME).is_file() {
"persistent"
} else {
"ephemeral"
}
}
#[derive(Clone, Copy)]
enum SocketStatus {
NotRunning,
Running,
#[cfg(unix)]
StaleOrUnreachable,
}
impl SocketStatus {
fn check_status(self) -> CheckStatus {
match self {
Self::NotRunning | Self::Running => CheckStatus::Ok,
#[cfg(unix)]
Self::StaleOrUnreachable => CheckStatus::Warning,
}
}
fn summary(self) -> &'static str {
match self {
Self::NotRunning => "background server is not running",
Self::Running => "background server is running",
#[cfg(unix)]
Self::StaleOrUnreachable => "background server socket is stale or unreachable",
}
}
fn detail_label(self) -> &'static str {
match self {
Self::NotRunning => "not running",
Self::Running => "running",
#[cfg(unix)]
Self::StaleOrUnreachable => "stale or unreachable",
}
}
}
fn socket_status(socket_path: &Path) -> SocketStatus {
if !socket_path.exists() {
return SocketStatus::NotRunning;
}
#[cfg(unix)]
{
match std::os::unix::net::UnixStream::connect(socket_path) {
Ok(_) => SocketStatus::Running,
Err(_) => SocketStatus::StaleOrUnreachable,
}
}
#[cfg(not(unix))]
{
SocketStatus::Running
}
}
File diff suppressed because it is too large Load Diff
+648
View File
@@ -0,0 +1,648 @@
//! Converts raw doctor detail strings into human-oriented rows.
//!
//! Checks intentionally store details as simple redacted `label: value` strings
//! so JSON serialization and human rendering share the same source data. This
//! module owns the presentation-only transformations: collapsing noisy booleans,
//! truncating long paths for terminal output, grouping repeated values, and
//! keeping the `--all` expansion behavior out of check construction.
use std::collections::BTreeSet;
use std::env;
use super::DoctorCheck;
use super::HumanOutputOptions;
use super::redact_detail;
const LIST_LIMIT: usize = 7;
const PATH_LIMIT: usize = 48;
#[derive(Clone, Debug, Eq, PartialEq)]
pub(super) enum HumanDetail {
Row {
label: String,
value: String,
expected: Option<String>,
},
Continuation(String),
Bullet(String),
Remedy(String),
}
#[derive(Clone, Debug, Eq, PartialEq)]
struct ParsedDetail {
label: String,
value: String,
}
pub(super) fn detail_lines(check: &DoctorCheck, options: HumanOutputOptions) -> Vec<HumanDetail> {
let parsed = parsed_details(check);
let details = match check.category.as_str() {
"runtime" => runtime_details(&parsed),
"install" => install_details(&parsed, options),
"config" => config_details(&parsed, options),
"state" => state_details(&parsed),
_ => generic_details(&parsed),
};
let mut details = details
.into_iter()
.map(|detail| attach_issue_metadata(detail, check))
.map(|detail| humanize_detail(detail, options))
.collect::<Vec<_>>();
details.extend(issue_remedies(check));
details
}
pub(super) fn detail_value(check: &DoctorCheck, label: &str) -> Option<String> {
parsed_details(check)
.into_iter()
.find(|detail| detail.label == label)
.map(|detail| detail.value)
}
pub(super) fn rollout_summary(value: &str) -> Option<String> {
let (files, rest) = value.split_once(" files, ")?;
let (total_bytes, rest) = rest.split_once(" total bytes, ")?;
let (average_bytes, _) = rest.split_once(" average bytes")?;
let files = files.trim().parse::<u64>().ok()?;
let total_bytes = total_bytes.trim().parse::<u64>().ok()?;
let average_bytes = average_bytes.trim().parse::<u64>().ok()?;
Some(format!(
"{} files · {} (avg {})",
format_count(files),
format_bytes(total_bytes),
format_bytes(average_bytes)
))
}
pub(super) fn rollout_files_and_bytes(value: &str) -> Option<(u64, u64)> {
let (files, rest) = value.split_once(" files, ")?;
let (total_bytes, _) = rest.split_once(" total bytes, ")?;
Some((
files.trim().parse::<u64>().ok()?,
total_bytes.trim().parse::<u64>().ok()?,
))
}
pub(super) fn format_bytes(bytes: u64) -> String {
const KIB: f64 = 1024.0;
const MIB: f64 = KIB * 1024.0;
const GIB: f64 = MIB * 1024.0;
let bytes = bytes as f64;
if bytes >= GIB {
format!("{:.2} GB", bytes / GIB)
} else if bytes >= MIB {
format!("{:.2} MB", bytes / MIB)
} else if bytes >= KIB {
format!("{:.2} KB", bytes / KIB)
} else {
format!("{} B", bytes as u64)
}
}
pub(super) fn format_count(count: u64) -> String {
let mut digits = count.to_string();
let mut out = String::new();
while digits.len() > 3 {
let tail = digits.split_off(digits.len() - 3);
if out.is_empty() {
out = tail;
} else {
out = format!("{tail},{out}");
}
}
if out.is_empty() {
digits
} else {
format!("{digits},{out}")
}
}
fn parsed_details(check: &DoctorCheck) -> Vec<ParsedDetail> {
check
.details
.iter()
.map(|detail| redact_detail(detail))
.map(|detail| {
detail
.split_once(": ")
.map(|(label, value)| ParsedDetail {
label: label.to_string(),
value: value.to_string(),
})
.unwrap_or_else(|| ParsedDetail {
label: String::new(),
value: detail,
})
})
.collect()
}
fn runtime_details(parsed: &[ParsedDetail]) -> Vec<HumanDetail> {
let mut out = Vec::new();
push_row_if_present(&mut out, parsed, "version", "version");
push_row_if_present(&mut out, parsed, "install method", "install method");
push_row_if_present(&mut out, parsed, "commit", "commit");
push_row_if_present(&mut out, parsed, "current executable", "executable");
push_remaining(
&mut out,
parsed,
&[
"version",
"platform",
"install method",
"commit",
"current executable",
],
&[],
);
out
}
fn install_details(parsed: &[ParsedDetail], options: HumanOutputOptions) -> Vec<HumanDetail> {
let mut out = Vec::new();
push_row_if_present(&mut out, parsed, "install context", "context");
if parsed.iter().any(|detail| {
detail.value == "ignored inherited package-manager launch env for cargo-built binary"
}) {
out.push(HumanDetail::Bullet(
"ignored inherited package-manager launch env for cargo-built binary".to_string(),
));
}
let managed_by_npm = value(parsed, "managed by npm").unwrap_or("false");
let managed_by_bun = value(parsed, "managed by bun").unwrap_or("false");
let package_root = value(parsed, "managed package root").unwrap_or("not set");
out.push(HumanDetail::Row {
label: "managed by".to_string(),
value: format!(
"npm: {} · bun: {} · package root {}",
yes_no(managed_by_npm),
yes_no(managed_by_bun),
if is_falsy(package_root) {
"".to_string()
} else {
package_root.to_string()
}
),
expected: None,
});
let path_entries = numbered_values(parsed, "PATH codex #");
if !path_entries.is_empty() {
let total = path_entries.len();
let shown = if options.show_all {
total
} else {
total.min(3)
};
out.push(HumanDetail::Row {
label: format!("PATH entries ({total})"),
value: path_entries[0].clone(),
expected: None,
});
out.extend(
path_entries
.iter()
.skip(1)
.take(shown.saturating_sub(1))
.cloned()
.map(HumanDetail::Continuation),
);
if shown < total {
out.push(HumanDetail::Continuation(
"… (full list with --all)".to_string(),
));
}
}
push_remaining(
&mut out,
parsed,
&[
"current executable",
"install context",
"managed by npm",
"managed by bun",
"managed package root",
"PATH codex entries",
],
&["PATH codex #"],
);
out
}
fn config_details(parsed: &[ParsedDetail], options: HumanOutputOptions) -> Vec<HumanDetail> {
let mut out = Vec::new();
if let Some(model) = value(parsed, "model") {
let value = value(parsed, "model provider").map_or_else(
|| model.to_string(),
|provider| format!("{model} · {provider}"),
);
out.push(HumanDetail::Row {
label: "model".to_string(),
value,
expected: None,
});
}
push_row_if_present(&mut out, parsed, "cwd", "cwd");
push_row_if_present(&mut out, parsed, "config.toml", "config.toml");
push_row_if_present(&mut out, parsed, "config.toml parse", "config.toml parse");
push_row_if_present(&mut out, parsed, "config.toml read", "config.toml read");
push_row_if_present(&mut out, parsed, "mcp servers", "MCP servers");
push_feature_flags(&mut out, parsed, options);
for detail in parsed
.iter()
.filter(|detail| detail.label == "legacy feature flag")
{
out.push(HumanDetail::Row {
label: "legacy alias".to_string(),
value: detail.value.clone(),
expected: None,
});
}
push_remaining(
&mut out,
parsed,
&[
"CODEX_HOME",
"cwd",
"model",
"model provider",
"log dir",
"sqlite home",
"mcp servers",
"feature flags enabled",
"enabled feature flags",
"feature flag overrides",
"legacy feature flag",
"config.toml",
"config.toml parse",
"config.toml read",
],
&[],
);
out
}
fn state_details(parsed: &[ParsedDetail]) -> Vec<HumanDetail> {
let mut out = Vec::new();
push_row_if_present(&mut out, parsed, "CODEX_HOME", "CODEX_HOME");
push_row_if_present(&mut out, parsed, "log dir", "log dir");
push_row_if_present(&mut out, parsed, "sqlite home", "sqlite home");
push_database_row(&mut out, parsed, "state DB");
push_database_row(&mut out, parsed, "log DB");
for (source, label) in [
("active rollout files", "active rollouts"),
("archived rollout files", "archived rollouts"),
] {
if let Some(value) = value(parsed, source) {
out.push(HumanDetail::Row {
label: label.to_string(),
value: rollout_summary(value).unwrap_or_else(|| value.to_string()),
expected: None,
});
}
}
push_remaining(
&mut out,
parsed,
&[
"CODEX_HOME",
"log dir",
"sqlite home",
"state DB",
"log DB",
"state DB integrity",
"log DB integrity",
"active rollout files",
"archived rollout files",
],
&[],
);
out
}
fn generic_details(parsed: &[ParsedDetail]) -> Vec<HumanDetail> {
parsed
.iter()
.map(|detail| {
if detail.label.is_empty() {
HumanDetail::Bullet(detail.value.clone())
} else {
HumanDetail::Row {
label: display_label(&detail.label),
value: detail.value.clone(),
expected: None,
}
}
})
.collect()
}
fn push_feature_flags(
out: &mut Vec<HumanDetail>,
parsed: &[ParsedDetail],
options: HumanOutputOptions,
) {
let enabled_count = value(parsed, "feature flags enabled")
.and_then(|value| value.parse::<usize>().ok())
.unwrap_or_default();
let overrides = list_items(value(parsed, "feature flag overrides").unwrap_or("none"));
let override_count = overrides.len();
let hint = if !options.show_all && enabled_count > 0 {
" (full list with --all)"
} else {
""
};
out.push(HumanDetail::Row {
label: "feature flags".to_string(),
value: format!("{enabled_count} enabled · {override_count} overridden{hint}"),
expected: None,
});
if !overrides.is_empty() {
push_list_row(out, "overrides", &override_names(&overrides), options);
}
if options.show_all {
let enabled = list_items(value(parsed, "enabled feature flags").unwrap_or("none"));
if !enabled.is_empty() {
push_list_row(out, "enabled flags", &enabled, options);
}
}
}
fn push_list_row(
out: &mut Vec<HumanDetail>,
label: &str,
items: &[String],
options: HumanOutputOptions,
) {
let limit = if options.show_all {
items.len()
} else {
items.len().min(LIST_LIMIT)
};
let mut value = items
.iter()
.take(limit)
.cloned()
.collect::<Vec<_>>()
.join(", ");
if limit < items.len() {
value.push_str(", … (full list with --all)");
}
out.push(HumanDetail::Row {
label: label.to_string(),
value,
expected: None,
});
}
fn push_database_row(out: &mut Vec<HumanDetail>, parsed: &[ParsedDetail], label: &str) {
let Some(path) = value(parsed, label) else {
return;
};
let integrity = value(parsed, &format!("{label} integrity"));
let value = integrity.map_or_else(
|| path.to_string(),
|integrity| format!("{path} · integrity {integrity}"),
);
out.push(HumanDetail::Row {
label: label.to_string(),
value,
expected: None,
});
}
fn push_row_if_present(
out: &mut Vec<HumanDetail>,
parsed: &[ParsedDetail],
source_label: &str,
display_label: &str,
) {
if let Some(value) = value(parsed, source_label) {
out.push(HumanDetail::Row {
label: display_label.to_string(),
value: value.to_string(),
expected: None,
});
}
}
fn push_remaining(
out: &mut Vec<HumanDetail>,
parsed: &[ParsedDetail],
consumed_labels: &[&str],
consumed_prefixes: &[&str],
) {
for detail in parsed {
if detail.value == "ignored inherited package-manager launch env for cargo-built binary" {
continue;
}
if consumed_labels.contains(&detail.label.as_str())
|| consumed_prefixes
.iter()
.any(|prefix| detail.label.starts_with(prefix))
{
continue;
}
if detail.label.is_empty() {
out.push(HumanDetail::Bullet(detail.value.clone()));
} else {
out.push(HumanDetail::Row {
label: display_label(&detail.label),
value: detail.value.clone(),
expected: None,
});
}
}
}
fn humanize_detail(detail: HumanDetail, options: HumanOutputOptions) -> HumanDetail {
match detail {
HumanDetail::Row {
label,
value,
expected,
} => HumanDetail::Row {
label,
value: humanize_value(&value, options),
expected,
},
HumanDetail::Continuation(value) => {
HumanDetail::Continuation(humanize_value(&value, options))
}
HumanDetail::Bullet(value) => HumanDetail::Bullet(humanize_value(&value, options)),
HumanDetail::Remedy(value) => HumanDetail::Remedy(value),
}
}
fn attach_issue_metadata(detail: HumanDetail, check: &DoctorCheck) -> HumanDetail {
let HumanDetail::Row {
label,
value,
expected,
} = detail
else {
return detail;
};
let expected = expected.or_else(|| issue_expected_for_label(check, &label));
HumanDetail::Row {
label,
value,
expected,
}
}
fn issue_expected_for_label(check: &DoctorCheck, label: &str) -> Option<String> {
check
.issues
.iter()
.find(|issue| {
issue
.fields
.iter()
.any(|field| display_label(field) == label || field == label)
})
.and_then(|issue| issue.expected.clone())
}
fn issue_remedies(check: &DoctorCheck) -> Vec<HumanDetail> {
let mut seen = BTreeSet::new();
check
.issues
.iter()
.filter_map(|issue| issue.remedy.as_ref())
.filter(|remedy| seen.insert((*remedy).clone()))
.cloned()
.map(HumanDetail::Remedy)
.collect()
}
fn humanize_value(value: &str, _options: HumanOutputOptions) -> String {
if looks_like_path(value) {
return shorten_path_prefix(value);
}
if let Some(timestamp) = humanize_timestamp(value) {
return timestamp;
}
value.to_string()
}
fn humanize_timestamp(value: &str) -> Option<String> {
if value.len() < 17 || !value.ends_with('Z') {
return None;
}
let (date, time) = value.split_once('T')?;
let hour_minute = time.get(..5)?;
Some(format!("{date} {hour_minute} UTC"))
}
fn shorten_path_prefix(value: &str) -> String {
let (path, suffix) = value.split_once(" (").map_or_else(
|| (value, String::new()),
|(path, suffix)| (path, format!(" ({suffix}")),
);
let home_shortened = home_shortened_path(path);
let shortened = middle_truncate(&home_shortened, PATH_LIMIT);
format!("{shortened}{suffix}")
}
fn home_shortened_path(path: &str) -> String {
let Some(home) = env::var_os("HOME").and_then(|home| home.into_string().ok()) else {
return path.to_string();
};
if path == home {
"~".to_string()
} else {
path.strip_prefix(&format!("{home}/"))
.map_or_else(|| path.to_string(), |tail| format!("~/{tail}"))
}
}
fn middle_truncate(value: &str, max_chars: usize) -> String {
let char_count = value.chars().count();
if char_count <= max_chars {
return value.to_string();
}
let head_len = max_chars / 2;
let tail_len = max_chars.saturating_sub(head_len + 1);
let head = value.chars().take(head_len).collect::<String>();
let tail = value
.chars()
.rev()
.take(tail_len)
.collect::<String>()
.chars()
.rev()
.collect::<String>();
format!("{head}{tail}")
}
fn looks_like_path(value: &str) -> bool {
value.starts_with('/')
|| value.starts_with("~/")
|| value.starts_with("./")
|| value.starts_with("../")
}
fn numbered_values(parsed: &[ParsedDetail], prefix: &str) -> Vec<String> {
parsed
.iter()
.filter(|detail| detail.label.starts_with(prefix))
.map(|detail| detail.value.clone())
.collect()
}
fn value<'a>(parsed: &'a [ParsedDetail], label: &str) -> Option<&'a str> {
parsed
.iter()
.find(|detail| detail.label == label)
.map(|detail| detail.value.as_str())
}
fn display_label(label: &str) -> String {
match label {
"codex-linux-sandbox helper" => "linux helper",
"optional reachability failed" => "optional reachability",
"check for update on startup" => "startup update check",
other => other,
}
.to_string()
}
fn list_items(value: &str) -> Vec<String> {
if is_falsy(value) {
return Vec::new();
}
value
.split(',')
.map(str::trim)
.filter(|item| !item.is_empty())
.map(str::to_string)
.collect()
}
fn override_names(items: &[String]) -> Vec<String> {
items
.iter()
.map(|item| item.split_once('=').map_or(item.as_str(), |(name, _)| name))
.map(str::to_string)
.collect()
}
fn yes_no(value: &str) -> &'static str {
if value == "true" { "yes" } else { "no" }
}
pub(super) fn is_falsy(value: &str) -> bool {
matches!(
value.trim().to_ascii_lowercase().as_str(),
"" | "false" | "none" | "not set" | "unknown" | "missing" | "absent" | "no" | "" | "-"
)
}
+139
View File
@@ -0,0 +1,139 @@
use std::io;
use std::io::IsTerminal;
use std::io::Write;
use std::sync::Mutex;
use std::time::Duration;
use super::CheckStatus;
/// Receives check lifecycle events while doctor builds the final report.
///
/// Progress implementations must not write to stdout. The final report owns
/// stdout so JSON and redirected human reports stay clean.
pub(super) trait DoctorProgress: Send + Sync {
fn begin(&self, label: &'static str);
fn heartbeat(&self, label: &'static str, elapsed: Duration);
fn finish(&self, label: &'static str, status: CheckStatus);
fn settle(&self);
}
/// Selects the progress implementation for the current output mode.
///
/// JSON output is always quiet so stdout remains valid JSON. Human output uses a
/// transient stderr line only for interactive terminals, then clears it before
/// the final report is printed.
pub(super) fn doctor_progress(json: bool) -> std::sync::Arc<dyn DoctorProgress> {
if should_show_progress(
json,
std::env::var("TERM").ok().as_deref(),
io::stderr().is_terminal(),
) {
std::sync::Arc::new(StderrProgress::default())
} else {
std::sync::Arc::new(QuietProgress)
}
}
fn should_show_progress(json: bool, term: Option<&str>, stderr_is_tty: bool) -> bool {
!json && stderr_is_tty && term != Some("dumb")
}
struct QuietProgress;
impl DoctorProgress for QuietProgress {
fn begin(&self, _label: &'static str) {}
fn heartbeat(&self, _label: &'static str, _elapsed: Duration) {}
fn finish(&self, _label: &'static str, _status: CheckStatus) {}
fn settle(&self) {}
}
#[derive(Default)]
struct StderrProgress {
state: Mutex<StderrProgressState>,
}
#[derive(Default)]
struct StderrProgressState {
wrote_line: bool,
}
impl StderrProgress {
fn render(&self, message: String) {
let Ok(mut state) = self.state.lock() else {
return;
};
let mut stderr = io::stderr().lock();
let _ = write!(stderr, "\r\x1b[2K{message}");
let _ = stderr.flush();
state.wrote_line = true;
}
}
impl DoctorProgress for StderrProgress {
fn begin(&self, label: &'static str) {
self.render(format!("Checking {label}..."));
}
fn heartbeat(&self, label: &'static str, elapsed: Duration) {
self.render(format!("Still checking {label}... {}s", elapsed.as_secs()));
}
fn finish(&self, _label: &'static str, _status: CheckStatus) {}
fn settle(&self) {
let Ok(mut state) = self.state.lock() else {
return;
};
if !state.wrote_line {
return;
}
let mut stderr = io::stderr().lock();
let _ = write!(stderr, "\r\x1b[2K");
let _ = stderr.flush();
state.wrote_line = false;
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn progress_is_quiet_for_json() {
assert!(!should_show_progress(
/*json*/ true,
Some("xterm-256color"),
/*stderr_is_tty*/ true,
));
}
#[test]
fn progress_is_quiet_for_non_tty() {
assert!(!should_show_progress(
/*json*/ false,
Some("xterm-256color"),
/*stderr_is_tty*/ false,
));
}
#[test]
fn progress_is_quiet_for_dumb_terminal() {
assert!(!should_show_progress(
/*json*/ false,
Some("dumb"),
/*stderr_is_tty*/ true,
));
}
#[test]
fn progress_is_shown_for_human_tty_output() {
assert!(should_show_progress(
/*json*/ false,
Some("xterm-256color"),
/*stderr_is_tty*/ true,
));
}
}
+141
View File
@@ -0,0 +1,141 @@
//! Captures how this Codex process was launched.
//!
//! Runtime diagnostics answer provenance questions that are hard to infer from
//! user reports: which binary is running, which install channel it resembles,
//! which platform it targets, and whether the search command comes from bundled
//! standalone resources or from PATH.
use std::env;
use std::process::Command;
use codex_install_context::InstallContext;
use super::CheckStatus;
use super::DoctorCheck;
use super::describe_install_context;
use super::doctor_install_context;
use super::push_path_detail;
/// Builds the process provenance row for the current Codex executable.
///
/// This check is informational and should not fail on its own; inconsistent
/// install state is reported by the installation and update checks instead.
pub(super) fn runtime_check() -> DoctorCheck {
let current_exe = env::current_exe().ok();
let install_context = doctor_install_context(current_exe.as_deref());
let os = env::consts::OS;
let arch = env::consts::ARCH;
let platform = format!("{os}-{arch}");
let install_method = install_method_name(&install_context);
let mut details = vec![
format!("version: {}", env!("CARGO_PKG_VERSION")),
format!("platform: {platform}"),
format!(
"install method: {}",
describe_install_context(&install_context)
),
format!("commit: {}", build_commit()),
];
push_path_detail(&mut details, "current executable", current_exe.as_deref());
DoctorCheck::new(
"runtime.provenance",
"runtime",
CheckStatus::Ok,
format!("running {install_method} on {platform}"),
)
.details(details)
}
/// Verifies that the search command selected by the install context is usable.
///
/// Standalone installs should point at a bundled ripgrep binary, while local or
/// package-managed installs usually resolve rg from PATH. A warning here means
/// features that depend on file search may degrade even when the CLI launches.
pub(super) fn search_check() -> DoctorCheck {
let current_exe = env::current_exe().ok();
let install_context = doctor_install_context(current_exe.as_deref());
let rg_command = install_context.rg_command();
let provider = search_provider(&install_context);
let mut details = vec![
format!("search command: {}", rg_command.display()),
format!("search provider: {provider}"),
];
let status = if rg_command.components().count() > 1 {
match std::fs::metadata(&rg_command) {
Ok(metadata) if metadata.is_file() => {
details.push("search command readiness: file exists".to_string());
CheckStatus::Ok
}
Ok(_) => {
details.push("search command readiness: path is not a file".to_string());
CheckStatus::Warning
}
Err(err) => {
details.push(format!("search command readiness: {err}"));
CheckStatus::Warning
}
}
} else {
match Command::new(&rg_command).arg("--version").output() {
Ok(output) if output.status.success() => {
let version = String::from_utf8_lossy(&output.stdout)
.lines()
.next()
.unwrap_or("rg version unknown")
.to_string();
details.push(format!("search command readiness: {version}"));
CheckStatus::Ok
}
Ok(output) => {
details.push(format!(
"search command readiness: exited with status {}",
output.status
));
CheckStatus::Warning
}
Err(err) => {
details.push(format!("search command readiness: {err}"));
CheckStatus::Warning
}
}
};
let summary = match status {
CheckStatus::Ok => format!("search is OK ({provider})"),
CheckStatus::Warning => "search command could not be verified".to_string(),
CheckStatus::Fail => unreachable!(),
};
let mut check = DoctorCheck::new("runtime.search", "search", status, summary).details(details);
if status != CheckStatus::Ok {
check = check.remediation("Install ripgrep or repair the bundled standalone resources.");
}
check
}
fn install_method_name(context: &InstallContext) -> &'static str {
match context {
InstallContext::Standalone { .. } => "standalone",
InstallContext::Npm => "npm",
InstallContext::Bun => "bun",
InstallContext::Brew => "brew",
InstallContext::Other => "local build",
}
}
fn search_provider(context: &InstallContext) -> &'static str {
match context {
InstallContext::Standalone {
resources_dir: Some(resources_dir),
..
} if context.rg_command().starts_with(resources_dir) => "bundled",
_ => "system",
}
}
fn build_commit() -> &'static str {
option_env!("CODEX_BUILD_COMMIT")
.or(option_env!("GIT_COMMIT"))
.unwrap_or("unknown")
}
+227
View File
@@ -0,0 +1,227 @@
//! Diagnoses whether Codex update paths target the running installation.
//!
//! Update diagnostics combine cached version metadata, install-channel hints,
//! and bounded latest-version probes. For npm-managed launches, this module also
//! verifies that npm install -g would update the package root that launched the
//! current process, which catches PATH and prefix mismatches before the user runs
//! an update command.
use std::path::Path;
use codex_core::config::Config;
use codex_install_context::InstallContext;
use serde::Deserialize;
use super::CheckStatus;
use super::DoctorCheck;
use super::NpmRootCheck;
use super::doctor_install_context;
use super::doctor_managed_by_npm;
use super::npm_global_root_check;
use super::run_command;
const VERSION_FILE_NAME: &str = "version.json";
const GITHUB_LATEST_RELEASE_URL: &str = "https://api.github.com/repos/openai/codex/releases/latest";
const HOMEBREW_CASK_API_URL: &str = "https://formulae.brew.sh/api/cask/codex.json";
/// Builds the update-health row for the current installation.
///
/// Network failures while fetching latest-version metadata degrade the row to a
/// warning instead of failing doctor outright; update freshness is useful
/// support context but should not mask more direct install/config failures.
pub(super) fn updates_check(config: &Config) -> DoctorCheck {
let current_exe = std::env::current_exe().ok();
let install_context = doctor_install_context(current_exe.as_deref());
let mut details = vec![
format!(
"check for update on startup: {}",
config.check_for_update_on_startup
),
format!("update action: {}", update_action_label(&install_context)),
];
let version_file = config.codex_home.join(VERSION_FILE_NAME);
push_cached_version_details(&mut details, &version_file);
let mut status = CheckStatus::Ok;
let mut summary = "update configuration is locally consistent".to_string();
let mut remediation = None;
if doctor_managed_by_npm(current_exe.as_deref()) {
match npm_global_root_check() {
NpmRootCheck::Match { package_root } => {
details.push(format!("npm update target: {}", package_root.display()));
}
NpmRootCheck::Mismatch {
running_package_root,
npm_package_root,
} => {
status = CheckStatus::Fail;
summary = "update would target a different npm install".to_string();
details.push(format!(
"running package root: {}",
running_package_root.display()
));
details.push(format!("npm package root: {}", npm_package_root.display()));
remediation = Some(format!(
"Fix PATH or npm prefix so the running package root ({}) matches the npm global package root ({}).",
running_package_root.display(),
npm_package_root.display()
));
}
NpmRootCheck::MissingPackageRoot => {
status = status.max(CheckStatus::Warning);
summary = "npm update target could not be proven".to_string();
remediation = Some(
"Reinstall or update Codex so the JS shim provides CODEX_MANAGED_PACKAGE_ROOT."
.to_string(),
);
}
NpmRootCheck::NpmUnavailable(error) => {
status = status.max(CheckStatus::Warning);
summary = "npm update target could not be inspected".to_string();
details.push(format!("npm root -g failed: {error}"));
}
}
}
match fetch_latest_version(&install_context) {
Ok(latest_version) => {
details.push(format!("latest version: {latest_version}"));
if is_newer(&latest_version, env!("CARGO_PKG_VERSION")) == Some(true) {
details.push("latest version status: newer version is available".to_string());
} else {
details.push("latest version status: current version is not older".to_string());
}
}
Err(err) => {
status = status.max(CheckStatus::Warning);
details.push(format!("latest version probe: {err}"));
}
}
let mut check = DoctorCheck::new("updates.status", "updates", status, summary).details(details);
if let Some(remediation) = remediation {
check = check.remediation(remediation);
}
check
}
fn push_cached_version_details(details: &mut Vec<String>, version_file: &Path) {
details.push(format!("version cache: {}", version_file.display()));
match std::fs::read_to_string(version_file) {
Ok(contents) => match serde_json::from_str::<VersionInfo>(&contents) {
Ok(info) => {
details.push(format!("cached latest version: {}", info.latest_version));
if let Some(last_checked_at) = info.last_checked_at {
details.push(format!("last checked at: {last_checked_at}"));
}
if let Some(dismissed_version) = info.dismissed_version {
details.push(format!("dismissed version: {dismissed_version}"));
}
}
Err(err) => details.push(format!("version cache parse: {err}")),
},
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
details.push("version cache: missing".to_string());
}
Err(err) => details.push(format!("version cache read: {err}")),
}
}
fn update_action_label(context: &InstallContext) -> &'static str {
match context {
InstallContext::Npm => "npm install -g @openai/codex",
InstallContext::Bun => "bun install -g @openai/codex",
InstallContext::Brew => "brew upgrade --cask codex",
InstallContext::Standalone { .. } => "standalone installer",
InstallContext::Other => "manual or unknown",
}
}
fn fetch_latest_version(context: &InstallContext) -> Result<String, String> {
match context {
InstallContext::Brew => fetch_homebrew_cask_version(),
InstallContext::Npm
| InstallContext::Bun
| InstallContext::Standalone { .. }
| InstallContext::Other => fetch_latest_github_release_version(),
}
}
fn fetch_latest_github_release_version() -> Result<String, String> {
#[derive(Deserialize)]
struct ReleaseInfo {
tag_name: String,
}
let info = http_get_json::<ReleaseInfo>(GITHUB_LATEST_RELEASE_URL)?;
info.tag_name
.strip_prefix("rust-v")
.map(str::to_string)
.ok_or_else(|| format!("failed to parse latest tag {}", info.tag_name))
}
fn fetch_homebrew_cask_version() -> Result<String, String> {
#[derive(Deserialize)]
struct HomebrewCaskInfo {
version: String,
}
http_get_json::<HomebrewCaskInfo>(HOMEBREW_CASK_API_URL).map(|info| info.version)
}
fn http_get_json<T>(url: &str) -> Result<T, String>
where
T: for<'de> Deserialize<'de>,
{
let body = run_command("curl", ["-fsSL", "--max-time", "5", url])?;
serde_json::from_str::<T>(&body).map_err(|err| err.to_string())
}
fn is_newer(latest: &str, current: &str) -> Option<bool> {
match (parse_version(latest), parse_version(current)) {
(Some(latest), Some(current)) => Some(latest > current),
(Some(_), None) | (None, Some(_)) | (None, None) => None,
}
}
fn parse_version(value: &str) -> Option<(u64, u64, u64)> {
let mut parts = value.trim().split('.');
let major = parts.next()?.parse::<u64>().ok()?;
let minor = parts.next()?.parse::<u64>().ok()?;
let patch = parts.next()?.parse::<u64>().ok()?;
Some((major, minor, patch))
}
#[derive(Deserialize)]
struct VersionInfo {
latest_version: String,
#[serde(default)]
last_checked_at: Option<String>,
#[serde(default)]
dismissed_version: Option<String>,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn is_newer_compares_plain_semver() {
assert_eq!(is_newer("1.2.4", "1.2.3"), Some(true));
assert_eq!(is_newer("1.2.3", "1.2.4"), Some(false));
assert_eq!(is_newer("1.2.3-beta.1", "1.2.2"), None);
}
#[test]
fn update_action_labels_install_contexts() {
assert_eq!(
update_action_label(&InstallContext::Npm),
"npm install -g @openai/codex"
);
assert_eq!(
update_action_label(&InstallContext::Other),
"manual or unknown"
);
}
}
+21 -1
View File
@@ -46,6 +46,7 @@ use supports_color::Stream;
mod app_cmd;
#[cfg(any(target_os = "macos", target_os = "windows"))]
mod desktop_app;
mod doctor;
mod marketplace_cmd;
mod mcp_cmd;
#[cfg(not(windows))]
@@ -53,6 +54,7 @@ mod wsl_paths;
use crate::marketplace_cmd::MarketplaceCli;
use crate::mcp_cmd::McpCli;
use doctor::DoctorCommand;
use codex_core::build_models_manager;
use codex_core::config::ConfigBuilder;
@@ -142,6 +144,9 @@ enum Subcommand {
/// Update Codex to the latest version.
Update,
/// Diagnose local Codex installation, config, auth, and runtime health.
Doctor(DoctorCommand),
/// Run commands within a Codex-provided sandbox.
Sandbox(SandboxArgs),
@@ -1163,6 +1168,20 @@ async fn cli_main(arg0_paths: Arg0DispatchPaths) -> anyhow::Result<()> {
)?;
run_update_command()?;
}
Some(Subcommand::Doctor(doctor_cli)) => {
reject_remote_mode_for_subcommand(
root_remote.as_deref(),
root_remote_auth_token_env.as_deref(),
"doctor",
)?;
doctor::run_doctor(
doctor_cli,
root_config_overrides.clone(),
&interactive,
&arg0_paths,
)
.await?;
}
Some(Subcommand::Cloud(mut cloud_cli)) => {
reject_remote_mode_for_subcommand(
root_remote.as_deref(),
@@ -1688,7 +1707,8 @@ fn unsupported_subcommand_name_for_strict_config(
| Some(Subcommand::Review(_))
| Some(Subcommand::McpServer(_))
| Some(Subcommand::Resume(_))
| Some(Subcommand::Fork(_)) => None,
| Some(Subcommand::Fork(_))
| Some(Subcommand::Doctor(_)) => None,
Some(Subcommand::AppServer(app_server)) if app_server.subcommand.is_none() => None,
Some(Subcommand::AppServer(app_server)) => {
Some(app_server_subcommand_name(app_server.subcommand.as_ref()))