aKode fase 5: rinomina interna (crate akode-*, akode-rs/, akode-cli/, binario akode, AKODE_*, ~/.akode, snapshot)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-11 11:06:46 +01:00
parent df99318392
commit 86e7c72e5f
10383 changed files with 749164 additions and 749170 deletions

60
akode-rs/cli/BUILD.bazel Normal file
View File

@@ -0,0 +1,60 @@
load("@crates//:data.bzl", "DEP_DATA")
load("@crates//:defs.bzl", "all_crate_deps")
load("@rules_rust//rust:defs.bzl", "rust_test")
load("//:defs.bzl", "MACOS_WEBRTC_RUSTC_LINK_FLAGS", "codex_rust_crate")
load("//bazel/platforms:release_binaries.bzl", "multiplatform_binaries")
load("//bazel/rules:e2e_benchmark.bzl", "codex_e2e_benchmark")
load("//bazel/rules:runtime_package.bzl", "release_binary")
codex_rust_crate(
name = "cli",
binaries_with_build_commit = ["codex"],
crate_name = "akode_cli",
extra_binaries = [
"//akode-rs/bwrap:bwrap",
],
rustc_flags_extra = MACOS_WEBRTC_RUSTC_LINK_FLAGS,
test_data_extra = glob(["src/**/snapshots/**"]),
)
# Real installation copies a full debug package. Run after other Bazel tests
# on the CI runner so remote executors do not amplify shared-disk writeback.
rust_test(
name = "cli-app_server_daemon_package-test",
timeout = "long",
srcs = [
"tests/app_server_daemon/package.rs",
"tests/app_server_daemon/support.rs",
],
args = ["--test-threads=1"],
crate_name = "app_server_daemon_package",
crate_root = "tests/app_server_daemon/package.rs",
data = [":codex"],
env = {"CARGO_BIN_EXE_codex": "$(rlocationpath :codex)"},
rustc_env = {"BAZEL_PACKAGE": "akode-rs/cli"},
rustc_flags = MACOS_WEBRTC_RUSTC_LINK_FLAGS,
tags = ["exclusive"],
target_compatible_with = select({
"@platforms//os:linux": [],
"@platforms//os:macos": [],
"//conditions:default": ["@platforms//:incompatible"],
}),
version = DEP_DATA["akode-rs/cli"]["version"],
deps = all_crate_deps(
normal = True,
normal_dev = True,
),
)
release_binary(
binary = ":codex",
)
multiplatform_binaries(
name = "codex",
)
codex_e2e_benchmark(
name = "codex-help",
binaries = [":codex"],
)

148
akode-rs/cli/Cargo.toml Normal file
View File

@@ -0,0 +1,148 @@
[package]
name = "akode-cli"
version.workspace = true
edition.workspace = true
license.workspace = true
build = "build.rs"
default-run = "akode"
[[bin]]
name = "akode"
path = "src/main.rs"
[[bin]]
name = "logs_client"
path = "src/bin/logs_client.rs"
[[test]]
name = "app_server_daemon_package"
path = "tests/app_server_daemon/package.rs"
[lib]
name = "akode_cli"
path = "src/lib.rs"
doctest = false
[lints]
workspace = true
[dependencies]
akode-utils-process = { workspace = true }
anyhow = { workspace = true }
chrono = { workspace = true }
clap = { workspace = true, features = ["derive", "env"] }
clap_complete = { workspace = true }
akode-app-server = { workspace = true }
akode-app-server-daemon = { workspace = true }
akode-app-server-protocol = { workspace = true }
akode-app-server-test-client = { workspace = true }
akode-arg0 = { workspace = true }
akode-build-info = { workspace = true }
akode-api = { workspace = true }
akode-utils-cli = { workspace = true }
akode-config = { workspace = true }
akode-core = { workspace = true }
akode-core-plugins = { workspace = true }
akode-history = { workspace = true }
akode-home = { workspace = true }
akode-http-client = { workspace = true }
akode-exec = { workspace = true }
akode-exec-server = { workspace = true }
akode-exec-server-cli = { workspace = true }
akode-execpolicy = { workspace = true }
akode-extension-api = { workspace = true }
akode-features = { workspace = true }
akode-multi-env-copy-file = { workspace = true }
akode-git-attribution = { workspace = true }
akode-git-utils = { workspace = true }
akode-install-context = { workspace = true }
akode-login = { workspace = true }
akode-model-provider-info = { workspace = true }
akode-memories-write = { workspace = true }
akode-mcp = { workspace = true }
akode-model-provider = { workspace = true }
akode-models-manager = { workspace = true }
akode-plugin = { workspace = true }
akode-protocol = { workspace = true }
akode-tcp-tunnel = { workspace = true }
akode-rmcp-client = { workspace = true }
akode-rollout = { workspace = true }
akode-rollout-trace = { workspace = true }
akode-sandboxing = { workspace = true }
akode-skills-extension = { workspace = true }
akode-state = { workspace = true }
akode-stdio-to-uds = { workspace = true }
akode-terminal-detection = { workspace = true }
akode-thread-store = { workspace = true }
akode-tui = { workspace = true }
akode-utils-absolute-path = { workspace = true }
akode-utils-path = { workspace = true }
akode-utils-path-uri = { workspace = true }
akode-utils-redacted-string = { workspace = true }
akode-websocket-auth = { workspace = true }
crossterm = { workspace = true, features = ["event-stream"] }
futures = { workspace = true }
http = { workspace = true }
libc = { workspace = true }
os_info = { workspace = true }
owo-colors = { workspace = true }
regex-lite = { workspace = true }
serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true }
sqlx = { workspace = true }
supports-color = { workspace = true }
sys-locale = { workspace = true }
tempfile = { workspace = true }
tokio = { workspace = true, features = [
"io-std",
"macros",
"net",
"process",
"rt-multi-thread",
"signal",
"time",
] }
toml = { workspace = true }
tracing = { workspace = true }
tracing-appender = { workspace = true }
tracing-subscriber = { workspace = true }
unicode-segmentation = { workspace = true }
url = { workspace = true }
which = { workspace = true }
[target.'cfg(all(target_os = "linux", target_env = "musl", any(target_arch = "x86_64", target_arch = "aarch64")))'.dependencies]
tikv-jemallocator = { workspace = true }
[target.'cfg(target_os = "windows")'.dependencies]
akode_windows_sandbox = { package = "akode-windows-sandbox", path = "../windows-sandbox-rs" }
windows-sys = { workspace = true, features = [
"Win32_Foundation",
"Win32_Storage_Packaging_Appx",
"Win32_System_Console",
"Win32_System_Threading",
] }
[dev-dependencies]
app_test_support = { workspace = true }
assert_cmd = { workspace = true }
assert_matches = { workspace = true }
akode-app-server-client = { workspace = true }
akode-utils-cargo-bin = { workspace = true }
akode-utils-pty = { workspace = true }
core_test_support = { workspace = true }
flate2 = { workspace = true }
insta = { workspace = true }
jsonwebtoken = { workspace = true }
predicates = { workspace = true }
pretty_assertions = { workspace = true }
sha2 = { workspace = true }
tar = { workspace = true }
tokio-tungstenite = { workspace = true }
vt100 = { workspace = true }
wiremock = { workspace = true }
zstd = { workspace = true }
[package.metadata.cargo-shear]
# These Rust sources are intentionally Bazel-only macrobenchmarks rather than
# Cargo targets.
ignored-paths = ["e2e_benches/*.rs"]

5
akode-rs/cli/build.rs Normal file
View File

@@ -0,0 +1,5 @@
fn main() {
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("macos") {
println!("cargo:rustc-link-arg=-ObjC");
}
}

View File

@@ -0,0 +1,26 @@
#![allow(clippy::expect_used)]
use std::process::Command;
use divan::Bencher;
fn main() {
divan::main();
}
/// Exercises the Bazel-backed end-to-end benchmark path with a cheap,
/// deterministic Codex invocation. Richer scenarios can add separate
/// benchmark binaries without making the shared harness depend on them.
#[divan::bench(sample_count = 20, sample_size = 1)]
fn codex_help(bencher: Bencher) {
let codex = akode_utils_cargo_bin::cargo_bin("akode")
.expect("codex binary should be available through Bazel runfiles");
bencher.bench_local(move || {
let output = Command::new(&codex)
.arg("--help")
.output()
.expect("akode --help should run");
assert!(output.status.success(), "akode --help should succeed");
});
}

View File

@@ -0,0 +1,468 @@
use std::path::PathBuf;
use std::time::Duration;
use anyhow::Context;
use chrono::DateTime;
use clap::Parser;
use clap::ValueEnum;
use akode_core::config::ConfigBuilder;
use akode_state::LogQuery;
use akode_state::LogRow;
use akode_state::SqliteConfig;
use akode_state::StateRuntime;
use akode_utils_absolute_path::AbsolutePathBuf;
use owo_colors::OwoColorize;
#[derive(Debug, Parser)]
#[command(name = "codex-state-logs")]
#[command(about = "Tail aKode logs from the dedicated logs SQLite DB with simple filters")]
struct Args {
/// Path to AKODE_HOME. Defaults to $AKODE_HOME or ~/.akode.
#[arg(long, env = "AKODE_HOME")]
codex_home: Option<PathBuf>,
/// Direct path to the logs SQLite database. Overrides --codex-home.
#[arg(long)]
db: Option<PathBuf>,
/// Minimum log level to include.
#[arg(long, value_enum, ignore_case = true)]
level: Option<LogLevelThreshold>,
/// Start timestamp (RFC3339 or unix seconds).
#[arg(long, value_name = "RFC3339|UNIX")]
from: Option<String>,
/// End timestamp (RFC3339 or unix seconds).
#[arg(long, value_name = "RFC3339|UNIX")]
to: Option<String>,
/// Substring match on module_path. Repeat to include multiple substrings.
#[arg(long = "module")]
module: Vec<String>,
/// Substring match on file path. Repeat to include multiple substrings.
#[arg(long = "file")]
file: Vec<String>,
/// Match one or more thread ids. Repeat to include multiple threads.
#[arg(long = "thread-id")]
thread_id: Vec<String>,
/// Substring match against the rendered log body.
#[arg(long)]
search: Option<String>,
/// Include logs that do not have a thread id.
#[arg(long)]
threadless: bool,
/// Number of matching rows to show before tailing.
#[arg(long, default_value_t = 200)]
backfill: usize,
/// Poll interval in milliseconds.
#[arg(long, default_value_t = 500)]
poll_ms: u64,
/// Show compact output with only time, level, and rendered log body.
#[arg(long)]
compact: bool,
}
#[derive(Debug, Clone)]
struct LogFilter {
levels_upper: Vec<String>,
from_ts: Option<i64>,
to_ts: Option<i64>,
module_like: Vec<String>,
file_like: Vec<String>,
thread_ids: Vec<String>,
search: Option<String>,
include_threadless: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
enum LogLevelThreshold {
Trace,
Debug,
Info,
Warn,
Error,
}
impl LogLevelThreshold {
fn levels_upper(self) -> Vec<String> {
let levels = match self {
LogLevelThreshold::Trace => &["TRACE", "DEBUG", "INFO", "WARN", "ERROR"][..],
LogLevelThreshold::Debug => &["DEBUG", "INFO", "WARN", "ERROR"],
LogLevelThreshold::Info => &["INFO", "WARN", "ERROR"],
LogLevelThreshold::Warn => &["WARN", "ERROR"],
LogLevelThreshold::Error => &["ERROR"],
};
levels.iter().map(ToString::to_string).collect()
}
}
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let args = Args::parse();
let sqlite = resolve_sqlite_config(&args).await?;
let filter = build_filter(&args)?;
let runtime = StateRuntime::init(sqlite, "logs-client".to_string()).await?;
let mut last_id =
print_backfill(runtime.as_ref(), &filter, args.backfill, args.compact).await?;
if last_id == 0 {
last_id = fetch_max_id(runtime.as_ref(), &filter).await?;
}
let poll_interval = Duration::from_millis(args.poll_ms);
loop {
let rows = fetch_new_rows(runtime.as_ref(), &filter, last_id).await?;
for row in rows {
last_id = last_id.max(row.id);
println!("{}", format_row(&row, args.compact));
}
tokio::time::sleep(poll_interval).await;
}
}
async fn resolve_sqlite_config(args: &Args) -> anyhow::Result<SqliteConfig> {
if let Some(db_path) = args.db.as_ref() {
let sqlite_home = db_path
.parent()
.map(ToOwned::to_owned)
.unwrap_or_else(|| PathBuf::from("."));
return Ok(SqliteConfig::from_sqlite_home_with_nfs_enforcement(
AbsolutePathBuf::relative_to_current_dir(sqlite_home)?,
/*enforce_delete_on_nfs*/ false,
));
}
let mut config_builder = ConfigBuilder::default();
if let Some(codex_home) = args.codex_home.as_ref() {
config_builder = config_builder.codex_home(codex_home.clone());
}
let config = config_builder.build().await?;
Ok(config.sqlite_config().clone())
}
fn build_filter(args: &Args) -> anyhow::Result<LogFilter> {
let from_ts = args
.from
.as_deref()
.map(parse_timestamp)
.transpose()
.context("failed to parse --from")?;
let to_ts = args
.to
.as_deref()
.map(parse_timestamp)
.transpose()
.context("failed to parse --to")?;
let levels_upper = args
.level
.map_or_else(Vec::new, LogLevelThreshold::levels_upper);
let module_like = args
.module
.iter()
.filter(|module| !module.is_empty())
.cloned()
.collect::<Vec<_>>();
let file_like = args
.file
.iter()
.filter(|file| !file.is_empty())
.cloned()
.collect::<Vec<_>>();
let thread_ids = args
.thread_id
.iter()
.filter(|thread_id| !thread_id.is_empty())
.cloned()
.collect::<Vec<_>>();
Ok(LogFilter {
levels_upper,
from_ts,
to_ts,
module_like,
file_like,
thread_ids,
search: args.search.clone(),
include_threadless: args.threadless,
})
}
fn parse_timestamp(value: &str) -> anyhow::Result<i64> {
if let Ok(secs) = value.parse::<i64>() {
return Ok(secs);
}
let dt = DateTime::parse_from_rfc3339(value)
.with_context(|| format!("expected RFC3339 or unix seconds, got {value}"))?;
Ok(dt.timestamp())
}
async fn print_backfill(
runtime: &StateRuntime,
filter: &LogFilter,
backfill: usize,
compact: bool,
) -> anyhow::Result<i64> {
if backfill == 0 {
return Ok(0);
}
let mut rows = fetch_backfill(runtime, filter, backfill).await?;
rows.reverse();
let mut last_id = 0;
for row in rows {
last_id = last_id.max(row.id);
println!("{}", format_row(&row, compact));
}
Ok(last_id)
}
async fn fetch_backfill(
runtime: &StateRuntime,
filter: &LogFilter,
backfill: usize,
) -> anyhow::Result<Vec<LogRow>> {
let query = to_log_query(
filter,
Some(backfill),
/*after_id*/ None,
/*descending*/ true,
);
runtime
.query_logs(&query)
.await
.context("failed to fetch backfill logs")
}
async fn fetch_new_rows(
runtime: &StateRuntime,
filter: &LogFilter,
last_id: i64,
) -> anyhow::Result<Vec<LogRow>> {
let query = to_log_query(
filter,
/*limit*/ None,
Some(last_id),
/*descending*/ false,
);
runtime
.query_logs(&query)
.await
.context("failed to fetch new logs")
}
async fn fetch_max_id(runtime: &StateRuntime, filter: &LogFilter) -> anyhow::Result<i64> {
let query = to_log_query(
filter, /*limit*/ None, /*after_id*/ None, /*descending*/ false,
);
runtime
.max_log_id(&query)
.await
.context("failed to fetch max log id")
}
fn to_log_query(
filter: &LogFilter,
limit: Option<usize>,
after_id: Option<i64>,
descending: bool,
) -> LogQuery {
LogQuery {
levels_upper: filter.levels_upper.clone(),
from_ts: filter.from_ts,
to_ts: filter.to_ts,
module_like: filter.module_like.clone(),
file_like: filter.file_like.clone(),
thread_ids: filter.thread_ids.clone(),
search: filter.search.clone(),
include_threadless: filter.include_threadless,
after_id,
limit,
descending,
}
}
fn format_row(row: &LogRow, compact: bool) -> String {
let timestamp = formatter::ts(row.ts, row.ts_nanos, compact);
let level = row.level.as_str();
let target = row.target.as_str();
let message = row.message.as_deref().unwrap_or("");
let level_colored = formatter::level(level);
let timestamp_colored = timestamp.dimmed().to_string();
let thread_id = row.thread_id.as_deref().unwrap_or("-");
let thread_id_colored = thread_id.blue().dimmed().to_string();
let target_colored = target.dimmed().to_string();
let message_colored = heuristic_formatting(message);
if compact {
format!("{timestamp_colored} {level_colored} {message_colored}")
} else {
format!(
"{timestamp_colored} {level_colored} [{thread_id_colored}] {target_colored} - {message_colored}"
)
}
}
fn heuristic_formatting(message: &str) -> String {
if matcher::apply_patch(message) {
formatter::apply_patch(message)
} else {
message.bold().to_string()
}
}
mod matcher {
pub(super) fn apply_patch(message: &str) -> bool {
message.contains("ToolCall: apply_patch")
}
}
mod formatter {
use chrono::DateTime;
use chrono::SecondsFormat;
use chrono::Utc;
use owo_colors::OwoColorize;
pub(super) fn apply_patch(message: &str) -> String {
message
.lines()
.map(|line| {
if line.starts_with('+') {
line.green().bold().to_string()
} else if line.starts_with('-') {
line.red().bold().to_string()
} else {
line.bold().to_string()
}
})
.collect::<Vec<_>>()
.join("\n")
}
pub(super) fn ts(ts: i64, ts_nanos: i64, compact: bool) -> String {
let nanos = u32::try_from(ts_nanos).unwrap_or(0);
match DateTime::<Utc>::from_timestamp(ts, nanos) {
Some(dt) if compact => dt.format("%H:%M:%S").to_string(),
Some(dt) => dt.to_rfc3339_opts(SecondsFormat::Millis, true),
None => format!("{ts}.{ts_nanos:09}Z"),
}
}
pub(super) fn level(level: &str) -> String {
let padded = format!("{level:<5}");
if level.eq_ignore_ascii_case("error") {
return padded.red().bold().to_string();
}
if level.eq_ignore_ascii_case("warn") {
return padded.yellow().bold().to_string();
}
if level.eq_ignore_ascii_case("info") {
return padded.green().bold().to_string();
}
if level.eq_ignore_ascii_case("debug") {
return padded.blue().bold().to_string();
}
if level.eq_ignore_ascii_case("trace") {
return padded.magenta().bold().to_string();
}
padded.bold().to_string()
}
}
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
use std::ffi::OsString;
#[test]
fn log_level_threshold_includes_more_severe_levels() {
assert_eq!(
LogLevelThreshold::Warn.levels_upper(),
vec!["WARN".to_string(), "ERROR".to_string()]
);
assert_eq!(
LogLevelThreshold::Trace.levels_upper(),
vec![
"TRACE".to_string(),
"DEBUG".to_string(),
"INFO".to_string(),
"WARN".to_string(),
"ERROR".to_string(),
]
);
}
#[test]
fn log_level_rejects_aliases_and_unknown_values() {
assert!(Args::try_parse_from(["codex-state-logs", "--level", "warning"]).is_err());
assert!(Args::try_parse_from(["codex-state-logs", "--level", "err"]).is_err());
assert!(Args::try_parse_from(["codex-state-logs", "--level", "warn,error"]).is_err());
}
#[test]
fn log_level_accepts_canonical_values_case_insensitively() {
let args = Args::try_parse_from(["codex-state-logs", "--level", "WARN"])
.expect("parse uppercase log level");
assert_eq!(args.level, Some(LogLevelThreshold::Warn));
}
/// Explicit database selection must not parse an overridden Codex home.
#[tokio::test]
async fn direct_db_skips_codex_home_config() {
let codex_home = tempfile::tempdir().expect("create Codex home");
std::fs::write(codex_home.path().join("config.toml"), "model = [")
.expect("write invalid config");
let sqlite_home = tempfile::tempdir().expect("create SQLite home");
let db_path = sqlite_home.path().join("logs_2.sqlite");
let args = Args::try_parse_from([
OsString::from("codex-state-logs"),
OsString::from("--codex-home"),
codex_home.path().as_os_str().to_owned(),
OsString::from("--db"),
db_path.as_os_str().to_owned(),
])
.expect("parse arguments");
let sqlite = resolve_sqlite_config(&args)
.await
.expect("resolve SQLite config");
assert_eq!(sqlite.logs_db_path(), db_path);
}
/// Direct database selection must preserve native path bytes.
#[cfg(unix)]
#[tokio::test]
async fn direct_db_preserves_non_utf8_path() {
use std::os::unix::ffi::OsStrExt;
use std::os::unix::ffi::OsStringExt;
let temp_dir = tempfile::tempdir().expect("create temp dir");
let mut db_path = temp_dir.path().as_os_str().as_bytes().to_vec();
db_path.extend_from_slice(b"/non-utf8-\xff/logs_2.sqlite");
let db_path = PathBuf::from(OsString::from_vec(db_path));
let args = Args::try_parse_from([
OsString::from("codex-state-logs"),
OsString::from("--db"),
db_path.as_os_str().to_owned(),
])
.expect("parse arguments");
let sqlite = resolve_sqlite_config(&args)
.await
.expect("resolve SQLite config");
assert_eq!(sqlite.logs_db_path(), db_path);
}
}

View File

@@ -0,0 +1,29 @@
//! Preserve config overrides across command boundaries without changing typed child arguments.
use crate::MultitoolCli;
use clap::CommandFactory;
use clap::FromArgMatches;
use akode_utils_cli::collect_config_overrides;
use std::ffi::OsString;
pub(super) fn try_parse_from(
args: impl IntoIterator<Item = impl Into<OsString>>,
) -> Result<MultitoolCli, clap::Error> {
let args: Vec<OsString> = args.into_iter().map(Into::into).collect();
let mut command = MultitoolCli::command();
let mut matches = command.try_get_matches_from_mut(&args)?;
crate::queue_cmd::validate_options(&command, &matches)?;
let mut cli = MultitoolCli::from_arg_matches_mut(&mut matches)
.map_err(|error| error.format(&mut command))?;
if cli.subcommand.is_none() || cli.config_overrides.raw_overrides.is_empty() {
return Ok(cli);
}
// Keep child copies unchanged: dispatch merges apply them after feature overrides.
cli.config_overrides = collect_config_overrides(MultitoolCli::command(), args)?;
Ok(cli)
}
#[cfg(test)]
#[path = "config_override_args_tests.rs"]
mod tests;

View File

@@ -0,0 +1,37 @@
//! Regression coverage for overrides split across CLI command boundaries.
use super::try_parse_from;
use crate::Subcommand;
use crate::mcp_cmd::McpSubcommand;
use pretty_assertions::assert_eq;
#[test]
fn preserves_scoped_overrides_and_forwarded_arguments() {
let cli = try_parse_from([
"codex",
"--config=a=1",
"mcp",
"-cb=2",
"add",
"example",
"-c",
"a=3",
"--",
"program",
"-c",
"payload",
])
.expect("parse");
assert_eq!(cli.config_overrides.raw_overrides, ["a=1", "b=2", "a=3"]);
let Some(Subcommand::Mcp(mcp)) = cli.subcommand else {
panic!("expected mcp");
};
assert_eq!(mcp.config_overrides.raw_overrides, ["a=3"]);
let McpSubcommand::Add(add) = mcp.subcommand else {
panic!("expected add");
};
assert_eq!(
add.transport_args.stdio.expect("stdio transport").command,
["program", "-c", "payload"],
);
}

View File

@@ -0,0 +1,42 @@
//! Confirmation for copying the invoking CLI package into a daemon installation.
use std::io::IsTerminal;
use anyhow::Result;
use akode_app_server_daemon::InstallRequest;
pub(crate) fn confirm_install(request: &InstallRequest, yes: bool) -> Result<bool> {
eprintln!("{}", describe_install(request));
if yes {
return Ok(true);
}
anyhow::ensure!(
std::io::stdin().is_terminal() && std::io::stderr().is_terminal(),
"daemon installation requires confirmation; rerun with --yes to copy this CLI package"
);
let confirmed = crate::confirm("Copy this package? [y/N]: ")?;
if !confirmed {
eprintln!("Daemon installation cancelled.");
}
Ok(confirmed)
}
fn describe_install(request: &InstallRequest) -> String {
let mut message = format!(
"Replace installed daemon version {} with CLI version {} from {}.\nThe daemon package will be installed in {}.\nThe selected package will be pinned. Run `akode app-server daemon update` to return to production updates.",
request.installed_version.as_deref().unwrap_or("unknown"),
request.version,
request.source.display(),
request.destination.display()
);
if request.restart_required {
message.push_str(
"\nThe running daemon will restart; active or queued work may be interrupted.",
);
}
message
}
#[cfg(test)]
#[path = "daemon_install_tests.rs"]
mod tests;

View File

@@ -0,0 +1,18 @@
use super::*;
#[test]
fn running_daemon_replacement_prompt() {
let request = InstallRequest {
source: "/cli/package".into(),
version: "0.0.0".into(),
destination: "/home/packages/app-server-daemon".into(),
installed_version: Some("0.152.0".into()),
restart_required: true,
};
insta::assert_snapshot!(describe_install(&request), @r"
Replace installed daemon version 0.152.0 with CLI version 0.0.0 from /cli/package.
The daemon package will be installed in /home/packages/app-server-daemon.
The selected package will be pinned. Run `akode app-server daemon update` to return to production updates.
The running daemon will restart; active or queued work may be interrupted.
");
}

View File

@@ -0,0 +1,69 @@
#![cfg(test)]
use super::*;
use akode_tui::DaemonUpdateSource;
use pretty_assertions::assert_eq;
use std::os::unix::fs::PermissionsExt;
#[test]
fn package_update_runs_outside_the_project() -> anyhow::Result<()> {
const CHILD: &str = "AKODE_TEST_PACKAGE_UPDATE_CHILD";
if std::env::var_os(CHILD).is_some() {
return run_update_action(UpdateAction::PnpmGlobalLatest, /*cli_executable*/ None);
}
let project = tempfile::tempdir()?;
let bin = tempfile::tempdir()?;
akode_utils_cargo_bin::write_executable(
&bin.path().join("pnpm"),
"#!/bin/sh\npwd -P > \"$0.cwd\"\n",
)?;
assert_cmd::Command::new(std::env::current_exe()?)
.args([
"--exact",
"daemon_update_tests::package_update_runs_outside_the_project",
])
.current_dir(project.path())
.env("TMPDIR", project.path())
.env("PATH", bin.path())
.env(CHILD, "1")
.assert()
.success();
let cwd = std::fs::read_to_string(bin.path().join("pnpm.cwd"))?;
assert!(!std::path::Path::new(cwd.trim_end()).starts_with(project.path().canonicalize()?));
Ok(())
}
#[test]
fn daemon_handoff_uses_selected_executable_and_propagates_failure() -> anyhow::Result<()> {
let dir = tempfile::tempdir()?;
let executable = dir.path().join("launching CLI");
let receipt = dir.path().join("launching CLI.args");
akode_utils_cargo_bin::write_executable(
&executable,
"#!/bin/sh\nprintf '%s\\n' \"$@\" > \"$0.args\"\n",
)?;
std::fs::set_permissions(&executable, std::fs::Permissions::from_mode(/*mode*/ 0o700))?;
for (source, expected) in [
(
DaemonUpdateSource::PublicStable,
"app-server\ndaemon\nupdate\n",
),
(
DaemonUpdateSource::ThisCli,
"app-server\ndaemon\nupdate\n--from-cli\n--yes\n",
),
] {
run_update_action(UpdateAction::Daemon(source), Some(&executable))?;
assert_eq!(std::fs::read_to_string(&receipt)?, expected);
}
akode_utils_cargo_bin::write_executable(&executable, "#!/bin/sh\nexit 7\n")?;
let error = run_update_action(
UpdateAction::Daemon(DaemonUpdateSource::ThisCli),
Some(&executable),
)
.unwrap_err();
assert!(error.to_string().contains("Daemon update failed"));
Ok(())
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,372 @@
use std::collections::HashSet;
use tokio::task::JoinHandle;
use tracing::warn;
/// Tracks the (recursive) descendants of a process by using `kqueue` to watch for fork events, and
/// `proc_listchildpids` to list the children of a process.
pub(crate) struct PidTracker {
kq: libc::c_int,
handle: JoinHandle<HashSet<i32>>,
}
impl PidTracker {
pub(crate) fn new(root_pid: i32) -> Option<Self> {
if root_pid <= 0 {
return None;
}
let kq = unsafe { libc::kqueue() };
let handle = tokio::task::spawn_blocking(move || track_descendants(kq, root_pid));
Some(Self { kq, handle })
}
pub(crate) async fn stop(self) -> HashSet<i32> {
trigger_stop_event(self.kq);
self.handle.await.unwrap_or_default()
}
}
unsafe extern "C" {
fn proc_listchildpids(
ppid: libc::c_int,
buffer: *mut libc::c_void,
buffersize: libc::c_int,
) -> libc::c_int;
}
/// Wrap proc_listchildpids.
fn list_child_pids(parent: i32) -> Vec<i32> {
unsafe {
let mut capacity: usize = 16;
loop {
let mut buf: Vec<i32> = vec![0; capacity];
let count = proc_listchildpids(
parent as libc::c_int,
buf.as_mut_ptr() as *mut libc::c_void,
(buf.len() * std::mem::size_of::<i32>()) as libc::c_int,
);
if count <= 0 {
return Vec::new();
}
let returned = count as usize;
if returned < capacity {
buf.truncate(returned);
return buf;
}
capacity = capacity.saturating_mul(2).max(returned + 16);
}
}
}
fn pid_is_alive(pid: i32) -> bool {
if pid <= 0 {
return false;
}
let res = unsafe { libc::kill(pid as libc::pid_t, 0) };
if res == 0 {
true
} else {
matches!(
std::io::Error::last_os_error().raw_os_error(),
Some(libc::EPERM)
)
}
}
enum WatchPidError {
ProcessGone,
Other(std::io::Error),
}
/// Add `pid` to the watch list in `kq`.
fn watch_pid(kq: libc::c_int, pid: i32) -> Result<(), WatchPidError> {
if pid <= 0 {
return Err(WatchPidError::ProcessGone);
}
let kev = libc::kevent {
ident: pid as libc::uintptr_t,
filter: libc::EVFILT_PROC,
flags: libc::EV_ADD | libc::EV_CLEAR,
fflags: libc::NOTE_FORK | libc::NOTE_EXEC | libc::NOTE_EXIT,
data: 0,
udata: std::ptr::null_mut(),
};
let res = unsafe { libc::kevent(kq, &kev, 1, std::ptr::null_mut(), 0, std::ptr::null()) };
if res < 0 {
let err = std::io::Error::last_os_error();
if err.raw_os_error() == Some(libc::ESRCH) {
Err(WatchPidError::ProcessGone)
} else {
Err(WatchPidError::Other(err))
}
} else {
Ok(())
}
}
fn watch_children(
kq: libc::c_int,
parent: i32,
seen: &mut HashSet<i32>,
active: &mut HashSet<i32>,
) {
for child_pid in list_child_pids(parent) {
add_pid_watch(kq, child_pid, seen, active);
}
}
/// Watch `pid` and its children, updating `seen` and `active` sets.
fn add_pid_watch(kq: libc::c_int, pid: i32, seen: &mut HashSet<i32>, active: &mut HashSet<i32>) {
if pid <= 0 {
return;
}
let newly_seen = seen.insert(pid);
let mut should_recurse = newly_seen;
if active.insert(pid) {
match watch_pid(kq, pid) {
Ok(()) => {
should_recurse = true;
}
Err(WatchPidError::ProcessGone) => {
active.remove(&pid);
return;
}
Err(WatchPidError::Other(err)) => {
warn!("failed to watch pid {pid}: {err}");
active.remove(&pid);
return;
}
}
}
if should_recurse {
watch_children(kq, pid, seen, active);
}
}
const STOP_IDENT: libc::uintptr_t = 1;
fn register_stop_event(kq: libc::c_int) -> bool {
let kev = libc::kevent {
ident: STOP_IDENT,
filter: libc::EVFILT_USER,
flags: libc::EV_ADD | libc::EV_CLEAR,
fflags: 0,
data: 0,
udata: std::ptr::null_mut(),
};
let res = unsafe { libc::kevent(kq, &kev, 1, std::ptr::null_mut(), 0, std::ptr::null()) };
res >= 0
}
fn trigger_stop_event(kq: libc::c_int) {
if kq < 0 {
return;
}
let kev = libc::kevent {
ident: STOP_IDENT,
filter: libc::EVFILT_USER,
flags: 0,
fflags: libc::NOTE_TRIGGER,
data: 0,
udata: std::ptr::null_mut(),
};
let _ = unsafe { libc::kevent(kq, &kev, 1, std::ptr::null_mut(), 0, std::ptr::null()) };
}
/// Put all of the above together to track all the descendants of `root_pid`.
fn track_descendants(kq: libc::c_int, root_pid: i32) -> HashSet<i32> {
if kq < 0 {
let mut seen = HashSet::new();
seen.insert(root_pid);
return seen;
}
if !register_stop_event(kq) {
let mut seen = HashSet::new();
seen.insert(root_pid);
let _ = unsafe { libc::close(kq) };
return seen;
}
let mut seen: HashSet<i32> = HashSet::new();
let mut active: HashSet<i32> = HashSet::new();
add_pid_watch(kq, root_pid, &mut seen, &mut active);
const EVENTS_CAP: usize = 32;
let mut events: [libc::kevent; EVENTS_CAP] =
unsafe { std::mem::MaybeUninit::zeroed().assume_init() };
let mut stop_requested = false;
loop {
if active.is_empty() {
if !pid_is_alive(root_pid) {
break;
}
add_pid_watch(kq, root_pid, &mut seen, &mut active);
if active.is_empty() {
continue;
}
}
let nev = unsafe {
libc::kevent(
kq,
std::ptr::null::<libc::kevent>(),
0,
events.as_mut_ptr(),
EVENTS_CAP as libc::c_int,
std::ptr::null(),
)
};
if nev < 0 {
let err = std::io::Error::last_os_error();
if err.kind() == std::io::ErrorKind::Interrupted {
continue;
}
break;
}
if nev == 0 {
continue;
}
for ev in events.iter().take(nev as usize) {
let pid = ev.ident as i32;
if ev.filter == libc::EVFILT_USER && ev.ident == STOP_IDENT {
stop_requested = true;
break;
}
if (ev.flags & libc::EV_ERROR) != 0 {
if ev.data == libc::ESRCH as isize {
active.remove(&pid);
}
continue;
}
if (ev.fflags & libc::NOTE_FORK) != 0 {
watch_children(kq, pid, &mut seen, &mut active);
}
if (ev.fflags & libc::NOTE_EXIT) != 0 {
active.remove(&pid);
}
}
if stop_requested {
break;
}
}
let _ = unsafe { libc::close(kq) };
seen
}
#[cfg(test)]
mod tests {
use super::*;
use std::process::Command;
use std::process::Stdio;
use std::time::Duration;
#[test]
fn pid_is_alive_detects_current_process() {
let pid = std::process::id() as i32;
assert!(pid_is_alive(pid));
}
#[cfg(target_os = "macos")]
#[test]
fn list_child_pids_includes_spawned_child() {
let mut child = Command::new("/bin/sleep")
.arg("5")
.stdin(Stdio::null())
.spawn()
.expect("failed to spawn child process");
let child_pid = child.id() as i32;
let parent_pid = std::process::id() as i32;
let mut found = false;
for _ in 0..100 {
if list_child_pids(parent_pid).contains(&child_pid) {
found = true;
break;
}
std::thread::sleep(Duration::from_millis(10));
}
let _ = child.kill();
let _ = child.wait();
assert!(found, "expected to find child pid {child_pid} in list");
}
#[cfg(target_os = "macos")]
#[tokio::test]
async fn pid_tracker_collects_spawned_children() {
let tracker = PidTracker::new(std::process::id() as i32).expect("failed to create tracker");
let mut child = Command::new("/bin/sleep")
.arg("0.1")
.stdin(Stdio::null())
.spawn()
.expect("failed to spawn child process");
let child_pid = child.id() as i32;
let parent_pid = std::process::id() as i32;
let _ = child.wait();
let seen = tracker.stop().await;
assert!(
seen.contains(&parent_pid),
"expected tracker to include parent pid {parent_pid}"
);
assert!(
seen.contains(&child_pid),
"expected tracker to include child pid {child_pid}"
);
}
#[cfg(target_os = "macos")]
#[tokio::test]
async fn pid_tracker_collects_bash_subshell_descendants() {
let tracker = PidTracker::new(std::process::id() as i32).expect("failed to create tracker");
let child = Command::new("/bin/bash")
.arg("-c")
.arg("(sleep 0.1 & echo $!; wait)")
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()
.expect("failed to spawn bash");
let output = child.wait_with_output().unwrap().stdout;
let subshell_pid = String::from_utf8_lossy(&output)
.trim()
.parse::<i32>()
.expect("failed to parse subshell pid");
let seen = tracker.stop().await;
assert!(
seen.contains(&subshell_pid),
"expected tracker to include subshell pid {subshell_pid}"
);
}
}

View File

@@ -0,0 +1,114 @@
use std::collections::HashSet;
use tokio::io::AsyncBufReadExt;
use tokio::process::Child;
use tokio::task::JoinHandle;
use super::pid_tracker::PidTracker;
pub struct SandboxDenial {
pub name: String,
pub capability: String,
}
pub struct DenialLogger {
log_stream: Child,
pid_tracker: Option<PidTracker>,
log_reader: Option<JoinHandle<Vec<u8>>>,
}
impl DenialLogger {
pub(crate) fn new() -> Option<Self> {
let mut log_stream = start_log_stream()?;
let stdout = log_stream.stdout.take()?;
let log_reader = tokio::spawn(async move {
let mut reader = tokio::io::BufReader::new(stdout);
let mut logs = Vec::new();
let mut chunk = Vec::new();
loop {
match reader.read_until(b'\n', &mut chunk).await {
Ok(0) | Err(_) => break,
Ok(_) => {
logs.extend_from_slice(&chunk);
chunk.clear();
}
}
}
logs
});
Some(Self {
log_stream,
pid_tracker: None,
log_reader: Some(log_reader),
})
}
pub(crate) fn on_child_spawn(&mut self, child: &Child) {
if let Some(root_pid) = child.id() {
self.pid_tracker = PidTracker::new(root_pid as i32);
}
}
pub(crate) async fn finish(mut self) -> Vec<SandboxDenial> {
let pid_set = match self.pid_tracker {
Some(tracker) => tracker.stop().await,
None => Default::default(),
};
if pid_set.is_empty() {
return Vec::new();
}
let _ = self.log_stream.kill().await;
let _ = self.log_stream.wait().await;
let logs_bytes = match self.log_reader.take() {
Some(handle) => handle.await.unwrap_or_default(),
None => Vec::new(),
};
let logs = String::from_utf8_lossy(&logs_bytes);
let mut seen: HashSet<(String, String)> = HashSet::new();
let mut denials: Vec<SandboxDenial> = Vec::new();
for line in logs.lines() {
if let Ok(json) = serde_json::from_str::<serde_json::Value>(line)
&& let Some(msg) = json.get("eventMessage").and_then(|v| v.as_str())
&& let Some((pid, name, capability)) = parse_message(msg)
&& pid_set.contains(&pid)
&& seen.insert((name.clone(), capability.clone()))
{
denials.push(SandboxDenial { name, capability });
}
}
denials
}
}
fn start_log_stream() -> Option<Child> {
use std::process::Stdio;
const PREDICATE: &str = r#"(((processID == 0) AND (senderImagePath CONTAINS "/Sandbox")) OR (subsystem == "com.apple.sandbox.reporting"))"#;
tokio::process::Command::new("log")
.args(["stream", "--style", "ndjson", "--predicate", PREDICATE])
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.kill_on_drop(true)
.spawn()
.ok()
}
fn parse_message(msg: &str) -> Option<(i32, String, String)> {
// Example message:
// Sandbox: processname(1234) deny(1) capability-name args...
static RE: std::sync::OnceLock<regex_lite::Regex> = std::sync::OnceLock::new();
let re = RE.get_or_init(|| {
#[expect(clippy::unwrap_used)]
regex_lite::Regex::new(r"^Sandbox:\s*(.+?)\((\d+)\)\s+deny\(.*?\)\s*(.+)$").unwrap()
});
let (_, [name, pid_str, capability]) = re.captures(msg)?.extract();
let pid = pid_str.trim().parse::<i32>().ok()?;
Some((pid, name.to_string(), capability.to_string()))
}

4539
akode-rs/cli/src/doctor.rs Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,365 @@
//! 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 bounded initialize probe when a socket already exists. That
//! keeps doctor safe to run while the user is debugging startup or update-loop
//! issues.
use std::io::Read;
use std::num::NonZeroU32;
use std::path::Path;
use akode_core::config::Config;
use serde::Deserialize;
use super::CheckStatus;
use super::DoctorCheck;
const MAX_PROBE_ERROR_CHARS: usize = 120;
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";
const MAX_SETTINGS_BYTES: u64 = 16 * 1024;
#[derive(Deserialize)]
struct ConfiguredSettings {
updater: Option<ConfiguredUpdater>,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct ConfiguredUpdater {
auto_update_enabled: Option<bool>,
update_interval_minutes: Option<NonZeroU32>,
}
/// 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) async 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),
);
push_file_detail(
&mut details,
"dedicated pid file",
&state_dir.join("daemon.pid"),
);
push_file_detail(
&mut details,
"dedicated update-loop pid file",
&state_dir.join("daemon-updater.pid"),
);
push_configured_updater(&mut details, &state_dir.join(SETTINGS_FILE_NAME));
let socket_path = match akode_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()).await;
details.push(format!("status: {}", status.detail_label()));
if let Some(version_detail) = status.app_server_version_detail() {
details.push(version_detail);
}
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 akode 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 push_configured_updater(details: &mut Vec<String>, path: &Path) {
if !path.is_file() {
return;
}
let mut contents = Vec::new();
let read = std::fs::File::open(path)
.and_then(|file| file.take(MAX_SETTINGS_BYTES + 1).read_to_end(&mut contents));
let settings = read
.ok()
.filter(|_| contents.len() as u64 <= MAX_SETTINGS_BYTES)
.and_then(|_| serde_json::from_slice::<ConfiguredSettings>(&contents).ok());
let Some(settings) = settings else {
details.push("configured updater settings: unreadable or invalid".into());
return;
};
if let Some(updater) = settings.updater {
if let Some(enabled) = updater.auto_update_enabled {
details.push(format!(
"automatic updates: {} (configured)",
if enabled { "enabled" } else { "disabled" }
));
}
if let Some(minutes) = updater.update_interval_minutes {
details.push(format!("update interval: {minutes} minutes (configured)"));
}
}
}
fn server_mode(state_dir: &Path) -> &'static str {
if state_dir.join(SETTINGS_FILE_NAME).is_file() {
"persistent"
} else {
"ephemeral"
}
}
enum SocketStatus {
NotRunning,
Running(String),
StaleOrUnreachable(String),
}
impl SocketStatus {
fn check_status(&self) -> CheckStatus {
match self {
Self::NotRunning | Self::Running(_) => CheckStatus::Ok,
Self::StaleOrUnreachable(_) => CheckStatus::Warning,
}
}
fn summary(&self) -> &'static str {
match self {
Self::NotRunning => "background server is not running",
Self::Running(_) => "background server is running",
Self::StaleOrUnreachable(_) => "background server socket is stale or unreachable",
}
}
fn detail_label(&self) -> &'static str {
match self {
Self::NotRunning => "not running",
Self::Running(_) => "running",
Self::StaleOrUnreachable(_) => "stale or unreachable",
}
}
fn app_server_version_detail(&self) -> Option<String> {
match self {
Self::NotRunning => None,
Self::Running(app_server_version) => {
Some(format!("app-server version: {app_server_version}"))
}
Self::StaleOrUnreachable(error) => {
Some(format!("app-server version: unavailable ({error})"))
}
}
}
}
async fn socket_status(socket_path: &Path) -> SocketStatus {
if !socket_path.exists() {
return SocketStatus::NotRunning;
}
match akode_app_server_daemon::probe_app_server_version(socket_path).await {
Ok(app_server_version) => SocketStatus::Running(app_server_version),
Err(err) => SocketStatus::StaleOrUnreachable(concise_probe_error(&err, socket_path)),
}
}
fn concise_probe_error(err: &anyhow::Error, socket_path: &Path) -> String {
let socket_path = socket_path.display().to_string();
let message = err
.to_string()
.replace(&socket_path, "control socket")
.split_whitespace()
.collect::<Vec<_>>()
.join(" ");
if message.is_empty() {
return "unknown error".to_string();
}
let mut chars = message.chars();
let truncated = chars
.by_ref()
.take(MAX_PROBE_ERROR_CHARS)
.collect::<String>();
if chars.next().is_some() {
format!("{truncated}...")
} else {
message
}
}
#[cfg(test)]
mod tests {
use std::path::PathBuf;
use akode_core::config::ConfigBuilder;
use pretty_assertions::assert_eq;
use super::*;
async fn test_config(codex_home: PathBuf) -> Config {
ConfigBuilder::default()
.codex_home(codex_home)
.build()
.await
.expect("config")
}
fn create_socket_placeholder(config: &Config) {
let socket_path = akode_app_server::app_server_control_socket_path(&config.codex_home)
.expect("socket path");
std::fs::create_dir_all(socket_path.parent().expect("socket parent"))
.expect("create socket dir");
std::fs::write(socket_path, "").expect("create socket placeholder");
}
#[tokio::test]
async fn not_running_background_server_stays_ok_without_version() {
let temp = tempfile::tempdir().expect("tempdir");
let config = test_config(temp.path().to_path_buf()).await;
let check = background_server_check(&config).await;
assert_eq!(check.status, CheckStatus::Ok);
assert_eq!(check.summary, "background server is not running");
assert!(check.details.contains(&"status: not running".to_string()));
assert!(
!check
.details
.iter()
.any(|detail| detail.starts_with("app-server version:"))
);
}
#[test]
fn running_background_server_reports_app_server_version() {
let status = SocketStatus::Running("1.2.3".to_string());
assert_eq!(status.check_status(), CheckStatus::Ok);
assert_eq!(status.summary(), "background server is running");
assert_eq!(status.detail_label(), "running");
assert_eq!(
status.app_server_version_detail(),
Some("app-server version: 1.2.3".to_string())
);
}
#[tokio::test]
async fn failed_version_probe_reports_unavailable() {
let temp = tempfile::tempdir().expect("tempdir");
let config = test_config(temp.path().to_path_buf()).await;
create_socket_placeholder(&config);
let check = background_server_check(&config).await;
assert_eq!(check.status, CheckStatus::Warning);
assert_eq!(
check.summary,
"background server socket is stale or unreachable"
);
assert!(
check
.details
.contains(&"status: stale or unreachable".to_string())
);
assert!(
check
.details
.iter()
.any(|detail| detail.starts_with("app-server version: unavailable ("))
);
}
#[tokio::test]
async fn configured_updates_and_missing_updater_record_are_visible() {
let temp = tempfile::tempdir().expect("tempdir");
let state_dir = temp.path().join(STATE_DIR_NAME);
std::fs::create_dir(&state_dir).expect("state dir");
std::fs::write(
state_dir.join(SETTINGS_FILE_NAME),
r#"{"updater":{"autoUpdateEnabled":false,"updateIntervalMinutes":90}}"#,
)
.expect("settings");
let config = test_config(temp.path().to_path_buf()).await;
let check = background_server_check(&config).await;
let details = check
.details
.iter()
.filter(|detail| {
detail.starts_with("automatic updates:")
|| detail.starts_with("update interval:")
|| detail.starts_with("update-loop pid file:")
|| detail.starts_with("dedicated")
})
.map(|detail| {
detail
.replace(&temp.path().display().to_string(), "AKODE_HOME")
.replace('\\', "/")
})
.collect::<Vec<_>>()
.join("\n");
insta::assert_snapshot!("configured_updater", details);
}
#[test]
fn invalid_settings_are_not_reported_as_effective() {
let temp = tempfile::tempdir().expect("tempdir");
let path = temp.path().join(SETTINGS_FILE_NAME);
for contents in [
r#"{"updater":{"autoUpdateEnabled":"no"}}"#,
r#"{"updater":{"updateIntervalMinutes":0}}"#,
] {
std::fs::write(&path, contents).expect("settings");
let mut details = Vec::new();
push_configured_updater(&mut details, &path);
insta::allow_duplicates! {
insta::assert_snapshot!(details.join("\n"), @"configured updater settings: unreadable or invalid");
}
}
}
}

View File

@@ -0,0 +1,314 @@
use std::cmp::Reverse;
use std::env;
use std::fs;
use std::io;
use std::io::Read;
use std::path::Path;
use std::path::PathBuf;
use std::time::SystemTime;
use chrono::DateTime;
use chrono::FixedOffset;
use chrono::Utc;
use super::CheckStatus;
use super::DoctorCheck;
#[cfg(target_os = "macos")]
mod macos_security;
pub(super) mod platform;
#[cfg(any(target_os = "windows", test))]
mod windows_security;
const MAX_DIRECTORY_ENTRIES: usize = 256;
const MAX_LOG_FILES: usize = 64;
const MAX_SESSION_LOG_FILES: usize = 8;
const MAX_LOG_SEGMENT_BYTES: u64 = 10 * 1024 * 1024;
const HANDSHAKE_CHECK_ID: &str = "desktop.app_server.handshake";
pub(super) struct DesktopDiagnostics {
pub(super) checks: Vec<DoctorCheck>,
}
struct DesktopLog {
path: PathBuf,
session_id: String,
process_id: u32,
modified: SystemTime,
}
struct HandshakeEvent {
timestamp: DateTime<FixedOffset>,
outcome: HandshakeOutcome,
websocket: bool,
}
enum HandshakeOutcome {
Success,
Failure,
}
enum DesktopLogEvent {
ConnectionContext { local_websocket: bool },
Handshake(HandshakeEvent),
}
pub(super) async fn collect() -> Option<DesktopDiagnostics> {
let application = match platform::installed_app().await {
Ok(Some(application)) => application,
Ok(None) => return None,
Err(_) => {
return Some(DesktopDiagnostics {
checks: vec![
unavailable(
"desktop.app.version",
"the desktop application installation could not be inspected",
),
#[cfg(target_os = "windows")]
windows_security::collect().await,
],
});
}
};
let directory = desktop_log_root(application.identity);
let (running, handshake) = match &directory {
Some(root) => inspect_desktop_session(
&root.join(Utc::now().format("%Y/%m/%d").to_string()),
|pid| platform::application_running(&application, pid),
),
None => (false, stopped_desktop_check()),
};
let log_directory = directory
.as_deref()
.map_or_else(|| "unavailable".to_string(), redacted_path);
let application_check = platform::desktop_check(
"desktop.app.version",
CheckStatus::Ok,
"the desktop application is installed",
)
.detail(format!("version: {}", application.version))
.detail(format!("running: {running}"))
.detail(format!("log directory: {log_directory}"));
Some(DesktopDiagnostics {
checks: vec![
application_check,
handshake,
#[cfg(target_os = "macos")]
macos_security::collect(&application.bundle).await,
#[cfg(target_os = "windows")]
windows_security::collect().await,
],
})
}
pub(super) fn inspect_desktop_session(
directory: &Path,
application_running: impl Fn(u32) -> bool,
) -> (bool, DoctorCheck) {
let logs = discover_desktop_logs(directory);
let Some(session) = logs.iter().find(|log| application_running(log.process_id)) else {
return (false, stopped_desktop_check());
};
let check = latest_session_handshake(&logs, &session.session_id).map_or_else(
|| {
platform::desktop_check(
HANDSHAKE_CHECK_ID,
CheckStatus::Ok,
"no desktop app-server handshake was recorded",
)
},
|event| event.outcome.into_check(),
);
(true, check)
}
fn desktop_log_root(identity: &str) -> Option<PathBuf> {
let root = match env::consts::OS {
"macos" => PathBuf::from(env::var_os("HOME")?)
.join("Library/Logs")
.join(identity),
"windows" => {
let local = env::var_os("LOCALAPPDATA").map(PathBuf::from).or_else(|| {
env::var_os("USERPROFILE").map(|home| PathBuf::from(home).join("AppData/Local"))
})?;
local.join("Codex/Logs")
}
_ => return None,
};
Some(root)
}
fn discover_desktop_logs(directory: &Path) -> Vec<DesktopLog> {
let Ok(entries) = fs::read_dir(directory) else {
return Vec::new();
};
let mut logs = entries
.take(MAX_DIRECTORY_ENTRIES)
.filter_map(Result::ok)
.filter_map(DesktopLog::from_entry)
.collect::<Vec<_>>();
logs.sort_unstable_by_key(|log| Reverse(log.modified));
logs.truncate(MAX_LOG_FILES);
logs
}
fn latest_session_handshake(logs: &[DesktopLog], session_id: &str) -> Option<HandshakeEvent> {
let mut latest: Option<HandshakeEvent> = None;
for log in logs
.iter()
.filter(|log| log.session_id == session_id)
.take(MAX_SESSION_LOG_FILES)
{
let Ok(contents) = read_log_segment(&log.path) else {
continue;
};
let mut local_websocket = false;
for line in String::from_utf8_lossy(&contents).lines() {
match DesktopLogEvent::parse(line) {
Some(DesktopLogEvent::ConnectionContext {
local_websocket: local,
}) => {
local_websocket = local;
}
Some(DesktopLogEvent::Handshake(event))
if (!event.websocket || local_websocket)
&& latest
.as_ref()
.is_none_or(|current| event.timestamp >= current.timestamp) =>
{
latest = Some(event);
}
_ => {}
}
}
}
latest
}
impl DesktopLog {
fn from_entry(entry: fs::DirEntry) -> Option<Self> {
let metadata = entry.metadata().ok()?;
if !metadata.is_file() {
return None;
}
let name = entry.file_name();
let name = name
.to_str()?
.strip_prefix("codex-desktop-")?
.strip_suffix(".log")?;
let (session_and_pid, _) = name.split_once("-t")?;
let (session_id, process_id) = session_and_pid.rsplit_once('-')?;
Some(Self {
path: entry.path(),
session_id: session_id.to_string(),
process_id: process_id.parse().ok().filter(|pid| *pid > 0)?,
modified: metadata.modified().ok()?,
})
}
}
fn read_log_segment(path: &Path) -> io::Result<Vec<u8>> {
let mut contents = Vec::new();
fs::File::open(path)?
.take(MAX_LOG_SEGMENT_BYTES)
.read_to_end(&mut contents)?;
Ok(contents)
}
impl DesktopLogEvent {
fn parse(line: &str) -> Option<Self> {
let (timestamp, line) = line.split_once(' ')?;
let timestamp = DateTime::parse_from_rfc3339(timestamp).ok()?;
let (_, message) = line.split_once(" [AppServerConnection] ")?;
if let Some(fields) = message
.strip_prefix("Starting app-server connection ")
.or_else(|| message.strip_prefix("app_server_connection.state_changed "))
{
return Some(Self::ConnectionContext {
local_websocket: log_field(fields, "hostId") == Some("local")
&& log_field(fields, "transport") == Some("websocket"),
});
}
let fields = message.strip_prefix("initialize_handshake_result ")?;
let outcome = match log_field(fields, "outcome")? {
"success" => HandshakeOutcome::Success,
"failure" => HandshakeOutcome::Failure,
_ => return None,
};
let websocket = match log_field(fields, "transportKind")? {
"stdio" => false,
"websocket" => true,
_ => return None,
};
Some(Self::Handshake(HandshakeEvent {
timestamp,
outcome,
websocket,
}))
}
}
impl HandshakeOutcome {
fn into_check(self) -> DoctorCheck {
let (status, summary) = match self {
Self::Success => (
CheckStatus::Ok,
"the desktop app-server initialized successfully",
),
Self::Failure => (
CheckStatus::Fail,
"the desktop app-server failed to initialize",
),
};
platform::desktop_check(HANDSHAKE_CHECK_ID, status, summary)
}
}
fn log_field<'a>(fields: &'a str, name: &str) -> Option<&'a str> {
fields.split_whitespace().rev().find_map(|field| {
let (key, value) = field.split_once('=')?;
(key == name).then_some(value)
})
}
fn stopped_desktop_check() -> DoctorCheck {
platform::desktop_check(
HANDSHAKE_CHECK_ID,
CheckStatus::Ok,
"the desktop application is not running",
)
}
fn unavailable(id: &'static str, summary: &'static str) -> DoctorCheck {
platform::desktop_check(id, CheckStatus::Warning, summary)
.remediation("restore desktop diagnostic access and rerun akode doctor")
}
fn redacted_path(path: &Path) -> String {
for variable in ["HOME", "USERPROFILE"] {
if let Some(home) = env::var_os(variable)
&& let Ok(relative) = path.strip_prefix(Path::new(&home))
{
return Path::new("$HOME").join(relative).display().to_string();
}
}
path.file_name()
.unwrap_or(path.as_os_str())
.to_string_lossy()
.into_owned()
}

View File

@@ -0,0 +1,236 @@
use super::super::CheckStatus;
use super::super::DoctorCheck;
use super::platform::desktop_check;
use std::io;
use std::path::Path;
use std::process::Output;
use std::process::Stdio;
use std::time::Duration;
use tokio::io::AsyncRead;
use tokio::io::AsyncReadExt;
use tokio::process::Command;
use tokio::time::timeout;
const PROBE_TIMEOUT: Duration = Duration::from_secs(10);
const MAX_OUTPUT_BYTES: usize = 256 * 1024;
const SECURITY_LOG_PREDICATE: &str = concat!(
"(process == 'syspolicyd' OR process == 'AppleSystemPolicy' ",
"OR process BEGINSWITH 'XProtect' OR subsystem BEGINSWITH 'com.apple.syspolicy' ",
"OR subsystem CONTAINS[c] 'XProtect' ",
"OR subsystem == 'com.apple.security.assessment') AND ",
"(eventMessage CONTAINS[c] 'codex' OR eventMessage CONTAINS[c] 'chatgpt' ",
"OR eventMessage CONTAINS[c] '.plugin-appserver' ",
"OR eventMessage CONTAINS[c] '100024' OR eventMessage CONTAINS[c] 'EMFILE' ",
"OR eventMessage CONTAINS[c] 'ENFILE' ",
"OR eventMessage CONTAINS[c] 'too many open files' ",
"OR eventMessage CONTAINS[c] 'Unexpected Xprotect assessment')"
);
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
enum Evidence {
Clear,
Audit,
Exhausted,
Blocked,
Malware,
Unavailable,
}
pub(super) async fn collect(bundle: &Path) -> DoctorCheck {
let (gatekeeper, events) = tokio::join!(inspect_gatekeeper(bundle), inspect_security_events());
enforcement_check(gatekeeper, events)
}
async fn inspect_gatekeeper(bundle: &Path) -> Evidence {
let mut command = Command::new("/usr/sbin/spctl");
command
.args(["--assess", "--type", "execute", "--verbose=2"])
.arg(bundle);
classify_gatekeeper(run_command(&mut command).await.as_ref())
}
fn classify_gatekeeper(output: Option<&Output>) -> Evidence {
let Some(output) = output.filter(|output| !is_truncated(output)) else {
return Evidence::Unavailable;
};
if output.status.success() {
return Evidence::Clear;
}
let error = String::from_utf8_lossy(&output.stderr).to_ascii_lowercase();
if error.contains("rejected") || error.contains("no usable signature") {
Evidence::Blocked
} else {
Evidence::Unavailable
}
}
async fn inspect_security_events() -> Evidence {
let mut command = Command::new("/usr/bin/log");
command.args([
"show",
"--last",
"30m",
"--info",
"--style",
"compact",
"--predicate",
SECURITY_LOG_PREDICATE,
]);
let Some(output) = run_command(&mut command)
.await
.filter(|output| output.status.success())
else {
return Evidence::Unavailable;
};
let evidence = classify_security_events(&String::from_utf8_lossy(&output.stdout));
if is_truncated(&output) && evidence < Evidence::Exhausted {
Evidence::Unavailable
} else {
evidence
}
}
fn classify_security_events(output: &str) -> Evidence {
let mut evidence = Evidence::Clear;
for line in output.lines().map(str::to_ascii_lowercase) {
let contains = |values: &[&str]| values.iter().any(|value| line.contains(value));
if !contains(&[
"com.openai.codex",
"codex.app",
"chatgpt.app",
".plugin-appserver",
"akode-command-runner",
]) || contains(&["not blocked", "not denied"])
{
continue;
}
let event = if contains(&["100024", "emfile", "enfile", "too many open files"]) {
Evidence::Exhausted
} else if contains(&["would block", "would deny"]) {
Evidence::Audit
} else if contains(&[
"xp_malware_detected",
"xp_malware_remediated",
"malware detected",
"malware blocked",
"malware removed",
"remediat",
]) {
Evidence::Malware
} else if contains(&[
"blocked",
"denied",
"rejected",
"notarization failed",
"signature invalid",
"execution prevented",
"unexpected xprotect assessment",
"damaged and",
]) {
Evidence::Blocked
} else if contains(&["audit"]) {
Evidence::Audit
} else {
Evidence::Clear
};
evidence = evidence.max(event);
}
evidence
}
fn enforcement_check(gatekeeper: Evidence, events: Evidence) -> DoctorCheck {
let id = "desktop.security.enforcement";
let (status, summary, remedy) = if events == Evidence::Malware {
(
CheckStatus::Fail,
"macos XProtect blocked or remediated the desktop application",
"collect the XProtect detection and ask your security administrator to review the official aKode installation",
)
} else if gatekeeper == Evidence::Blocked {
(
CheckStatus::Fail,
"macos gatekeeper rejected the desktop application",
"ask your security administrator to review the application policy",
)
} else if events == Evidence::Blocked {
(
CheckStatus::Fail,
"a recent macos security event blocked the desktop application",
"ask your security administrator to review the matching prevention event",
)
} else if events == Evidence::Exhausted {
(
CheckStatus::Warning,
"macos system-policy diagnostics indicate file descriptor exhaustion",
"restart your Mac, retry aKode once, and contact support if the problem returns",
)
} else if events == Evidence::Audit {
(
CheckStatus::Warning,
"recent desktop security events are audit-only",
"ask your security administrator to verify the application policy",
)
} else if gatekeeper == Evidence::Unavailable {
(
CheckStatus::Warning,
"the desktop security assessment was unavailable",
"check access to macos gatekeeper diagnostics",
)
} else if events == Evidence::Unavailable {
(
CheckStatus::Warning,
"recent macos security enforcement history was unavailable",
"check access to macos unified security logs and rerun akode doctor",
)
} else {
return desktop_check(
id,
CheckStatus::Ok,
"the desktop application passed available macos security assessments",
)
.detail("gatekeeper: accepted");
};
desktop_check(id, status, summary).remediation(remedy)
}
fn is_truncated(output: &Output) -> bool {
output.stdout.len() > MAX_OUTPUT_BYTES || output.stderr.len() > MAX_OUTPUT_BYTES
}
async fn run_command(command: &mut Command) -> Option<Output> {
command
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.kill_on_drop(true);
let mut child = command.spawn().ok()?;
let (stdout, stderr) = (child.stdout.take()?, child.stderr.take()?);
timeout(PROBE_TIMEOUT, async {
let (stdout, stderr, status) =
tokio::join!(read_bounded(stdout), read_bounded(stderr), child.wait());
Some(Output {
status: status.ok()?,
stdout: stdout.ok()?,
stderr: stderr.ok()?,
})
})
.await
.ok()
.flatten()
}
async fn read_bounded<R: AsyncRead + Unpin>(mut reader: R) -> io::Result<Vec<u8>> {
let mut bytes = Vec::new();
(&mut reader)
.take(MAX_OUTPUT_BYTES as u64 + 1)
.read_to_end(&mut bytes)
.await?;
if bytes.len() > MAX_OUTPUT_BYTES {
tokio::io::copy(&mut reader, &mut tokio::io::sink()).await?;
}
Ok(bytes)
}
#[cfg(test)]
#[path = "macos_security_tests.rs"]
mod tests;

View File

@@ -0,0 +1,67 @@
use super::CheckStatus;
use super::Evidence;
use super::classify_gatekeeper;
use super::classify_security_events;
use super::enforcement_check;
use pretty_assertions::assert_eq;
use std::os::unix::process::ExitStatusExt;
use std::process::ExitStatus;
use std::process::Output;
#[test]
fn only_matching_enforced_apple_security_events_are_failures() {
for (event, expected) in [
("denied com.openai.codex", Evidence::Blocked),
(
"denied /Applications/Codex.app/Contents/MacOS/Codex",
Evidence::Blocked,
),
("malware detected ChatGPT.app", Evidence::Malware),
("audit token blocked ChatGPT.app", Evidence::Blocked),
(
"audit token XP_MALWARE_DETECTED ChatGPT.app",
Evidence::Malware,
),
("XP_MALWARE_REMEDIATED ChatGPT.app", Evidence::Malware),
("denied .plugin-appserver", Evidence::Blocked),
("audit would block ChatGPT.app", Evidence::Audit),
("OSStatus 100024 ChatGPT.app", Evidence::Exhausted),
("not blocked ChatGPT.app", Evidence::Clear),
("denied EMFILE com.example.other", Evidence::Clear),
("EMFILE\nmalware detected ChatGPT.app", Evidence::Malware),
] {
assert_eq!(classify_security_events(event), expected, "{event}");
}
}
#[test]
fn gatekeeper_failures_require_actionable_security_evidence() {
for (message, expected) in [
("ChatGPT.app: rejected", Evidence::Blocked),
("operation not permitted", Evidence::Unavailable),
] {
let output = Output {
status: ExitStatus::from_raw(1 << 8),
stdout: Vec::new(),
stderr: message.as_bytes().to_vec(),
};
assert_eq!(classify_gatekeeper(Some(&output)), expected);
}
}
#[test]
fn exhaustion_and_unavailable_history_have_actionable_warnings() {
for (events, remedy) in [
(Evidence::Exhausted, "restart"),
(Evidence::Unavailable, "unified security logs"),
] {
let check = enforcement_check(Evidence::Clear, events);
assert_eq!(check.status, CheckStatus::Warning);
assert!(
check
.remediation
.as_deref()
.is_some_and(|value| value.contains(remedy))
);
}
}

View File

@@ -0,0 +1,275 @@
#[cfg(target_os = "macos")]
use std::ffi::CStr;
#[cfg(target_os = "macos")]
use std::ffi::OsStr;
#[cfg(target_os = "macos")]
use std::fs;
#[cfg(target_os = "macos")]
use std::os::unix::ffi::OsStrExt;
#[cfg(target_os = "windows")]
use std::os::windows::io::AsRawHandle;
#[cfg(target_os = "windows")]
use std::os::windows::io::FromRawHandle;
#[cfg(target_os = "windows")]
use std::os::windows::io::OwnedHandle;
#[cfg(target_os = "macos")]
use std::path::Path;
#[cfg(target_os = "macos")]
use std::path::PathBuf;
#[cfg(target_os = "macos")]
use std::process::Stdio;
#[cfg(target_os = "macos")]
use std::time::Duration;
#[cfg(target_os = "macos")]
use serde_json::Value;
#[cfg(target_os = "macos")]
use tokio::process::Command;
#[cfg(target_os = "macos")]
use tokio::time::timeout;
#[cfg(target_os = "windows")]
use windows_sys::Win32::Foundation::ERROR_INSUFFICIENT_BUFFER;
#[cfg(target_os = "windows")]
use windows_sys::Win32::Foundation::ERROR_SUCCESS;
#[cfg(target_os = "windows")]
use windows_sys::Win32::Storage::Packaging::Appx::FindPackagesByPackageFamily;
#[cfg(target_os = "windows")]
use windows_sys::Win32::Storage::Packaging::Appx::GetPackageFamilyName;
#[cfg(target_os = "windows")]
use windows_sys::Win32::Storage::Packaging::Appx::PACKAGE_FILTER_HEAD;
#[cfg(target_os = "windows")]
use windows_sys::Win32::System::Threading::OpenProcess;
#[cfg(target_os = "windows")]
use windows_sys::Win32::System::Threading::PROCESS_QUERY_LIMITED_INFORMATION;
use super::super::CheckStatus;
use super::super::DoctorCheck;
pub(in crate::doctor) struct InstalledApp {
pub(in crate::doctor) identity: &'static str,
pub(in crate::doctor) version: String,
#[cfg(target_os = "windows")]
package_family: &'static str,
#[cfg(target_os = "macos")]
pub(in crate::doctor) bundle: PathBuf,
}
#[derive(Clone, Copy, Debug)]
pub(in crate::doctor) struct DiscoveryError;
pub(super) async fn installed_app() -> Result<Option<InstalledApp>, DiscoveryError> {
#[cfg(target_os = "windows")]
{
installed_windows_app()
}
#[cfg(target_os = "macos")]
{
installed_macos_app().await
}
#[cfg(not(any(target_os = "windows", target_os = "macos")))]
{
Ok(None)
}
}
#[cfg(target_os = "macos")]
pub(super) fn application_running(application: &InstalledApp, candidate_pid: u32) -> bool {
process_executable_path(candidate_pid)
.is_some_and(|path| path.starts_with(application.bundle.join("Contents/MacOS")))
}
#[cfg(target_os = "macos")]
fn process_executable_path(pid: u32) -> Option<PathBuf> {
let pid = i32::try_from(pid).ok()?;
let mut buffer = [0_u8; libc::PROC_PIDPATHINFO_MAXSIZE as usize];
let result =
unsafe { libc::proc_pidpath(pid, buffer.as_mut_ptr().cast(), buffer.len() as u32) };
if result <= 0 {
return None;
}
let executable = CStr::from_bytes_until_nul(&buffer).ok()?;
Some(PathBuf::from(OsStr::from_bytes(executable.to_bytes())))
}
#[cfg(target_os = "windows")]
pub(super) fn application_running(application: &InstalledApp, candidate_pid: u32) -> bool {
process_package_family(candidate_pid).as_deref() == Some(application.package_family)
}
#[cfg(target_os = "windows")]
fn process_package_family(pid: u32) -> Option<String> {
let handle = unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid) };
if handle.is_null() {
return None;
}
let process = unsafe { OwnedHandle::from_raw_handle(handle) };
let mut family_length = 0;
let result = unsafe {
GetPackageFamilyName(
process.as_raw_handle(),
&mut family_length,
std::ptr::null_mut(),
)
};
if result != ERROR_INSUFFICIENT_BUFFER || family_length == 0 {
return None;
}
let mut family = vec![0_u16; family_length as usize];
let result = unsafe {
GetPackageFamilyName(
process.as_raw_handle(),
&mut family_length,
family.as_mut_ptr(),
)
};
if result != ERROR_SUCCESS {
return None;
}
let end = family.iter().position(|value| *value == 0)?;
String::from_utf16(&family[..end]).ok()
}
#[cfg(not(any(target_os = "windows", target_os = "macos")))]
pub(super) fn application_running(_application: &InstalledApp, _candidate_pid: u32) -> bool {
false
}
pub(super) fn desktop_check(
id: impl Into<String>,
status: CheckStatus,
summary: impl Into<String>,
) -> DoctorCheck {
DoctorCheck::new(id, "desktop", status, summary)
}
#[cfg(target_os = "windows")]
fn installed_windows_app() -> Result<Option<InstalledApp>, DiscoveryError> {
const PACKAGE_FAMILY: &str = "OpenAI.Codex_2p2nqsd0c76g0";
let family = PACKAGE_FAMILY
.encode_utf16()
.chain(std::iter::once(0))
.collect::<Vec<_>>();
let mut count = 0;
let mut length = 0;
let result = unsafe {
FindPackagesByPackageFamily(
family.as_ptr(),
PACKAGE_FILTER_HEAD,
&mut count,
std::ptr::null_mut(),
&mut length,
std::ptr::null_mut(),
std::ptr::null_mut(),
)
};
if result == ERROR_SUCCESS && count == 0 {
return Ok(None);
}
if result != ERROR_INSUFFICIENT_BUFFER {
return Err(DiscoveryError);
}
let mut names = vec![std::ptr::null_mut(); count as usize];
let mut buffer = vec![0_u16; length as usize];
let result = unsafe {
FindPackagesByPackageFamily(
family.as_ptr(),
PACKAGE_FILTER_HEAD,
&mut count,
names.as_mut_ptr(),
&mut length,
buffer.as_mut_ptr(),
std::ptr::null_mut(),
)
};
if result != ERROR_SUCCESS {
return Err(DiscoveryError);
}
if count == 0 {
return Ok(None);
}
let end = buffer
.iter()
.position(|value| *value == 0)
.ok_or(DiscoveryError)?;
let package = String::from_utf16(&buffer[..end]).map_err(|_| DiscoveryError)?;
let version = package
.strip_prefix("OpenAI.Codex_")
.and_then(|name| name.split('_').next())
.filter(|version| {
version
.split('.')
.all(|part| !part.is_empty() && part.bytes().all(|digit| digit.is_ascii_digit()))
})
.ok_or(DiscoveryError)?;
Ok(Some(InstalledApp {
identity: "OpenAI.Codex",
version: version.to_string(),
package_family: PACKAGE_FAMILY,
}))
}
#[cfg(target_os = "macos")]
async fn installed_macos_app() -> Result<Option<InstalledApp>, DiscoveryError> {
let applications = std::iter::once(PathBuf::from("/Applications"))
.chain(std::env::var_os("HOME").map(|home| PathBuf::from(home).join("Applications")))
.flat_map(|directory| {
["ChatGPT.app", "Codex.app"]
.into_iter()
.map(move |application| directory.join(application))
});
for bundle in applications {
match fs::metadata(&bundle) {
Ok(metadata) if metadata.is_dir() => {}
Ok(_) => continue,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue,
Err(_) => return Err(DiscoveryError),
}
if let Some(application) = inspect_macos_bundle(&bundle).await? {
return Ok(Some(application));
}
}
Ok(None)
}
#[cfg(target_os = "macos")]
pub(in crate::doctor) async fn inspect_macos_bundle(
bundle: &Path,
) -> Result<Option<InstalledApp>, DiscoveryError> {
let mut command = Command::new("/usr/bin/plutil");
command
.args(["-convert", "json", "-o", "-"])
.arg(bundle.join("Contents/Info.plist"))
.stdin(Stdio::null())
.stderr(Stdio::null())
.kill_on_drop(true);
let output = timeout(Duration::from_secs(5), command.output())
.await
.map_err(|_| DiscoveryError)?
.map_err(|_| DiscoveryError)?;
if !output.status.success() || output.stdout.len() > 64 * 1024 {
return Err(DiscoveryError);
}
let metadata: Value = serde_json::from_slice(&output.stdout).map_err(|_| DiscoveryError)?;
if metadata.get("CFBundleIdentifier").and_then(Value::as_str) != Some("com.openai.codex") {
return Ok(None);
}
let version = metadata
.get("CFBundleShortVersionString")
.or_else(|| metadata.get("CFBundleVersion"))
.and_then(Value::as_str)
.ok_or(DiscoveryError)?;
Ok(Some(InstalledApp {
identity: "com.openai.codex",
version: version.to_string(),
bundle: bundle.to_path_buf(),
}))
}

View File

@@ -0,0 +1,232 @@
use std::env;
use std::path::Path;
use std::process::Stdio;
use std::time::Duration;
use tokio::io::AsyncReadExt;
use tokio::process::Command;
use tokio::time::timeout;
use super::super::CheckStatus;
use super::super::DoctorCheck;
use super::platform::desktop_check;
const MAX_EVENTS_PER_CHANNEL: usize = 256;
const MAX_RENDERED_EVENTS: usize = 16;
const MAX_EVENT_OUTPUT_BYTES: usize = 2 * 1024 * 1024;
type Channel = (&'static str, &'static str, &'static [u32]);
type Evidence = (CheckStatus, String);
const CHANNELS: [Channel; 5] = [
(
"microsoft_defender",
"Microsoft-Windows-Windows Defender/Operational",
&[
1006, 1007, 1116, 1117, 1121, 1122, 1123, 1124, 1125, 1126, 1127, 1128,
],
),
(
"applocker",
"Microsoft-Windows-AppLocker/EXE and DLL",
&[8003, 8004],
),
(
"applocker",
"Microsoft-Windows-AppLocker/Packaged app-Execution",
&[8021, 8022],
),
(
"applocker",
"Microsoft-Windows-AppLocker/MSI and Script",
&[8006, 8007],
),
(
"windows_app_control",
"Microsoft-Windows-CodeIntegrity/Operational",
&[3076, 3077],
),
];
pub(super) async fn collect() -> DoctorCheck {
let Some(system_root) = env::var_os("SystemRoot") else {
return classify(&[]);
};
let wevtutil = Path::new(&system_root).join("System32/wevtutil.exe");
let mut channels = Vec::with_capacity(CHANNELS.len());
for pair in CHANNELS.chunks(/*chunk_size*/ 2) {
let first = query_channel(&wevtutil, pair[0]);
if let Some(second) = pair.get(/*index*/ 1) {
let (first, second) = tokio::join!(first, query_channel(&wevtutil, *second));
channels.extend([first, second]);
} else {
channels.push(first.await);
}
}
classify(&channels)
}
async fn query_channel(wevtutil: &Path, channel: Channel) -> Option<Vec<Evidence>> {
let events = channel
.2
.iter()
.map(|id| format!("EventID={id}"))
.collect::<Vec<_>>()
.join(" or ");
let mut child = Command::from(akode_utils_process::background_command(wevtutil))
.args(["qe", channel.1])
.arg(format!(
"/q:*[System[({events}) and TimeCreated[timediff(@SystemTime) <= 604800000]]]"
))
.arg(format!("/c:{MAX_EVENTS_PER_CHANNEL}"))
.args(["/rd:true", "/f:xml"])
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.kill_on_drop(true)
.spawn()
.ok()?;
let mut output = Vec::new();
let status = timeout(Duration::from_secs(10), async {
let mut reader = child.stdout.take()?.take(MAX_EVENT_OUTPUT_BYTES as u64 + 1);
reader.read_to_end(&mut output).await.ok()?;
if output.len() > MAX_EVENT_OUTPUT_BYTES {
return None;
}
child.wait().await.ok()
})
.await
.ok()
.flatten()?;
status
.success()
.then(|| parse_events(&String::from_utf8_lossy(&output), channel))
}
fn parse_events(xml: &str, (source, _, ids): Channel) -> Vec<Evidence> {
xml.split("</Event>")
.take(MAX_EVENTS_PER_CHANNEL)
.filter_map(|event| {
let id = element(event, "EventID")?.parse().ok()?;
if !ids.contains(&id) {
return None;
}
let target = event
.split("<Data")
.skip(/*n*/ 1)
.filter_map(|data| data.split_once('>')?.1.split_once("</Data>").map(|v| v.0))
.chain(
["FilePath", "FileName", "Image", "PackageName", "PackageFamilyName"]
.into_iter()
.filter_map(|name| element(event, name)),
)
.find_map(event_target)?;
let timestamp = event.split_once("SystemTime=\"")?.1.split_once('"')?.0;
let (status, action) = match id {
1121 | 1123 | 1126 | 1127 | 8004 | 8007 | 8022 | 3077 => {
(CheckStatus::Fail, "blocked")
}
1122 | 1124 | 1125 | 1128 | 8003 | 8006 | 8021 | 3076 => {
(CheckStatus::Warning, "audited")
}
1006 | 1116 => (CheckStatus::Warning, "detected"),
1007 | 1117 => defender_action(event),
_ => return None,
};
Some((
status,
format!(
"source: {source}; event: {id}; target: {target}; action: {action}; time: {timestamp}"
),
))
})
.collect()
}
fn event_target(value: &str) -> Option<&'static str> {
let value = value.to_ascii_lowercase();
let parts = value.split(['\\', '/']).map(str::trim).collect::<Vec<_>>();
let name = *parts.last()?;
let package = parts.iter().any(|part| part.starts_with("openai.codex_"));
let trusted = package || parts.windows(2).any(|pair| pair == ["openai", "codex"]);
match name {
"akode-windows-sandbox-setup.exe" => Some("sandbox_setup"),
"akode-command-runner.exe" => Some("command_runner"),
"akode.exe" => Some("codex"),
"codex-desktop.exe" => Some("codex_desktop"),
"chatgpt.exe" | "electron.exe" if trusted => Some("codex_desktop"),
"rg.exe" if trusted => Some("ripgrep"),
_ if package => Some("codex_desktop_package"),
_ => None,
}
}
fn defender_action(event: &str) -> (CheckStatus, &'static str) {
let action = [
"Action Name",
"ActionName",
"Action",
"Action ID",
"ActionID",
]
.into_iter()
.find_map(|name| data_value(event, name))
.or_else(|| element(event, "ActionName"))
.unwrap_or_default()
.to_ascii_lowercase();
match action.as_str() {
"quarantine" | "2" => (CheckStatus::Fail, "quarantined"),
"clean" | "remove" | "block" | "1" | "3" | "10" => (CheckStatus::Fail, "blocked"),
"allow" | "ignore" | "none" | "no action" | "user defined" | "6" | "8" | "9" | "11" => {
(CheckStatus::Ok, "allowed")
}
_ => (CheckStatus::Warning, "detected"),
}
}
fn classify(channels: &[Option<Vec<Evidence>>]) -> DoctorCheck {
let visible = channels.iter().any(Option::is_some);
let mut status = if visible {
CheckStatus::Ok
} else {
CheckStatus::Warning
};
let mut details = Vec::new();
for (event_status, detail) in channels.iter().flatten().flatten() {
status = status.max(*event_status);
if details.len() < MAX_RENDERED_EVENTS {
details.push(detail.clone());
}
}
let summary = match (status, visible) {
(CheckStatus::Ok, _) if channels.contains(&None) => "security event coverage is incomplete",
(CheckStatus::Ok, _) => "no locally visible recent aKode security enforcement was found",
(CheckStatus::Warning, false) => "security event channels could not be inspected",
(CheckStatus::Warning, true) => "recent aKode security audit or detection requires review",
(CheckStatus::Fail, _) => "endpoint security blocked or quarantined an aKode executable",
};
let mut check = desktop_check("desktop.security.enforcement", status, summary).details(details);
if status != CheckStatus::Ok {
check = check.remediation(
"ask your organization's security administrator to review endpoint security events and the approved aKode application policy",
);
}
check
}
fn element<'a>(xml: &'a str, name: &str) -> Option<&'a str> {
let body = xml.split_once(&format!("<{name}"))?.1.split_once('>')?.1;
Some(body.split_once(&format!("</{name}>"))?.0.trim())
}
fn data_value<'a>(xml: &'a str, name: &str) -> Option<&'a str> {
let body = xml
.split_once(&format!("Name=\"{name}\""))?
.1
.split_once('>')?
.1;
Some(body.split_once("</Data>")?.0.trim())
}
#[cfg(test)]
#[path = "windows_security_tests.rs"]
mod tests;

View File

@@ -0,0 +1,85 @@
use pretty_assertions::assert_eq;
use super::CHANNELS;
use super::CheckStatus;
use super::MAX_RENDERED_EVENTS;
use super::classify;
use super::parse_events;
#[cfg(not(target_os = "windows"))]
#[tokio::test]
async fn an_unavailable_reader_is_not_reported_as_clean() {
assert_eq!(super::collect().await.status, CheckStatus::Warning);
}
#[test]
fn every_source_distinguishes_audits_from_blocks() {
for (channel, audit, block) in [
(0, 1122, 1121),
(0, 1125, 1126),
(1, 8003, 8004),
(2, 8021, 8022),
(3, 8006, 8007),
(4, 3076, 3077),
] {
for (id, expected) in [(audit, CheckStatus::Warning), (block, CheckStatus::Fail)] {
let events = parse_events(&fixture(id, "akode.exe", &[]), CHANNELS[channel]);
assert_eq!(events[0].0, expected, "misclassified event {id}");
}
}
}
#[test]
fn defender_distinguishes_detection_and_remediation() {
for (id, action, expected) in [
(1116, "", CheckStatus::Warning),
(1117, "Allow", CheckStatus::Ok),
(1117, "Quarantine", CheckStatus::Fail),
(1117, "Remove", CheckStatus::Fail),
] {
let events = parse_events(
&fixture(id, "akode.exe", &[("Action Name", action)]),
CHANNELS[0],
);
assert_eq!(classify(&[Some(events)]).status, expected);
}
}
#[test]
fn only_trusted_codex_executables_are_reported() {
for (path, expected) in [
("akode.exe", true),
(r"OpenAI.Codex_2p2nqsd0c76g0\ChatGPT.exe", true),
("evil-codex.exe", false),
(r"C:\Other\ChatGPT.exe", false),
(r"OpenAI.CodexEvil_1\ChatGPT.exe", false),
] {
let events = parse_events(&fixture(/*id*/ 1121, path, &[]), CHANNELS[0]);
assert_eq!(!events.is_empty(), expected, "misclassified {path}");
}
}
#[test]
fn evidence_is_bounded_redacted_and_correctly_classified() {
assert_eq!(classify(&[None]).status, CheckStatus::Warning);
assert_eq!(classify(&[Some(Vec::new()), None]).status, CheckStatus::Ok);
let audits = fixture(/*id*/ 1122, "akode.exe", &[]).repeat(MAX_RENDERED_EVENTS);
let secret = "private-customer-secret";
let block = fixture(/*id*/ 1121, "akode.exe", &[("User", secret)]);
let events = parse_events(&format!("{audits}{block}"), CHANNELS[0]);
let check = classify(&[Some(events)]);
assert_eq!(check.id, "desktop.security.enforcement");
assert_eq!(check.status, CheckStatus::Fail);
assert_eq!(check.details.len(), MAX_RENDERED_EVENTS);
assert!(!serde_json::to_string(&check).unwrap().contains(secret));
}
fn fixture(id: u32, path: &str, fields: &[(&str, &str)]) -> String {
let data = fields
.iter()
.map(|(name, value)| format!("<Data Name=\"{name}\">{value}</Data>"))
.collect::<String>();
format!(
"<Event><System><EventID>{id}</EventID><TimeCreated SystemTime=\"2026-01-01T00:00:00Z\"/></System><EventData><Data Name=\"Path\">{path}</Data>{data}</EventData></Event>"
)
}

View File

@@ -0,0 +1,97 @@
use std::fs;
use std::path::Path;
use pretty_assertions::assert_eq;
use super::CheckStatus;
use super::desktop::inspect_desktop_session;
const CURRENT_SESSION: &str = "12345678-1234-1234-1234-123456789abc";
const CURRENT_PROCESS: u32 = 12345;
#[test]
fn current_desktop_session_reports_the_latest_local_handshake() {
let directory = tempfile::tempdir().expect("temporary directory should be created");
write_log(
directory.path(),
concat!(
"2026-08-07T12:00:00.000Z error [AppServerConnection] initialize_handshake_result outcome=failure transportKind=stdio\n",
"2026-08-07T12:01:00.000Z info [AppServerConnection] Starting app-server connection hostId=local transport=websocket\n",
"2026-08-07T12:02:00.000Z info [AppServerConnection] initialize_handshake_result outcome=success transportKind=websocket\n",
"2026-08-07T12:03:00.000Z info [AppServerConnection] app_server_connection.state_changed hostId=remote transport=websocket\n",
"2026-08-07T12:04:00.000Z error [AppServerConnection] initialize_handshake_result outcome=failure transportKind=websocket\n",
),
);
let (running, check) = inspect_desktop_session(directory.path(), |pid| pid == CURRENT_PROCESS);
assert!(running);
assert_eq!(check.id, "desktop.app_server.handshake");
assert_eq!(check.status, CheckStatus::Ok);
assert_eq!(
check.summary,
"the desktop app-server initialized successfully"
);
}
#[test]
fn failed_handshake_does_not_expose_sensitive_log_fields() {
let directory = tempfile::tempdir().expect("temporary directory should be created");
write_log(
directory.path(),
"2026-08-07T12:00:00.000Z error [AppServerConnection] initialize_handshake_result errorMessage=\"desktop-secret outcome=success\" outcome=failure transportKind=stdio\n",
);
let (running, check) = inspect_desktop_session(directory.path(), |_| true);
assert!(running);
assert_eq!(check.status, CheckStatus::Fail);
assert_eq!(check.summary, "the desktop app-server failed to initialize");
assert!(
!serde_json::to_string(&check)
.unwrap()
.contains("desktop-secret")
);
}
#[test]
fn handshake_failure_in_the_middle_of_a_log_segment_is_detected() {
let directory = tempfile::tempdir().expect("temporary directory should be created");
let padding = "x".repeat(96 * 1024);
write_log(
directory.path(),
&format!(
"{padding}\n2026-08-07T12:00:00.000Z error [AppServerConnection] initialize_handshake_result outcome=failure transportKind=stdio\n{padding}"
),
);
let (running, check) = inspect_desktop_session(directory.path(), |_| true);
assert!(running);
assert_eq!(check.status, CheckStatus::Fail);
}
#[test]
fn stopped_desktop_does_not_report_a_failure() {
let directory = tempfile::tempdir().expect("temporary directory should be created");
write_log(
directory.path(),
"2026-08-07T12:00:00.000Z error [AppServerConnection] initialize_handshake_result outcome=failure transportKind=stdio\n",
);
let (running, check) = inspect_desktop_session(directory.path(), |_| false);
assert!(!running);
assert_eq!(check.status, CheckStatus::Ok);
assert_eq!(check.summary, "the desktop application is not running");
}
fn write_log(directory: &Path, contents: &str) {
fs::write(
directory.join(format!(
"codex-desktop-{CURRENT_SESSION}-{CURRENT_PROCESS}-t0-i0-120000-0.log"
)),
contents,
)
.expect("desktop log fixture should be created");
}

View File

@@ -0,0 +1,178 @@
use std::io;
use std::path::Path;
use akode_core::config::Config;
use super::CheckStatus;
use super::DoctorCheck;
use super::DoctorIssue;
use super::find_codex_home;
const GIB: u64 = 1024 * 1024 * 1024;
const FAIL_THRESHOLD: u64 = GIB;
const WARNING_THRESHOLD: u64 = 5 * GIB;
pub(super) fn check(config: Option<&Config>, cwd: &Path) -> DoctorCheck {
let home = config
.map(|config| config.codex_home.as_path().to_path_buf())
.or_else(|| find_codex_home().ok().map(Into::into))
.or_else(|| std::env::var_os("AKODE_HOME").map(Into::into));
check_with_paths(home.as_deref(), cwd, available_space)
}
fn check_with_paths(
home: Option<&Path>,
cwd: &Path,
measure: impl Fn(&Path) -> io::Result<u64>,
) -> DoctorCheck {
let home = home.and_then(|path| std::path::absolute(path).ok());
let mut check = DoctorCheck::new(
"system.disk",
"disk",
CheckStatus::Ok,
"sufficient free disk space",
)
.detail(format!(
"warning threshold: {}",
format_capacity(WARNING_THRESHOLD)
))
.detail(format!(
"failure threshold: {}",
format_capacity(FAIL_THRESHOLD)
));
let mut lowest = None;
for (label, path) in [("AKODE_HOME", home.as_deref()), ("worktree", Some(cwd))] {
let field = format!("{label} available");
let available = path
.and_then(|path| path.ancestors().find(|ancestor| ancestor.is_dir()))
.map(&measure)
.unwrap_or_else(|| Err(io::ErrorKind::NotFound.into()));
match available {
Ok(available) => {
let measured = format_capacity(available);
check = check.detail(format!("{field}: {measured}"));
lowest = Some(lowest.map_or(available, |lowest: u64| lowest.min(available)));
let status = match available {
0..FAIL_THRESHOLD => CheckStatus::Fail,
FAIL_THRESHOLD..WARNING_THRESHOLD => CheckStatus::Warning,
WARNING_THRESHOLD.. => CheckStatus::Ok,
};
if status != CheckStatus::Ok {
check.status = check.status.max(status);
check = check.issue(
DoctorIssue::new(status, format!("{label} has insufficient disk space"))
.measured(measured)
.expected(format!("at least {}", format_capacity(WARNING_THRESHOLD)))
.remedy("Free disk space or move the worktree to a larger volume.")
.field(field),
);
}
}
Err(error) => {
check.status = check.status.max(CheckStatus::Warning);
check = check
.detail(format!("{field}: unavailable ({:?})", error.kind()))
.issue(
DoctorIssue::new(
CheckStatus::Warning,
format!("disk space for {label} could not be checked"),
)
.measured(format!("{:?}", error.kind()))
.expected("readable filesystem capacity")
.remedy("Check filesystem access and available disk space.")
.field(field),
);
}
}
}
check.summary = match (check.status, lowest) {
(CheckStatus::Fail, Some(available)) => {
format!("critically low disk space ({})", format_capacity(available))
}
(CheckStatus::Warning, Some(available)) if available < WARNING_THRESHOLD => {
format!("low disk space ({})", format_capacity(available))
}
(CheckStatus::Warning, _) => "disk capacity could not be fully verified".to_string(),
(CheckStatus::Ok, Some(available)) => {
format!(
"sufficient free disk space ({})",
format_capacity(available)
)
}
(CheckStatus::Ok | CheckStatus::Fail, None) => {
"disk capacity could not be verified".to_string()
}
};
check
}
fn format_capacity(bytes: u64) -> String {
if bytes >= GIB {
format!("{:.1} GiB", bytes as f64 / GIB as f64)
} else {
format!("{:.1} MiB", bytes as f64 / (1024 * 1024) as f64)
}
}
#[cfg(unix)]
fn available_space(path: &Path) -> io::Result<u64> {
use std::ffi::CString;
use std::mem::MaybeUninit;
use std::os::unix::ffi::OsStrExt;
let path = CString::new(path.as_os_str().as_bytes())
.map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "path contains NUL"))?;
let mut stats = MaybeUninit::<libc::statvfs>::uninit();
if unsafe { libc::statvfs(path.as_ptr(), stats.as_mut_ptr()) } != 0 {
return Err(io::Error::last_os_error());
}
let stats = unsafe { stats.assume_init() };
if stats.f_files > 0 && stats.f_favail == 0 {
return Ok(0);
}
u64::try_from(u128::from(stats.f_bavail) * u128::from(stats.f_frsize))
.map_err(|_| io::Error::other("available disk space exceeds u64"))
}
#[cfg(windows)]
fn available_space(path: &Path) -> io::Result<u64> {
use std::os::windows::ffi::OsStrExt;
use windows_sys::Win32::Storage::FileSystem::GetDiskFreeSpaceExW;
let mut path = path.as_os_str().encode_wide().collect::<Vec<_>>();
if path.last() != Some(&u16::from(b'\\')) {
path.push(u16::from(b'\\'));
}
path.push(0);
let mut available = 0;
if unsafe {
GetDiskFreeSpaceExW(
path.as_ptr(),
&mut available,
std::ptr::null_mut(),
std::ptr::null_mut(),
)
} == 0
{
return Err(io::Error::last_os_error());
}
Ok(available)
}
#[cfg(not(any(unix, windows)))]
fn available_space(_path: &Path) -> io::Result<u64> {
Err(io::Error::new(
io::ErrorKind::Unsupported,
"filesystem capacity is unavailable on this platform",
))
}
#[cfg(test)]
#[path = "disk_tests.rs"]
mod tests;

View File

@@ -0,0 +1,160 @@
use std::cell::RefCell;
use std::io;
use std::path::Path;
use pretty_assertions::assert_eq;
use serde_json::json;
use super::CheckStatus;
use super::FAIL_THRESHOLD;
use super::GIB;
use super::WARNING_THRESHOLD;
use super::check;
use super::check_with_paths;
#[test]
fn disk_capacity_is_reported_without_loaded_configuration() {
let check = check(/*config*/ None, Path::new("."));
for label in ["AKODE_HOME available: ", "worktree available: "] {
assert!(
check
.details
.iter()
.any(|detail| detail.starts_with(label) && !detail.contains("unavailable"))
);
}
}
#[test]
fn disk_capacity_thresholds_produce_complete_diagnostics() {
for (available, status, measured, summary) in [
(0, "fail", "0.0 MiB", "critically low disk space (0.0 MiB)"),
(
FAIL_THRESHOLD - 1,
"fail",
"1024.0 MiB",
"critically low disk space (1024.0 MiB)",
),
(
FAIL_THRESHOLD,
"warning",
"1.0 GiB",
"low disk space (1.0 GiB)",
),
(
WARNING_THRESHOLD - 1,
"warning",
"5.0 GiB",
"low disk space (5.0 GiB)",
),
(
WARNING_THRESHOLD,
"ok",
"5.0 GiB",
"sufficient free disk space (5.0 GiB)",
),
(
WARNING_THRESHOLD + GIB,
"ok",
"6.0 GiB",
"sufficient free disk space (6.0 GiB)",
),
] {
let issues = ["AKODE_HOME", "worktree"]
.into_iter()
.filter(|_| status != "ok")
.map(|label| {
json!({
"severity": status,
"cause": format!("{label} has insufficient disk space"),
"measured": measured,
"expected": "at least 5.0 GiB",
"remedy": "Free disk space or move the worktree to a larger volume.",
"fields": [format!("{label} available")],
})
})
.collect::<Vec<_>>();
let check = check_with_paths(Some(Path::new(".")), Path::new("."), |_| Ok(available));
assert_eq!(
serde_json::to_value(check).unwrap(),
json!({
"id": "system.disk",
"category": "disk",
"status": status,
"summary": summary,
"details": [
"warning threshold: 5.0 GiB",
"failure threshold: 1.0 GiB",
format!("AKODE_HOME available: {measured}"),
format!("worktree available: {measured}"),
],
"issues": issues,
"remediation": null,
"durationMs": 0,
}),
"available bytes: {available}"
);
}
}
#[test]
fn disk_measurement_errors_produce_complete_warning_diagnostics() {
let check = check_with_paths(Some(Path::new(".")), Path::new("."), |_| {
Err(io::ErrorKind::PermissionDenied.into())
});
let issues = ["AKODE_HOME", "worktree"]
.into_iter()
.map(|label| {
json!({
"severity": "warning",
"cause": format!("disk space for {label} could not be checked"),
"measured": "PermissionDenied",
"expected": "readable filesystem capacity",
"remedy": "Check filesystem access and available disk space.",
"fields": [format!("{label} available")],
})
})
.collect::<Vec<_>>();
assert_eq!(
serde_json::to_value(check).unwrap(),
json!({
"id": "system.disk",
"category": "disk",
"status": "warning",
"summary": "disk capacity could not be fully verified",
"details": [
"warning threshold: 5.0 GiB",
"failure threshold: 1.0 GiB",
"AKODE_HOME available: unavailable (PermissionDenied)",
"worktree available: unavailable (PermissionDenied)",
],
"issues": issues,
"remediation": null,
"durationMs": 0,
})
);
}
#[test]
fn nonexistent_relative_codex_home_uses_current_directory_capacity() {
let measured_paths = RefCell::new(Vec::new());
let check = check_with_paths(
Some(Path::new("doctor-nonexistent-relative-home/nested")),
Path::new("."),
|path| {
measured_paths.borrow_mut().push(path.to_path_buf());
Ok(WARNING_THRESHOLD)
},
);
assert_eq!(check.status, CheckStatus::Ok);
assert_eq!(
measured_paths.into_inner(),
[std::env::current_dir().unwrap(), Path::new(".").into()]
);
}

View File

@@ -0,0 +1,385 @@
//! Checks literal sandbox grants without traversing directory trees or probing deny rules.
//!
//! Filesystem calls run in disposable copies of this executable: a blocked mount
//! must not occupy a Tokio blocking worker and delay doctor's runtime shutdown.
//! Budgets bound helper waits, not synchronous process launch; policy is unchanged.
//! Windows only lists paths: even local-looking paths can redirect to network shares.
//! Restricted-read policies also only list paths: lexical checks cannot constrain symlinks.
use std::collections::BTreeSet;
use std::collections::HashMap;
use std::io;
use std::path::Path;
use std::process::Stdio;
use std::time::Duration;
use std::time::Instant;
use akode_config::ConfigPathContext;
use akode_config::format_config_layer_source;
use akode_config::permissions_toml::FilesystemPermissionToml;
use akode_core::config::Config;
use akode_protocol::permissions::FileSystemAccessMode;
use akode_protocol::permissions::FileSystemPath;
use akode_protocol::permissions::FileSystemSandboxPolicy;
use akode_protocol::permissions::FileSystemSandboxPolicyContext;
use akode_protocol::permissions::ReadDenyMatcher;
use akode_utils_absolute_path::AbsolutePathBuf;
use akode_utils_absolute_path::AbsolutePathBufGuard;
use akode_utils_path_uri::PathConvention;
use akode_utils_path_uri::PathUri;
use tokio::process::Command;
use super::CheckStatus;
use super::DoctorCheck;
use super::DoctorIssue;
const PROBE_TIMEOUT: Duration = Duration::from_secs(2);
const TOTAL_TIMEOUT: Duration = Duration::from_secs(8);
const SLOW_PROBE: Duration = Duration::from_secs(1);
const MAX_PATHS: usize = 32;
pub(super) async fn check(config: &Config) -> DoctorCheck {
let mut check = DoctorCheck::new(
"sandbox.filesystem_paths",
"sandbox",
CheckStatus::Ok,
"configured filesystem paths respond promptly",
);
// Resolve policy semantics lexically, without querying the configured paths.
let policy = config
.permissions
.permission_profile()
.file_system_sandbox_policy();
let cwd = PathUri::from_abs_path(&config.cwd);
let roots = config.effective_workspace_roots();
let home = AbsolutePathBufGuard::home_directory()
.and_then(|home| PathUri::from_host_native_path(home).ok());
let temporary_directories = std::env::var_os("TMPDIR")
.filter(|path| !path.is_empty())
.and_then(|path| AbsolutePathBuf::from_absolute_path(path).ok())
.map(PathUri::from)
.into_iter()
.collect::<Vec<_>>();
let context = FileSystemSandboxPolicyContext {
cwd: &cwd,
workspace_roots: &roots,
user_home_dir: home.as_ref(),
temporary_directories: Some(&temporary_directories),
};
let paths = literal_paths(&policy, &context);
if paths.is_empty() {
check.summary = "no explicit filesystem paths to probe".to_string();
return check;
}
let read_restricted = !policy.has_full_disk_read_access();
if read_restricted {
check.summary =
"configured filesystem paths listed; read restrictions prevent probes".to_string();
} else if cfg!(windows) {
check.summary =
"configured filesystem paths listed; probes disabled on Windows".to_string();
}
if let Some(profile) = config.permissions.active_permission_profile() {
check
.details
.push(format!("permission profile: {}", profile.id));
}
check
.details
.push("operation: resolve paths only; read/write access is not tested".to_string());
check
.details
.push("probe budgets: 2 seconds per path, 8 seconds total, at most 32 paths".to_string());
let started = Instant::now();
let mut checked = 0;
for (path, access) in paths.iter().take(MAX_PATHS) {
let remaining = TOTAL_TIMEOUT.saturating_sub(started.elapsed());
if remaining.is_zero() {
break;
}
let label = format!("path {}", checked + 1);
let probe_started = Instant::now();
let outcome = match path.to_abs_path() {
Ok(_) if read_restricted => ProbeResult::SkippedReadRestrictions,
Ok(_) if cfg!(windows) => ProbeResult::SkippedWindows,
Ok(native) => {
let executable = match std::env::current_exe() {
Ok(executable) => executable,
Err(_) => {
check.status = CheckStatus::Warning;
check.summary =
"filesystem path probes unavailable: cannot locate aKode executable"
.to_string();
return check;
}
};
let mut command = Command::new(&executable);
command
.arg("doctor")
.arg("--probe-filesystem-path")
.arg(native.as_path());
probe(&mut command, remaining.min(PROBE_TIMEOUT)).await
}
Err(_) => ProbeResult::Unsupported,
};
let slow = probe_started.elapsed() >= SLOW_PROBE;
checked += 1;
let access = access
.iter()
.map(ToString::to_string)
.collect::<Vec<_>>()
.join(", ");
check.details.push(format!(
"{label}: {} ({access}); {}",
path.inferred_native_path_string(),
outcome.description()
));
if slow {
check.details.push(format!(
"{label} latency: over 1 second (includes helper startup)"
));
}
check
.details
.push(format!("{label} source: {}", source(config, path)));
if !matches!(
outcome,
ProbeResult::Resolved
| ProbeResult::Missing
| ProbeResult::SkippedWindows
| ProbeResult::SkippedReadRestrictions
) || slow
{
check.status = CheckStatus::Warning;
check.summary =
"some configured filesystem paths are slow or could not be checked".to_string();
check.issues.push(
DoctorIssue::new(CheckStatus::Warning, format!("{label}: {}{}", outcome.description(), if slow { "; slow path probe" } else { "" }))
.field(label)
.remedy("Check this path's mount and host permissions. Ask your administrator whether the entry is needed on this machine; do not remove required restrictions."),
);
}
}
if checked < paths.len() {
check.status = CheckStatus::Warning;
check.summary = "filesystem path check is incomplete".to_string();
check.details.push(format!(
"unchecked paths: {} (probe budget exhausted)",
paths.len() - checked
));
}
check
.details
.push(format!("paths checked: {checked} of {}", paths.len()));
check
}
fn literal_paths(
policy: &FileSystemSandboxPolicy,
context: &FileSystemSandboxPolicyContext<'_>,
) -> Vec<(PathUri, BTreeSet<FileSystemAccessMode>)> {
let mut paths = HashMap::<_, BTreeSet<_>>::new();
let denials = ReadDenyMatcher::from_context(policy, context);
for entry in &policy.entries {
// Deny rules can contain private managed-policy paths. Doctor only
// reports their counts in the existing sandbox check.
if entry.access == FileSystemAccessMode::Deny {
continue;
}
match &entry.path {
FileSystemPath::Path { path } => {
if policy.can_read_path(path, context)
&& !denials
.as_ref()
.is_some_and(|matcher| matcher.is_read_denied_uri(path, context))
{
paths.entry(path.clone()).or_default().insert(entry.access);
}
}
FileSystemPath::GlobPattern { .. } | FileSystemPath::Special { .. } => {}
}
}
let mut paths = paths.into_iter().collect::<Vec<_>>();
paths.sort_by_cached_key(|(path, _)| path.to_string());
paths
}
fn source(config: &Config, path: &PathUri) -> String {
let active = config.permissions.active_permission_profile();
let context = ConfigPathContext::new(
PathConvention::native(),
Some(PathUri::from_abs_path(&config.cwd)),
AbsolutePathBufGuard::home_directory()
.and_then(|home| PathUri::from_host_native_path(home).ok()),
);
let effective = config.config_layer_stack.effective_config();
let managed = config
.config_layer_stack
.requirements_toml()
.permissions
.as_ref();
let matches_path = |base: &str, subpath: Option<&str>| {
let base = if subpath.is_none() {
base.strip_suffix("/**").unwrap_or(base)
} else {
base
};
let Ok(base) = context.resolve_path(base) else {
return false;
};
match subpath.map(|subpath| subpath.strip_suffix("/**").unwrap_or(subpath)) {
None | Some(".") => base == *path,
Some(subpath) => context
.resolve_against(subpath, &base)
.is_ok_and(|resolved| resolved == *path),
}
};
let mut profiles = Vec::new();
let mut next = active.as_ref().map(|profile| profile.id.as_str());
while let Some(profile) = next {
if profiles.contains(&profile) {
break;
}
profiles.push(profile);
next = effective
.get("permissions")
.and_then(|permissions| permissions.get(profile))
.and_then(|profile| profile.get("extends"))
.and_then(toml::Value::as_str)
.or_else(|| managed?.profiles.get(profile)?.extends.as_deref());
}
for profile in profiles {
// Managed grants have no config-layer origin and can shadow a parent's grant.
if managed
.and_then(|managed| managed.profiles.get(profile))
.and_then(|profile| profile.filesystem.as_ref())
.is_some_and(|filesystem| {
filesystem.entries.iter().any(|(base, entry)| match entry {
FilesystemPermissionToml::Access(access) => {
*access != FileSystemAccessMode::Deny
&& matches_path(base, /*subpath*/ None)
}
FilesystemPermissionToml::Scoped(entries) => {
entries.iter().any(|(subpath, access)| {
*access != FileSystemAccessMode::Deny
&& matches_path(base, Some(subpath))
})
}
})
})
{
break;
}
let origins = config
.config_layer_stack
.origins_with_path_filter(|segments| {
if segments.len() < 4 || segments[0] != "permissions" || segments[2] != "filesystem"
{
return false;
}
if profile != segments[1] {
return false;
}
// Origins can retain leaves removed by a table/scalar replacement.
if !matches!(
segments
.iter()
.try_fold(&effective, |value, segment| value.get(segment))
.and_then(toml::Value::as_str),
Some("read" | "write")
) {
return false;
}
matches_path(&segments[3], segments.get(4).map(String::as_str))
});
let sources = origins
.into_iter()
.map(|(key, origin)| {
format!(
"{key} in {}",
format_config_layer_source(&origin.name, akode_config::CONFIG_TOML_FILE)
)
})
.collect::<BTreeSet<_>>();
if !sources.is_empty() {
return sources.into_iter().collect::<Vec<_>>().join("; ");
}
}
// Compiled requirements, legacy config, and runtime-added entries do not
// retain per-entry provenance. Do not misattribute them to a config file.
"effective filesystem policy (entry provenance unavailable)".to_string()
}
#[derive(Debug, PartialEq, Eq)]
enum ProbeResult {
Resolved,
Missing,
Denied,
TimedOut,
Failed,
Unsupported,
SkippedWindows,
SkippedReadRestrictions,
}
impl ProbeResult {
fn description(&self) -> &'static str {
match self {
Self::Resolved => "path resolved (read/write access not tested)",
Self::Missing => "missing (may be intentional)",
Self::Denied => "access denied to doctor",
Self::TimedOut => "path probe timed out",
Self::Failed => "path probe failed",
Self::Unsupported => "path is not native to this host; not probed",
Self::SkippedWindows => "not probed on Windows (network authentication risk)",
Self::SkippedReadRestrictions => "not probed (filesystem read restrictions apply)",
}
}
}
async fn probe(command: &mut Command, budget: Duration) -> ProbeResult {
command
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.kill_on_drop(/*kill_on_drop*/ true);
let Ok(mut child) = command.spawn() else {
return ProbeResult::Failed;
};
match tokio::time::timeout(budget, child.wait()).await {
Ok(Ok(status)) => match status.code() {
Some(0) => ProbeResult::Resolved,
Some(2) => ProbeResult::Missing,
Some(3) => ProbeResult::Denied,
Some(5) => ProbeResult::SkippedWindows,
_ => ProbeResult::Failed,
},
Ok(Err(_)) => ProbeResult::Failed,
Err(_) => {
// Do not await termination: an uninterruptible filesystem syscall
// can delay even SIGKILL. Tokio reaps the child when it can exit.
let _ = child.start_kill();
ProbeResult::TimedOut
}
}
}
pub(super) fn probe_exit_code(path: &Path) -> i32 {
// Even drive-qualified paths can traverse reparse points to network shares.
// Do not initiate filesystem access on Windows from this unsandboxed helper.
if cfg!(windows) {
return 5;
}
match std::fs::canonicalize(path) {
Ok(_) => 0,
Err(error) => match error.kind() {
io::ErrorKind::NotFound => 2,
io::ErrorKind::PermissionDenied => 3,
_ => 4,
},
}
}
#[cfg(test)]
#[path = "filesystem_paths_tests.rs"]
mod tests;

View File

@@ -0,0 +1,286 @@
use std::collections::BTreeSet;
use std::time::Duration;
use std::time::Instant;
use akode_config::LoaderOverrides;
use akode_core::config::ConfigBuilder;
use akode_protocol::permissions::FileSystemAccessMode;
use akode_protocol::permissions::FileSystemPath;
use akode_protocol::permissions::FileSystemSandboxEntry;
use akode_protocol::permissions::FileSystemSandboxPolicy;
use akode_protocol::permissions::FileSystemSandboxPolicyContext;
use akode_protocol::permissions::FileSystemSpecialPath;
use akode_utils_path_uri::PathUri;
use pretty_assertions::assert_eq;
use tokio::process::Command;
use super::ProbeResult;
use super::literal_paths;
use super::probe;
use super::source;
#[test]
fn deduplicates_literal_paths_without_expanding_globs_or_special_paths() {
let temp = tempfile::tempdir().unwrap();
let path = PathUri::from_host_native_path(temp.path()).unwrap();
let mut policy = FileSystemSandboxPolicy {
entries: vec![
FileSystemSandboxEntry {
path: path.clone().into(),
access: FileSystemAccessMode::Read,
missing_path_behavior: None,
},
FileSystemSandboxEntry {
path: path.clone().into(),
access: FileSystemAccessMode::Write,
missing_path_behavior: None,
},
FileSystemSandboxEntry {
path: PathUri::from_host_native_path(temp.path().join("private-policy-path"))
.unwrap()
.into(),
access: FileSystemAccessMode::Deny,
missing_path_behavior: None,
},
FileSystemSandboxEntry {
path: FileSystemPath::GlobPattern {
pattern: format!("{}/**/*.env", temp.path().display()),
},
access: FileSystemAccessMode::Deny,
missing_path_behavior: None,
},
FileSystemSandboxEntry {
path: FileSystemPath::Special {
value: FileSystemSpecialPath::Root,
},
access: FileSystemAccessMode::Read,
missing_path_behavior: None,
},
],
..Default::default()
};
// Equal-specificity denials, denied ancestors, and deny globs all override grants.
for suffix in [
"private-policy-path",
"private-policy-path/child",
"secret.env",
] {
policy.entries.push(FileSystemSandboxEntry {
path: PathUri::from_host_native_path(temp.path().join(suffix))
.unwrap()
.into(),
access: FileSystemAccessMode::Read,
missing_path_behavior: None,
});
}
let context = FileSystemSandboxPolicyContext {
cwd: &path,
workspace_roots: std::slice::from_ref(&path),
user_home_dir: None,
temporary_directories: Some(&[]),
};
assert_eq!(
literal_paths(&policy, &context),
vec![(
path,
BTreeSet::from([FileSystemAccessMode::Read, FileSystemAccessMode::Write])
)]
);
}
#[tokio::test]
async fn attributes_paths_inherited_through_managed_profiles_to_their_config_layer() {
let home = tempfile::tempdir().unwrap();
let configured = home.path().join("unavailable");
let config_file = home.path().join("config.toml");
let base = toml::Value::String(configured.display().to_string());
std::fs::write(
&config_file,
format!(
r#"
default_permissions = "diagnostic"
[permissions.diagnostic]
extends = "middle"
[permissions.diagnostic.filesystem.{base}]
"." = "read"
[permissions.base]
extends = ":workspace"
[permissions.base.filesystem.{base}]
"." = "write"
".git" = "write"
"subtree/**" = "read"
"overridden" = "read"
"#
),
)
.unwrap();
let requirements_file = home.path().join("requirements.toml");
std::fs::write(
&requirements_file,
format!(
r#"
[permissions.middle]
extends = "base"
[permissions.middle.filesystem.{base}]
".git/**" = "deny"
"overridden" = "write"
"#
),
)
.unwrap();
let mut overrides = LoaderOverrides::without_managed_config_for_tests();
overrides.system_requirements_path = Some(requirements_file);
let config = ConfigBuilder::default()
.codex_home(home.path().to_path_buf())
.loader_overrides(overrides)
.build()
.await
.unwrap();
let path = PathUri::from_host_native_path(configured.join(".git")).unwrap();
assert_eq!(
source(&config, &path),
format!(
"permissions.base.filesystem.{}..git in user ({})",
configured.display(),
config_file.display()
)
);
let subtree = PathUri::from_host_native_path(configured.join("subtree")).unwrap();
assert_eq!(
source(&config, &subtree),
format!(
"permissions.base.filesystem.{}.subtree/** in user ({})",
configured.display(),
config_file.display()
)
);
let overridden = PathUri::from_host_native_path(configured.join("overridden")).unwrap();
assert_eq!(
source(&config, &overridden),
"effective filesystem policy (entry provenance unavailable)"
);
let base_path = PathUri::from_host_native_path(&configured).unwrap();
assert_eq!(
source(&config, &base_path),
format!(
"permissions.diagnostic.filesystem.{}.. in user ({})",
configured.display(),
config_file.display()
)
);
let mut check = super::check(&config).await;
for detail in &mut check.details {
*detail = detail
.replace(&home.path().display().to_string(), "FIXTURE")
.replace('\\', "/");
}
let report = super::super::DoctorReport {
schema_version: 1,
generated_at: "2026-01-01T00:00:00Z".to_string(),
overall_status: check.status,
codex_version: "test".to_string(),
checks: vec![check],
};
insta::assert_snapshot!(
"doctor_read_restricted_filesystem_paths",
super::super::render_human_report(
&report,
super::super::HumanOutputOptions {
show_details: true,
show_all: false,
ascii: true,
color_enabled: false,
},
)
);
}
#[tokio::test]
async fn returns_when_a_probe_process_does_not_exit() {
let mut command = Command::new(std::env::current_exe().unwrap());
command.args([
"--ignored",
"--exact",
"doctor::filesystem_paths::tests::blocked_probe_fixture",
]);
let started = Instant::now();
assert_eq!(
probe(&mut command, Duration::from_millis(/*millis*/ 150)).await,
ProbeResult::TimedOut
);
assert!(started.elapsed() < Duration::from_secs(/*secs*/ 5));
}
#[test]
#[ignore = "subprocess fixture for the bounded filesystem probe test"]
fn blocked_probe_fixture() {
std::thread::sleep(Duration::from_secs(/*secs*/ 30));
}
#[tokio::test]
async fn attributes_home_relative_subtree_paths_to_their_config_layer() {
let home = tempfile::tempdir().unwrap();
let config_file = home.path().join("config.toml");
std::fs::write(
&config_file,
r#"
default_permissions = "diagnostic"
[permissions.diagnostic]
extends = ":read-only"
[permissions.diagnostic.filesystem]
"~/doctor-provenance/**" = "read"
"#,
)
.unwrap();
let config = ConfigBuilder::default()
.codex_home(home.path().to_path_buf())
.build()
.await
.unwrap();
let user_home = akode_utils_absolute_path::AbsolutePathBufGuard::home_directory().unwrap();
let path = PathUri::from_host_native_path(user_home.join("doctor-provenance")).unwrap();
assert_eq!(
source(&config, &path),
format!(
"permissions.diagnostic.filesystem.~/doctor-provenance/** in user ({})",
config_file.display()
)
);
}
#[tokio::test]
async fn excludes_scoped_origins_replaced_by_a_scalar_grant() {
let home = tempfile::tempdir().unwrap();
let configured = home.path().join("cache.v1");
let base = toml::Value::String(configured.display().to_string());
std::fs::write(
home.path().join("config.toml"),
format!(
r#"
default_permissions = "diagnostic"
[permissions.diagnostic]
extends = ":read-only"
[permissions.diagnostic.filesystem.{base}]
"." = "read"
"#
),
)
.unwrap();
let config = ConfigBuilder::default()
.codex_home(home.path().to_path_buf())
.cli_overrides(vec![(
"permissions.diagnostic.filesystem".to_string(),
format!("{{ {base} = \"write\" }}").parse().unwrap(),
)])
.build()
.await
.unwrap();
let path = PathUri::from_host_native_path(&configured).unwrap();
assert_eq!(
source(&config, &path),
format!(
"permissions.diagnostic.filesystem.{} in session-flags",
configured.display()
)
);
}

View File

@@ -0,0 +1,160 @@
//! Inspects Git executable locations and repository metadata without running Git.
use std::collections::BTreeSet;
use std::path::Path;
use std::path::PathBuf;
use akode_git_utils::get_git_repo_root;
use super::CheckStatus;
use super::DoctorCheck;
use super::DoctorIssue;
#[derive(Clone, Debug, Default, Eq, PartialEq)]
struct GitCheckInputs {
selected_git: Option<PathBuf>,
git_candidates: Vec<PathBuf>,
repo_root: Option<PathBuf>,
git_entry: Option<String>,
}
pub(super) fn git_check(cwd: &Path) -> DoctorCheck {
let selected_git = which::which("git").ok();
let git_candidates = git_candidates();
let repo_root = get_git_repo_root(cwd);
git_check_from_inputs(GitCheckInputs {
selected_git,
git_candidates,
git_entry: repo_root.as_deref().map(git_entry_summary),
repo_root,
})
}
fn git_check_from_inputs(inputs: GitCheckInputs) -> DoctorCheck {
let mut details = Vec::new();
match inputs.selected_git.as_deref() {
Some(path) => details.push(format!("selected git: {}", path.display())),
None => details.push("selected git: not found".to_string()),
}
details.push(format!("PATH git entries: {}", inputs.git_candidates.len()));
for (index, path) in inputs.git_candidates.iter().enumerate() {
details.push(format!("PATH git #{}: {}", index + 1, path.display()));
}
match inputs.repo_root.as_deref() {
Some(root) => {
details.push("repo detected: true".to_string());
details.push(format!("repo root: {}", root.display()));
}
None => details.push("repo detected: false".to_string()),
}
if let Some(entry) = inputs.git_entry.as_deref() {
details.push(format!(".git entry: {entry}"));
}
details.push("git execution: not inspected (PATH helpers are not executed)".to_string());
let mut check = DoctorCheck::new(
"git.environment",
"git",
CheckStatus::Ok,
if inputs.selected_git.is_some() {
"git executable found; execution not verified"
} else {
"git executable not found"
},
)
.details(details);
if inputs.selected_git.is_none() && inputs.repo_root.is_some() {
check.status = CheckStatus::Warning;
check.summary = "Git repository detected but git executable was not found".to_string();
check = check.issue(
DoctorIssue::new(
CheckStatus::Warning,
"Git repository detected but git executable was not found",
)
.expected("git available on PATH")
.remedy("Install Git or fix PATH so aKode can inspect repository metadata.")
.field("selected git"),
);
}
check
}
fn git_candidates() -> Vec<PathBuf> {
let Ok(candidates) = which::which_all("git") else {
return Vec::new();
};
let mut seen = BTreeSet::new();
candidates
.filter(|candidate| seen.insert(candidate.clone()))
.collect()
}
fn git_entry_summary(repo_root: &Path) -> String {
let entry = repo_root.join(".git");
match std::fs::metadata(&entry) {
Ok(metadata) if metadata.is_dir() => "directory".to_string(),
Ok(metadata) if metadata.is_file() => std::fs::read_to_string(&entry)
.ok()
.and_then(|contents| {
contents
.strip_prefix("gitdir:")
.map(str::trim)
.map(|path| format!("file -> {path}"))
})
.unwrap_or_else(|| "file".to_string()),
Ok(_) => "other".to_string(),
Err(err) if err.kind() == std::io::ErrorKind::NotFound => "missing".to_string(),
Err(err) => format!("unreadable ({err})"),
}
}
#[cfg(test)]
mod tests {
use pretty_assertions::assert_eq;
use super::*;
#[test]
fn warns_when_git_repo_has_no_git_executable() {
let check = git_check_from_inputs(GitCheckInputs {
repo_root: Some(PathBuf::from("/repo")),
..GitCheckInputs::default()
});
assert_eq!(check.status, CheckStatus::Warning);
assert_eq!(
check.summary,
"Git repository detected but git executable was not found"
);
}
#[test]
fn reports_git_candidates_and_repo_metadata() {
let check = git_check_from_inputs(GitCheckInputs {
selected_git: Some(PathBuf::from("/usr/bin/git")),
git_candidates: vec![PathBuf::from("/usr/bin/git"), PathBuf::from("/opt/bin/git")],
repo_root: Some(PathBuf::from("/repo")),
git_entry: Some("directory".to_string()),
});
let report = super::super::DoctorReport {
schema_version: 1,
generated_at: "2026-01-01T00:00:00Z".to_string(),
overall_status: check.status,
codex_version: "test".to_string(),
checks: vec![check],
};
insta::assert_snapshot!(super::super::render_human_report(
&report,
super::super::HumanOutputOptions {
show_details: true,
show_all: false,
ascii: true,
color_enabled: false,
},
));
}
}

View File

@@ -0,0 +1,223 @@
use std::env;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
use std::time::Instant;
use akode_arg0::Arg0DispatchPaths;
use akode_core::config::Config;
#[cfg(target_os = "macos")]
use akode_http_client::MacosSystemProxyConfiguration;
use akode_http_client::RouteAwareClientPool;
use akode_http_client::RouteAwareRequestError;
use akode_http_client::RouteFailureClass;
#[cfg(target_os = "macos")]
use akode_http_client::macos_system_proxy_configuration;
use akode_login::default_client::create_client_without_request_logging;
use akode_tui::Cli as TuiCli;
use akode_utils_cli::CliConfigOverrides;
use http::HeaderMap;
use http::Method;
use super::CheckStatus;
use super::DoctorCheck;
use super::DoctorProgress;
use super::push_proxy_env_details;
use super::read_probe_file;
pub(super) async fn checks(
overrides: CliConfigOverrides,
interactive: &TuiCli,
arg0_paths: &Arg0DispatchPaths,
progress: &Arc<dyn DoctorProgress>,
) -> Vec<DoctorCheck> {
progress.begin("config");
let config_started = Instant::now();
let config = match super::load_config(overrides, interactive, arg0_paths).await {
Ok(config) => config,
Err(error) => {
let check = super::config_load_failure(&error)
.detail("network diagnostics: effective network configuration is unavailable");
progress.finish("config", check.status);
return vec![check];
}
};
let config_duration = config_started.elapsed();
let mut config_check = super::config_check(&config).detail(format!(
"configuration load ms: {}",
config_duration.as_millis()
));
config_check.duration_ms = config_duration.as_millis().try_into().unwrap_or(u64::MAX);
progress.finish("config", config_check.status);
let auth_manager = akode_login::AuthManager::shared_from_config(
&config, /*enable_codex_api_key_env*/ true,
)
.await
.ok();
let plan = super::provider_reachability_plan(&config);
#[cfg(target_os = "macos")]
let url = plan.endpoints.first().map(|endpoint| endpoint.url.clone());
let (network, websocket, reachability) = tokio::join!(
async { super::run_sync_check("network", progress.clone(), || check(Some(&config))) },
super::run_async_check(
"websocket",
progress.clone(),
super::websocket_reachability_check(&config, auth_manager)
),
super::run_async_check(
"provider reachability",
progress.clone(),
super::provider_reachability_check(plan)
),
);
#[cfg(target_os = "macos")]
let reachability = with_system_proxy_remediation(reachability, &config, url.as_deref());
vec![config_check, network, websocket, reachability]
}
#[cfg(any(target_os = "macos", test))]
pub(super) const SYSTEM_PROXY_REMEDIATION: &str = "A macOS system proxy is configured but unused. If your organization requires it, ask your administrator whether to enable the experimental System proxy setting in `/experimental` or with `akode features enable respect_system_proxy`. Restart aKode after changing this setting.";
pub(super) fn check(config: Option<&Config>) -> DoctorCheck {
let mut details = Vec::new();
push_proxy_env_details(&mut details);
#[cfg(target_os = "macos")]
{
let request_url = config
.and_then(|config| config.model_provider.base_url.as_deref())
.unwrap_or("http://localhost/");
let configuration = match macos_system_proxy_configuration(request_url) {
MacosSystemProxyConfiguration::Automatic => "automatic (PAC)",
MacosSystemProxyConfiguration::Manual => "manual",
MacosSystemProxyConfiguration::Direct => "direct",
MacosSystemProxyConfiguration::Unavailable => "unavailable",
};
details.push(format!("system proxy: {configuration}"));
}
if let Some(config) = config {
let enabled = |value| if value { "enabled" } else { "disabled" };
details.push(format!(
"respect system proxy: {}",
enabled(config.respect_system_proxy)
));
if config.permissions.network.is_some() {
details.push("managed proxy: configured".to_string());
} else {
details.push("managed proxy: not configured".to_string());
}
}
let mut status = CheckStatus::Ok;
let mut summary = "network-related environment looks readable".to_string();
for name in ["AKODE_CA_CERTIFICATE", "SSL_CERT_FILE"] {
if let Some(raw) = env::var_os(name) {
let path = PathBuf::from(raw);
match std::fs::metadata(&path) {
Ok(metadata) if metadata.is_file() => {
if let Err(error) = read_probe_file(&path) {
status = CheckStatus::Warning;
summary = "custom CA env var points at an unreadable file".to_string();
details.push(format!("{name}: {} ({error})", path.display()));
} else {
details.push(format!("{name}: readable file {}", path.display()));
}
}
Ok(_) => {
status = CheckStatus::Warning;
summary = "custom CA env var does not point at a file".to_string();
details.push(format!("{name}: not a file {}", path.display()));
}
Err(error) => {
status = CheckStatus::Warning;
summary = "custom CA env var points at an unreadable path".to_string();
details.push(format!("{name}: {} ({error})", path.display()));
}
}
}
}
DoctorCheck::new("network.env", "network", status, summary).details(details)
}
#[cfg(target_os = "macos")]
pub(super) fn with_system_proxy_remediation(
mut check: DoctorCheck,
config: &Config,
request_url: Option<&str>,
) -> DoctorCheck {
if check.status == CheckStatus::Fail
&& !config.respect_system_proxy
&& config.permissions.network.is_none()
&& config
.config_layer_stack
.requirements()
.feature_requirements
.as_ref()
.and_then(|requirements| requirements.value.entries.get("respect_system_proxy"))
.is_none_or(|enabled| *enabled)
&& !super::PROXY_ENV_VARS
.iter()
.any(|name| !name.eq_ignore_ascii_case("NO_PROXY") && super::env_var_present(name))
&& request_url.is_some_and(|url| {
matches!(
macos_system_proxy_configuration(url),
MacosSystemProxyConfiguration::Automatic | MacosSystemProxyConfiguration::Manual
)
})
{
check.remediation = Some(SYSTEM_PROXY_REMEDIATION.to_string());
}
check
}
pub(super) async fn probe_status(
client: &RouteAwareClientPool,
url: &str,
method: Method,
headers: HeaderMap,
) -> Result<u16, String> {
let response = if env::var("AKODE_SANDBOX").as_deref() == Ok("seatbelt") {
create_client_without_request_logging()
.request(method, url)
.headers(headers)
.timeout(Duration::from_secs(8))
.send()
.await
} else {
client
.request(method, url)
.headers(headers)
// Allow five seconds for PAC resolution before the three-second HTTP budget.
.timeout(Duration::from_secs(8))
.send()
.await
}
.map_err(request_error)?;
let status = response.status().as_u16();
if status == 407 {
return Err("proxy authentication required (HTTP 407)".to_string());
}
Ok(status)
}
pub(super) fn request_error(error: RouteAwareRequestError) -> String {
match error.failure_class() {
Some(RouteFailureClass::TlsError) => "TLS handshake or certificate validation failed",
Some(RouteFailureClass::ProxyAuthenticationRequired) => "proxy authentication required",
Some(RouteFailureClass::InvalidProxyConfig) => "invalid proxy configuration",
Some(RouteFailureClass::ProxyResolutionUnavailable) => {
"system proxy configuration unavailable"
}
Some(RouteFailureClass::ConnectTimeout) => "request timed out",
Some(RouteFailureClass::UnsupportedProxyScheme) => "unsupported proxy configuration",
Some(RouteFailureClass::ResolverError) => "proxy resolution failed",
None if error.is_timeout() => "request timed out",
None if error.is_connect() => "connect failed",
None => "request failed",
}
.to_string()
}
#[cfg(test)]
#[path = "network_tests.rs"]
mod tests;

View File

@@ -0,0 +1,35 @@
use pretty_assertions::assert_eq;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::method;
use super::super::CheckStatus;
use super::super::ProviderAuthReachabilityMode;
use super::super::provider_reachability_check;
use super::super::provider_reachability_plan_from_parts;
#[tokio::test]
async fn provider_reachability_rejects_proxy_authentication_challenges() {
let proxy = MockServer::start().await;
Mock::given(method("HEAD"))
.respond_with(ResponseTemplate::new(407))
.mount(&proxy)
.await;
let plan = provider_reachability_plan_from_parts(
ProviderAuthReachabilityMode::NotRequired,
"local",
"Local",
Some(&format!("{}/v1", proxy.uri())),
/*provider_query_params*/ None,
);
let check = provider_reachability_check(plan).await;
assert_eq!(check.status, CheckStatus::Fail);
assert!(
check
.details
.join(" ")
.contains("proxy authentication required (HTTP 407)")
);
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,791 @@
//! 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() {
"system" => system_details(&parsed),
"runtime" => runtime_details(&parsed),
"install" => install_details(&parsed, options),
"git" => git_details(&parsed, options),
"title" => title_details(&parsed),
"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
}
fn system_details(parsed: &[ParsedDetail]) -> Vec<HumanDetail> {
let mut out = Vec::new();
push_row_if_present(&mut out, parsed, "os", "os");
push_row_if_present(&mut out, parsed, "os language", "OS language");
push_row_if_present(&mut out, parsed, "LC_ALL", "LC_ALL");
push_row_if_present(&mut out, parsed, "LC_CTYPE", "LC_CTYPE");
push_row_if_present(&mut out, parsed, "LANG", "LANG");
push_row_if_present(&mut out, parsed, "VISUAL", "VISUAL");
push_row_if_present(&mut out, parsed, "EDITOR", "EDITOR");
push_row_if_present(&mut out, parsed, "PAGER", "PAGER");
push_row_if_present(&mut out, parsed, "GIT_PAGER", "GIT_PAGER");
push_row_if_present(&mut out, parsed, "GH_PAGER", "GH_PAGER");
push_row_if_present(&mut out, parsed, "LESS", "LESS");
push_remaining(
&mut out,
parsed,
&[
"os",
"os type",
"os version",
"os language",
"LC_ALL",
"LC_CTYPE",
"LANG",
"VISUAL",
"EDITOR",
"PAGER",
"GIT_PAGER",
"GH_PAGER",
"LESS",
],
&[],
);
out
}
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 managed_by_pnpm = value(parsed, "managed by pnpm").unwrap_or("false");
let managed_by_vite_plus = value(parsed, "managed by Vite+").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: {} · pnpm: {} · Vite+: {} · package root {}",
yes_no(managed_by_npm),
yes_no(managed_by_bun),
yes_no(managed_by_pnpm),
yes_no(managed_by_vite_plus),
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 by pnpm",
"managed by Vite+",
"managed package root",
"PATH codex entries",
],
&["PATH codex #"],
);
out
}
fn git_details(parsed: &[ParsedDetail], options: HumanOutputOptions) -> Vec<HumanDetail> {
let mut out = Vec::new();
push_row_if_present(&mut out, parsed, "selected git", "selected git");
push_row_if_present(&mut out, parsed, "git version", "version");
push_row_if_present(&mut out, parsed, "git exec path", "exec path");
push_row_if_present(&mut out, parsed, "repo detected", "repo detected");
push_row_if_present(&mut out, parsed, "repo root", "repo root");
push_row_if_present(&mut out, parsed, ".git entry", ".git entry");
push_row_if_present(&mut out, parsed, "git branch", "branch");
push_row_if_present(&mut out, parsed, "core.fsmonitor", "core.fsmonitor");
let path_entries = numbered_values(parsed, "PATH git #");
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,
&[
"selected git",
"PATH git entries",
"git version",
"git exec path",
"git build options",
"repo detected",
"repo root",
".git entry",
"git branch",
"core.fsmonitor",
],
&["PATH git #"],
);
out
}
fn title_details(parsed: &[ParsedDetail]) -> Vec<HumanDetail> {
let mut out = Vec::new();
push_row_if_present(&mut out, parsed, "terminal title source", "title source");
push_row_if_present(&mut out, parsed, "terminal title items", "title items");
push_row_if_present(&mut out, parsed, "terminal title activity", "activity item");
push_row_if_present(
&mut out,
parsed,
"terminal title project source",
"project source",
);
push_row_if_present(
&mut out,
parsed,
"terminal title project value",
"project value",
);
push_remaining(
&mut out,
parsed,
&[
"terminal title source",
"terminal title items",
"terminal title activity",
"terminal title project source",
"terminal title project value",
],
&[],
);
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,
&[
"AKODE_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, "AKODE_HOME", "AKODE_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");
push_database_row(&mut out, parsed, "goals DB");
push_database_row(&mut out, parsed, "memories 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,
&[
"AKODE_HOME",
"log dir",
"sqlite home",
"state DB",
"log DB",
"goals DB",
"state DB integrity",
"log DB integrity",
"goals DB integrity",
"memories DB",
"memories 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 {
"auth file" => "auth.json path (file backend/fallback)",
"akode-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" | "—" | "-"
)
}

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,
));
}
}

View File

@@ -0,0 +1,145 @@
//! 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
//! package files or from PATH.
use std::env;
use akode_install_context::InstallContext;
use akode_install_context::InstallMethod;
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)
}
/// Inspects the search command selected by the install context without executing it.
///
/// Package-layout installs should point at a bundled ripgrep binary, while local
/// installs without that layout 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 which::which(&rg_command) {
Ok(path) => {
details.push(format!("search command path: {}", path.display()));
details.push("search command readiness: found; execution not verified".to_string());
CheckStatus::Ok
}
Err(err) => {
details.push(format!("search command readiness: {err}"));
CheckStatus::Warning
}
}
};
let summary = match status {
CheckStatus::Ok => format!("search command found ({provider}); execution not verified"),
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 aKode package.");
}
check
}
fn install_method_name(context: &InstallContext) -> &'static str {
match &context.method {
InstallMethod::Standalone { .. } => "standalone",
InstallMethod::Npm => "npm",
InstallMethod::Bun => "bun",
InstallMethod::VitePlus => "vite+",
InstallMethod::Pnpm => "pnpm",
InstallMethod::Brew => "brew",
InstallMethod::Other => "local build",
}
}
fn search_provider(context: &InstallContext) -> &'static str {
let rg_command = context.rg_command();
let from_package_layout = context
.package_layout
.as_ref()
.and_then(|package_layout| package_layout.path_dir.as_ref())
.is_some_and(|path_dir| rg_command.starts_with(path_dir));
let from_legacy_standalone = matches!(
&context.method,
InstallMethod::Standalone {
resources_dir: Some(resources_dir),
..
} if rg_command.starts_with(resources_dir)
);
if from_package_layout || from_legacy_standalone {
"bundled"
} else {
"system"
}
}
fn build_commit() -> &'static str {
option_env!("AKODE_BUILD_COMMIT")
.or(option_env!("GIT_COMMIT"))
.unwrap_or("unknown")
}

View File

@@ -0,0 +1,356 @@
#[cfg(target_os = "windows")]
use std::fs;
#[cfg(target_os = "windows")]
use std::io;
use akode_arg0::Arg0DispatchPaths;
use akode_config::RequirementSource;
use akode_core::config::Config;
#[cfg(target_os = "windows")]
use akode_core::windows_sandbox::WindowsSandboxLevelExt;
#[cfg(target_os = "windows")]
use akode_protocol::config_types::WindowsSandboxLevel;
use akode_protocol::permissions::FileSystemAccessMode;
use akode_protocol::permissions::FileSystemPath;
#[cfg(target_os = "windows")]
use akode_sandboxing::windows_sandbox_uses_elevated_backend;
#[cfg(target_os = "windows")]
use akode_windows_sandbox::SetupErrorCode;
#[cfg(target_os = "windows")]
use windows_sys::Win32::Foundation::ERROR_ACCESS_DENIED;
#[cfg(target_os = "windows")]
use windows_sys::Win32::NetworkManagement::NetManagement::NERR_Success as NERR_SUCCESS;
#[cfg(target_os = "windows")]
use windows_sys::Win32::NetworkManagement::NetManagement::NERR_UserNotFound as NERR_USER_NOT_FOUND;
#[cfg(target_os = "windows")]
use windows_sys::Win32::NetworkManagement::NetManagement::NetApiBufferFree;
#[cfg(target_os = "windows")]
use windows_sys::Win32::NetworkManagement::NetManagement::NetUserGetInfo;
#[cfg(target_os = "windows")]
use windows_sys::Win32::NetworkManagement::NetManagement::UF_ACCOUNTDISABLE;
#[cfg(target_os = "windows")]
use windows_sys::Win32::NetworkManagement::NetManagement::UF_LOCKOUT;
#[cfg(target_os = "windows")]
use windows_sys::Win32::NetworkManagement::NetManagement::UF_PASSWORD_EXPIRED;
#[cfg(target_os = "windows")]
use windows_sys::Win32::NetworkManagement::NetManagement::USER_INFO_23;
use super::CheckStatus;
use super::DoctorCheck;
#[cfg(target_os = "windows")]
use super::DoctorIssue;
use super::push_path_detail;
#[cfg(target_os = "windows")]
const WINDOWS_SETUP_REMEDIATION: &str = "run akode sandbox setup --elevated --user <end-user> --codex-home <authoritative-home> from an elevated shell";
pub(super) fn sandbox_check(config: &Config, arg0_paths: &Arg0DispatchPaths) -> DoctorCheck {
let mut details = Vec::new();
details.push(format!(
"approval policy: {:?}",
config.permissions.approval_policy.value()
));
let file_system_sandbox = config.permissions.file_system_sandbox_policy();
details.push(format!("filesystem sandbox: {}", file_system_sandbox.kind));
let denied_entries = file_system_sandbox
.entries
.iter()
.filter(|entry| entry.access == FileSystemAccessMode::Deny);
details.push(format!(
"denied-read rules: {}",
denied_entries.clone().count()
));
details.push(format!(
"denied-read glob rules: {}",
denied_entries
.filter(|entry| matches!(entry.path, FileSystemPath::GlobPattern { .. }))
.count()
));
details.push(format!(
"glob scan max depth: {}",
file_system_sandbox
.glob_scan_max_depth
.map_or_else(|| "unbounded".to_string(), |depth| depth.to_string())
));
details.push(format!(
"managed filesystem source: {}",
match config
.config_layer_stack
.requirements()
.filesystem
.as_ref()
.map(|value| &value.source)
{
None => "none",
Some(RequirementSource::Unknown) => "unknown",
Some(RequirementSource::Composite { .. }) => "multiple layers",
Some(RequirementSource::MdmManagedPreferences { .. }) => "MDM",
Some(RequirementSource::SystemRequirementsToml { .. }) => "system",
Some(RequirementSource::LegacyManagedConfigTomlFromFile { .. }) => "legacy file",
Some(RequirementSource::LegacyManagedConfigTomlFromMdm) => "legacy MDM",
}
));
details.push(format!(
"network sandbox: {}",
config.permissions.network_sandbox_policy()
));
push_path_detail(
&mut details,
"akode-linux-sandbox helper",
arg0_paths.codex_linux_sandbox_exe.as_deref(),
);
let mut status = CheckStatus::Ok;
let mut summary = "sandbox configuration is readable".to_string();
if let Some(helper) = arg0_paths.codex_linux_sandbox_exe.as_deref()
&& !helper.exists()
{
status = CheckStatus::Warning;
summary = "Linux sandbox helper path does not exist".to_string();
}
let check = DoctorCheck::new("sandbox.helpers", "sandbox", status, summary).details(details);
#[cfg(target_os = "windows")]
let mut check = check;
#[cfg(target_os = "windows")]
{
let configured_level = WindowsSandboxLevel::from_config(config);
let mxc = config.effective_local_windows_sandbox_type()
== akode_protocol::sandbox::SandboxType::WindowsMxc;
let elevated = !mxc
&& configured_level != WindowsSandboxLevel::Disabled
&& windows_sandbox_uses_elevated_backend(configured_level);
let backend = if mxc {
"mxc".to_string()
} else if elevated {
WindowsSandboxLevel::Elevated.to_string()
} else {
configured_level.to_string()
};
let denied = !file_system_sandbox.has_full_disk_read_access();
check.details.push(format!("sandbox backend: {backend}"));
check
.details
.push(format!("denied-read restrictions: {denied}"));
if denied && !elevated && !mxc {
check.issues.push(
DoctorIssue::new(
CheckStatus::Fail,
"managed denied-read requirements need the elevated Windows sandbox backend",
)
.measured(format!("{backend} backend"))
.expected("elevated backend")
.remedy("enable the elevated Windows sandbox backend permitted by managed policy")
.field("sandbox backend")
.field("denied-read restrictions"),
);
}
if elevated {
let home = config.codex_home.as_path();
let path = akode_windows_sandbox::setup_error_path(home);
let report = match fs::metadata(&path) {
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None),
Ok(metadata) if metadata.is_file() && metadata.len() <= 64 * 1024 => {
akode_windows_sandbox::read_setup_error_report(home)
.map_err(|error| error.to_string())
}
Ok(metadata) if !metadata.is_file() => Err("not a regular file".to_string()),
Ok(_) => Err("larger than 64 KiB".to_string()),
Err(error) => Err(error.to_string()),
};
let report = match report {
Ok(report) => report,
Err(error) => {
check
.details
.push("setup failure report: unreadable".to_string());
check.issues.push(
DoctorIssue::new(
CheckStatus::Warning,
"Windows sandbox setup failure report could not be read",
)
.measured(error)
.expected("readable setup failure report no larger than 64 KiB")
.remedy(WINDOWS_SETUP_REMEDIATION)
.field("setup failure report"),
);
None
}
};
if report.is_none() && akode_windows_sandbox::sandbox_setup_is_complete(home) {
check
.details
.push("sandbox provisioning: complete".to_string());
for username in [
akode_windows_sandbox::OFFLINE_USERNAME,
akode_windows_sandbox::ONLINE_USERNAME,
] {
let username_wide = username.encode_utf16().chain(Some(0)).collect::<Vec<_>>();
let mut buffer = std::ptr::null_mut();
let status = unsafe {
NetUserGetInfo(
std::ptr::null(),
username_wide.as_ptr(),
/*level*/ 23,
&mut buffer,
)
};
let flags = if status == NERR_SUCCESS && !buffer.is_null() {
Some(unsafe { (*(buffer as *const USER_INFO_23)).usri23_flags })
} else {
None
};
if !buffer.is_null() {
unsafe { NetApiBufferFree(buffer.cast()) };
}
let (severity, cause, remediation) = match (status, flags) {
(NERR_USER_NOT_FOUND, _) => (
CheckStatus::Fail,
"a Windows sandbox account is missing",
WINDOWS_SETUP_REMEDIATION,
),
(NERR_SUCCESS, Some(flags)) if flags & UF_LOCKOUT != 0 => (
CheckStatus::Fail,
"a Windows sandbox account is locked",
"stop sandbox retries and ask IT to unlock the account",
),
(NERR_SUCCESS, Some(flags)) if flags & UF_ACCOUNTDISABLE != 0 => (
CheckStatus::Fail,
"a Windows sandbox account is disabled",
"ask IT to enable the sandbox account before rerunning setup",
),
(NERR_SUCCESS, Some(flags)) if flags & UF_PASSWORD_EXPIRED != 0 => (
CheckStatus::Fail,
"a Windows sandbox account password has expired",
WINDOWS_SETUP_REMEDIATION,
),
(NERR_SUCCESS, Some(_)) => continue,
(ERROR_ACCESS_DENIED, _) => (
CheckStatus::Warning,
"Windows sandbox account status could not be inspected",
"ask IT to inspect access to the local sandbox accounts",
),
_ => (
CheckStatus::Warning,
"Windows sandbox account status could not be inspected",
"ask IT to inspect the local sandbox accounts",
),
};
check.details.push(format!("sandbox account: {username}"));
if !matches!(
status,
NERR_SUCCESS | NERR_USER_NOT_FOUND | ERROR_ACCESS_DENIED
) {
check
.details
.push(format!("account query status: {status}"));
}
check.issues.push(
DoctorIssue::new(severity, cause)
.measured(username)
.expected("enabled, unlocked local sandbox account")
.remedy(remediation)
.field("sandbox account"),
);
}
} else {
check.details.push(if report.is_some() {
"sandbox provisioning: failed".to_string()
} else {
"sandbox provisioning: incomplete".to_string()
});
if let Some(report) = report {
let remediation = match report.code {
SetupErrorCode::OrchestratorElevationCheckFailed
| SetupErrorCode::OrchestratorElevationRequired
| SetupErrorCode::OrchestratorHelperLaunchCanceled => {
"use an elevated shell or your organization's approved elevation workflow"
}
SetupErrorCode::OrchestratorHelperLaunchFailed
| SetupErrorCode::OrchestratorHelperExitNonzero
| SetupErrorCode::OrchestratorHelperReportReadFailed
| SetupErrorCode::OrchestratorHelperIncomplete
| SetupErrorCode::HelperReadAclHelperSpawnFailed => {
"repair the installed aKode helpers or ask IT to allow their execution"
}
SetupErrorCode::HelperUserProvisionFailed
| SetupErrorCode::HelperUsersGroupCreateFailed
| SetupErrorCode::HelperUserCreateOrUpdateFailed
| SetupErrorCode::HelperSidResolveFailed
| SetupErrorCode::HelperCapabilitySidFailed => {
"ask IT to allow the managed local sandbox accounts and group"
}
SetupErrorCode::OrchestratorSandboxDirCreateFailed
| SetupErrorCode::HelperSandboxDirCreateFailed
| SetupErrorCode::HelperLogFailed
| SetupErrorCode::HelperDpapiProtectFailed
| SetupErrorCode::HelperUsersFileWriteFailed
| SetupErrorCode::HelperSetupMarkerWriteFailed
| SetupErrorCode::HelperSandboxLockFailed => {
"rerun elevated setup for the authoritative aKode home or ask IT"
}
SetupErrorCode::HelperFirewallComInitFailed
| SetupErrorCode::HelperFirewallPolicyAccessFailed
| SetupErrorCode::HelperFirewallPolicyIneffective
| SetupErrorCode::HelperFirewallRuleCreateOrAddFailed
| SetupErrorCode::HelperFirewallRuleVerifyFailed => {
"ask IT to allow aKode sandbox rules in managed Windows Firewall policy"
}
SetupErrorCode::OrchestratorPayloadSerializeFailed
| SetupErrorCode::HelperRequestArgsFailed
| SetupErrorCode::HelperUnknownError => {
"repair or reinstall the aKode CLI from an approved distribution"
}
};
check
.details
.push(format!("error code: {}", report.code.as_str()));
check.issues.push(
DoctorIssue::new(
CheckStatus::Fail,
"elevated Windows sandbox provisioning recorded a structured failure",
)
.measured(report.code.as_str())
.remedy(remediation)
.field("error code"),
);
} else {
check.issues.push(
DoctorIssue::new(
CheckStatus::Warning,
"elevated Windows sandbox provisioning is incomplete or outdated",
)
.remedy(WINDOWS_SETUP_REMEDIATION)
.field("sandbox provisioning"),
);
}
}
}
if let Some(severity) = check.issues.iter().map(|issue| issue.severity).max() {
check.status = check.status.max(severity);
check.summary = if check.issues.len() == 1 {
check.issues[0].cause.clone()
} else {
"Windows sandbox has multiple configuration or provisioning issues".to_string()
};
if check.remediation.is_none() {
check.remediation = check.issues.iter().find_map(|issue| issue.remedy.clone());
}
}
}
check
}
#[cfg(test)]
#[path = "sandbox_tests.rs"]
mod tests;

View File

@@ -0,0 +1,160 @@
use akode_arg0::Arg0DispatchPaths;
use akode_core::config::ConfigBuilder;
use pretty_assertions::assert_eq;
use super::CheckStatus;
use super::sandbox_check;
#[tokio::test]
async fn reports_missing_linux_sandbox_helper() {
let home = tempfile::tempdir().expect("create Codex home");
let config = ConfigBuilder::default()
.codex_home(home.path().to_path_buf())
.build()
.await
.expect("load sandbox config");
let arg0_paths = Arg0DispatchPaths {
codex_linux_sandbox_exe: Some(home.path().join("missing-linux-helper")),
..Default::default()
};
let check = sandbox_check(&config, &arg0_paths);
assert_eq!(check.status, CheckStatus::Warning);
assert_eq!(check.summary, "Linux sandbox helper path does not exist");
}
#[cfg(target_os = "windows")]
#[tokio::test]
async fn reports_refresh_failure_after_setup_completed() {
let home = tempfile::tempdir().expect("create Codex home");
let version = akode_windows_sandbox::SETUP_VERSION;
for (path, contents) in [
(
".sandbox/setup_marker.json",
serde_json::json!({
"version": version,
"offline_username": akode_windows_sandbox::OFFLINE_USERNAME,
"online_username": akode_windows_sandbox::ONLINE_USERNAME,
}),
),
(
".sandbox-secrets/sandbox_users.json",
serde_json::json!({
"version": version,
"offline": {
"username": akode_windows_sandbox::OFFLINE_USERNAME,
"password": "",
},
"online": {
"username": akode_windows_sandbox::ONLINE_USERNAME,
"password": "",
},
}),
),
] {
let path = home.path().join(path);
std::fs::create_dir_all(path.parent().expect("fixture parent"))
.expect("create fixture directory");
std::fs::write(path, contents.to_string()).expect("write sandbox fixture");
}
assert!(akode_windows_sandbox::sandbox_setup_is_complete(
home.path()
));
akode_windows_sandbox::write_setup_error_report(
home.path(),
&akode_windows_sandbox::SetupErrorReport {
code: akode_windows_sandbox::SetupErrorCode::HelperFirewallPolicyIneffective,
message: "firewall policy rejected the refresh".to_string(),
},
)
.expect("write refresh failure");
std::fs::write(
home.path().join("config.toml"),
"[windows]\nsandbox = \"elevated\"\n",
)
.expect("write elevated sandbox config");
let config = ConfigBuilder::default()
.codex_home(home.path().to_path_buf())
.build()
.await
.expect("load sandbox config");
let check = sandbox_check(&config, &Arg0DispatchPaths::default());
assert_eq!(check.status, CheckStatus::Fail);
assert_eq!(
check.issues[0].measured.as_deref(),
Some("helper_firewall_policy_ineffective")
);
}
#[cfg(target_os = "windows")]
#[tokio::test]
async fn rejects_oversized_setup_failure_reports() {
let home = tempfile::tempdir().expect("create Codex home");
akode_windows_sandbox::write_setup_error_report(
home.path(),
&akode_windows_sandbox::SetupErrorReport {
code: akode_windows_sandbox::SetupErrorCode::HelperFirewallPolicyIneffective,
message: "x".repeat(64 * 1024),
},
)
.expect("write oversized setup failure");
std::fs::write(
home.path().join("config.toml"),
"[windows]\nsandbox = \"elevated\"\n",
)
.expect("write elevated sandbox config");
let config = ConfigBuilder::default()
.codex_home(home.path().to_path_buf())
.build()
.await
.expect("load sandbox config");
let check = sandbox_check(&config, &Arg0DispatchPaths::default());
assert_eq!(check.status, CheckStatus::Warning);
assert!(
check
.details
.contains(&"setup failure report: unreadable".to_string())
);
assert_eq!(
check.issues[0].cause,
"Windows sandbox setup failure report could not be read"
);
assert_eq!(
check.issues[0].measured.as_deref(),
Some("larger than 64 KiB")
);
}
#[cfg(target_os = "windows")]
#[tokio::test]
async fn reports_malformed_setup_failure_reports() {
let home = tempfile::tempdir().expect("create Codex home");
let path = akode_windows_sandbox::setup_error_path(home.path());
std::fs::create_dir_all(path.parent().expect("setup failure report parent"))
.expect("create sandbox directory");
std::fs::write(path, "{").expect("write malformed setup failure report");
std::fs::write(
home.path().join("config.toml"),
"[windows]\nsandbox = \"elevated\"\n",
)
.expect("write elevated sandbox config");
let config = ConfigBuilder::default()
.codex_home(home.path().to_path_buf())
.build()
.await
.expect("load sandbox config");
let check = sandbox_check(&config, &Arg0DispatchPaths::default());
assert_eq!(check.status, CheckStatus::Warning);
assert_eq!(
check.issues[0].cause,
"Windows sandbox setup failure report could not be read"
);
assert!(check.issues[0].measured.is_some());
}

View File

@@ -0,0 +1,254 @@
#[cfg(any(target_os = "macos", target_os = "windows"))]
use std::ffi::OsStr;
#[cfg(target_os = "windows")]
use std::path::PathBuf;
#[cfg(any(target_os = "macos", target_os = "windows"))]
use std::process::Output;
#[cfg(any(target_os = "macos", target_os = "windows"))]
use std::process::Stdio;
#[cfg(any(target_os = "macos", target_os = "windows"))]
use std::time::Duration;
#[cfg(any(target_os = "macos", target_os = "windows"))]
use tokio::process::Command;
#[cfg(any(target_os = "macos", target_os = "windows"))]
use tokio::time::timeout;
use super::CheckStatus;
use super::DoctorCheck;
use super::DoctorIssue;
#[cfg(any(target_os = "macos", target_os = "windows"))]
const PRODUCT_QUERY_TIMEOUT: Duration = Duration::from_secs(5);
#[cfg(any(target_os = "macos", target_os = "windows"))]
const MAX_PRODUCT_OUTPUT_BYTES: usize = 64 * 1024;
pub(super) enum EndpointInspection {
Complete(Vec<&'static str>),
#[cfg(any(target_os = "windows", test))]
Partial(Vec<&'static str>),
#[cfg(any(target_os = "macos", target_os = "windows", test))]
Unavailable,
}
pub(super) async fn check() -> DoctorCheck {
endpoint_check(endpoint_products().await)
}
pub(super) fn endpoint_check(inspection: EndpointInspection) -> DoctorCheck {
let (products, visibility_incomplete) = match inspection {
EndpointInspection::Complete(products) => (products, false),
#[cfg(any(target_os = "windows", test))]
EndpointInspection::Partial(products) => (products, true),
#[cfg(any(target_os = "macos", target_os = "windows", test))]
EndpointInspection::Unavailable => {
return DoctorCheck::new(
"security.endpoint",
"security",
CheckStatus::Warning,
"endpoint protection inspection unavailable",
)
.detail("endpoint products: unavailable");
}
};
if products.is_empty() {
let (summary, detail) = if cfg!(any(target_os = "macos", target_os = "windows")) {
("no supported endpoint protection detected", "none detected")
} else {
(
"endpoint protection is not inspected on this platform",
"not inspected on this platform",
)
};
return DoctorCheck::new("security.endpoint", "security", CheckStatus::Ok, summary)
.detail(format!("endpoint products: {detail}"));
}
let targets = if cfg!(target_os = "windows") {
"signed Codex app; codex.exe; akode-windows-sandbox-setup.exe; akode-command-runner.exe; akode-code-mode-host.exe"
} else if cfg!(target_os = "macos") {
"signing team 2DC432GLL2 plus the installed Codex app identity, signed codex agent, and required helpers"
} else {
"verified Codex app, codex agent, and required helpers"
};
let mut check = DoctorCheck::new(
"security.endpoint",
"security",
CheckStatus::Warning,
"endpoint protection detected; aKode exclusions are unverified",
)
.detail(format!("endpoint products: {}", products.join(", ")))
.detail(format!("exclusion targets: {targets}"))
.detail("aKode exclusions: not verified")
.remediation(
"ask your security administrator to verify aKode exclusions and required helper allowances",
);
if visibility_incomplete {
check = check.detail("additional endpoint products: unavailable");
}
for product in products {
let remedy = match product {
"CrowdStrike Falcon" => {
"CrowdStrike Falcon: Add a certificate or IOA exclusion for aKode. If sensor overhead continues, exclude the aKode agent from sensor visibility. Keep monitoring descendant processes."
}
"BeyondTrust Privilege Management" => {
"BeyondTrust: Remove aKode from application blocking rules. Add allow rules for aKode helper executables. Do not grant administrator privileges."
}
"Microsoft Defender" => {
"Microsoft Defender: Add a certificate or executable-path exclusion for aKode and its helpers. If Attack Surface Reduction blocks aKode, add a rule exclusion. If Controlled Folder Access blocks aKode, allow the app."
}
"SentinelOne" => {
"SentinelOne: Add a signer, file-hash, or executable-path exclusion for aKode and its helpers."
}
"Jamf Protect" => {
"Jamf Protect: Add an Override Threat Prevention exception for aKode app and helper signing identities. If analytics cause delays, add an Ignore System Events for Analytics exception."
}
_ => {
"Add an exclusion for aKode and its helpers. Use the endpoint product instructions."
}
};
check = check.issue(
DoctorIssue::new(
CheckStatus::Warning,
format!("{product} can interfere with aKode. Verify aKode exclusions."),
)
.measured("not verified")
.expected("aKode application and helper exclusions")
.remedy(remedy)
.field("aKode exclusions"),
);
}
check
}
async fn endpoint_products() -> EndpointInspection {
#[cfg(target_os = "windows")]
{
let system32 = std::env::var_os("SystemRoot")
.map(PathBuf::from)
.unwrap_or_else(|| PathBuf::from(r"C:\Windows"))
.join("System32");
let service = system32.join("sc.exe");
let (crowdstrike, beyondtrust, defender, sentinelone) = tokio::join!(
product_command(&service, &["query", "CSFalconService"]),
product_command(&service, &["query", "DefendpointService"]),
product_command(&service, &["query", "WinDefend"]),
product_command(&service, &["query", "SentinelAgent"]),
);
let mut products = Vec::new();
let mut visibility_incomplete = false;
for (product, output) in [
("CrowdStrike Falcon", crowdstrike),
("BeyondTrust Privilege Management", beyondtrust),
("Microsoft Defender", defender),
("SentinelOne", sentinelone),
] {
match output {
Some(output) if output.status.success() => {
if product != "Microsoft Defender"
|| String::from_utf8_lossy(&output.stdout).lines().any(|line| {
line.split_once(':').is_some_and(|(_, value)| {
value.split_whitespace().next() == Some("4")
})
})
{
products.push(product);
}
}
Some(output) if output.status.code() == Some(1060) => {}
Some(_) | None => visibility_incomplete = true,
}
}
if visibility_incomplete {
if products.is_empty() {
EndpointInspection::Unavailable
} else {
EndpointInspection::Partial(products)
}
} else {
EndpointInspection::Complete(products)
}
}
#[cfg(target_os = "macos")]
{
const PRODUCTS: &[(&str, &str, &str)] = &[
(
"CrowdStrike Falcon",
"X9E956P446",
"com.crowdstrike.falcon.Agent",
),
(
"BeyondTrust Privilege Management",
"2ZS8T6NYB8",
"com.beyondtrust.endpointsecurity",
),
(
"Microsoft Defender",
"UBF8T346G9",
"com.microsoft.wdav.epsext",
),
(
"SentinelOne",
"4AYE5J54KN",
"com.sentinelone.network-monitoring",
),
(
"Jamf Protect",
"483DWKW443",
"com.jamf.protect.security-extension",
),
];
let Some(output) = product_command("/usr/bin/systemextensionsctl", &["list"])
.await
.filter(|output| output.status.success())
else {
return EndpointInspection::Unavailable;
};
EndpointInspection::Complete(
String::from_utf8_lossy(&output.stdout)
.lines()
.filter_map(|line| {
let mut columns = line.split_whitespace();
if columns.next() != Some("*") || columns.next() != Some("*") {
return None;
}
let team = columns.next()?;
let bundle = columns.next()?;
PRODUCTS.iter().find_map(|&(name, signer, identifier)| {
(team == signer && bundle == identifier).then_some(name)
})
})
.collect(),
)
}
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
{
EndpointInspection::Complete(Vec::new())
}
}
#[cfg(any(target_os = "macos", target_os = "windows"))]
async fn product_command(program: impl AsRef<OsStr>, args: &[&str]) -> Option<Output> {
let mut command = Command::from(akode_utils_process::background_command(program));
command
.args(args)
.stdin(Stdio::null())
.stderr(Stdio::null())
.kill_on_drop(true);
timeout(PRODUCT_QUERY_TIMEOUT, command.output())
.await
.ok()?
.ok()
.filter(|output| output.stdout.len() <= MAX_PRODUCT_OUTPUT_BYTES)
}
#[cfg(test)]
#[path = "security_tests.rs"]
mod tests;

View File

@@ -0,0 +1,184 @@
use pretty_assertions::assert_eq;
use super::super::redacted_json_check;
use super::CheckStatus;
use super::EndpointInspection;
use super::endpoint_check;
#[test]
fn no_endpoint_products_require_no_remediation() {
let check = endpoint_check(EndpointInspection::Complete(Vec::new()));
assert_eq!(check.status, CheckStatus::Ok);
assert_eq!(check.remediation, None);
assert!(check.issues.is_empty());
}
#[test]
fn unavailable_endpoint_inspection_does_not_require_remediation() {
let check = endpoint_check(EndpointInspection::Unavailable);
assert_eq!(check.status, CheckStatus::Warning);
assert!(check.summary.to_ascii_lowercase().contains("unavailable"));
assert_eq!(check.details, vec!["endpoint products: unavailable"]);
assert_eq!(check.remediation, None);
assert!(check.issues.is_empty());
}
#[test]
fn each_endpoint_product_requires_vendor_specific_app_exclusions() {
let cases: [(&str, &[&str]); 5] = [
("CrowdStrike Falcon", &["certificate", "ioa"]),
("BeyondTrust Privilege Management", &["application"]),
("Microsoft Defender", &["executable", "path", "certificate"]),
("SentinelOne", &["signer", "hash", "path"]),
("Jamf Protect", &["threat prevention"]),
];
for (product, strategies) in cases {
let check = endpoint_check(EndpointInspection::Complete(vec![product]));
assert_eq!(check.status, CheckStatus::Warning, "{product}");
assert!(
check
.details
.iter()
.any(|detail| detail.starts_with("exclusion targets: ")),
"{product}: {:?}",
check.details
);
let remediation = check
.remediation
.as_deref()
.expect("detected endpoint protection should require remediation")
.to_ascii_lowercase();
assert_eq!(
remediation,
"ask your security administrator to verify akode exclusions and required helper allowances",
"{product}"
);
assert!(
!serde_json::to_string(&redacted_json_check(&check))
.expect("serialize endpoint check")
.to_ascii_lowercase()
.contains("chatgpt"),
"{product}: endpoint diagnostics should only refer to Codex"
);
assert_eq!(check.issues.len(), 1, "{product}");
let issue = &check.issues[0];
assert_eq!(issue.severity, CheckStatus::Warning, "{product}");
assert!(
issue
.cause
.to_ascii_lowercase()
.contains(&product.to_ascii_lowercase()),
"{product}: {}",
issue.cause
);
assert!(
issue.cause.contains("Verify aKode exclusions."),
"{product}: {}",
issue.cause
);
let remedy = issue
.remedy
.as_deref()
.expect("endpoint product should have vendor-specific guidance")
.to_ascii_lowercase();
assert!(
strategies.iter().any(|strategy| remedy.contains(strategy)),
"{product}: {remedy}"
);
assert!(!remedy.contains("administrator-approved"), "{product}");
assert!(!remedy.contains(';'), "{product}");
for sentence in remedy.split('.') {
assert!(
sentence.split_whitespace().count() <= 20,
"{product}: {sentence}"
);
}
if product == "BeyondTrust Privilege Management" {
assert!(remedy.contains("rule"), "{product}: {remedy}");
assert!(remedy.contains("blocking"), "{product}: {remedy}");
assert!(
remedy.contains("do not grant administrator privileges"),
"{product}: {remedy}"
);
}
if product == "Microsoft Defender" {
assert!(
remedy.contains("attack surface reduction"),
"{product}: {remedy}"
);
assert!(
remedy.contains("controlled folder access"),
"{product}: {remedy}"
);
}
if product == "CrowdStrike Falcon" {
assert!(remedy.contains("sensor visibility"), "{product}: {remedy}");
assert!(remedy.contains("descendant"), "{product}: {remedy}");
}
if product == "Jamf Protect" {
assert!(remedy.contains("exception"), "{product}: {remedy}");
assert!(remedy.contains("signing"), "{product}: {remedy}");
}
}
}
#[test]
fn multiple_endpoint_products_each_get_distinct_guidance() {
let products = ["CrowdStrike Falcon", "Microsoft Defender"];
let check = endpoint_check(EndpointInspection::Complete(products.to_vec()));
assert_eq!(check.status, CheckStatus::Warning);
assert_eq!(check.issues.len(), products.len());
for product in products {
let matching_issues = check
.issues
.iter()
.filter(|issue| {
issue
.cause
.to_ascii_lowercase()
.contains(&product.to_ascii_lowercase())
})
.count();
assert_eq!(matching_issues, 1, "{product}");
}
}
#[test]
fn endpoint_product_guidance_preserves_structured_json_contract() {
let check = endpoint_check(EndpointInspection::Complete(vec!["Microsoft Defender"]));
let json = serde_json::to_value(redacted_json_check(&check)).expect("serialize endpoint check");
assert_eq!(json["id"], "security.endpoint");
assert_eq!(json["category"], "security");
assert_eq!(json["status"], "warning");
assert_eq!(json["details"]["endpoint products"], "Microsoft Defender");
assert!(json["details"]["exclusion targets"].is_string());
assert_eq!(json["issues"].as_array().map(Vec::len), Some(1));
assert!(json["issues"][0]["remedy"].is_string());
}
#[test]
fn detected_products_preserve_partial_inspection_visibility() {
let check = endpoint_check(EndpointInspection::Partial(vec!["Microsoft Defender"]));
assert_eq!(check.status, CheckStatus::Warning);
assert!(
check
.details
.contains(&"additional endpoint products: unavailable".to_string())
);
assert_eq!(check.issues.len(), 1);
}

View File

@@ -0,0 +1,9 @@
---
source: cli/src/doctor/background.rs
expression: details
---
update-loop pid file: AKODE_HOME/app-server-daemon/app-server-updater.pid (missing)
dedicated pid file: AKODE_HOME/app-server-daemon/daemon.pid (missing)
dedicated update-loop pid file: AKODE_HOME/app-server-daemon/daemon-updater.pid (missing)
automatic updates: disabled (configured)
update interval: 90 minutes (configured)

View File

@@ -0,0 +1,26 @@
---
source: cli/src/doctor/filesystem_paths_tests.rs
expression: "super::super::render_human_report(&report, super::super::HumanOutputOptions\n{ show_details: true, show_all: false, ascii: true, color_enabled: false, },)"
---
aKode Doctor vtest
Configuration
[ok] sandbox configured filesystem paths listed; read restrictions prevent probes
permission profile diagnostic
operation resolve paths only; read/write access is not tested
probe budgets 2 seconds per path, 8 seconds total, at most 32 paths
path 1 FIXTURE/unavailable (read); not probed (filesystem read restrictions apply)
path 1 source permissions.diagnostic.filesystem.FIXTURE/unavailable.. in user (FIXTURE/config.toml)
path 2 FIXTURE/unavailable/.git (write); not probed (filesystem read restrictions apply)
path 2 source permissions.base.filesystem.FIXTURE/unavailable..git in user (FIXTURE/config.toml)
path 3 FIXTURE/unavailable/overridden (write); not probed (filesystem read restrictions apply)
path 3 source effective filesystem policy (entry provenance unavailable)
path 4 FIXTURE/unavailable/subtree (read); not probed (filesystem read restrictions apply)
path 4 source permissions.base.filesystem.FIXTURE/unavailable.subtree/** in user (FIXTURE/config.toml)
paths checked 4 of 4
-------------------------------------------------------------
1 ok | 0 warn | 0 fail ok
--summary compact output --all expand truncated lists
--json redacted report

View File

@@ -0,0 +1,22 @@
---
source: cli/src/doctor/git.rs
assertion_line: 150
expression: "super::super::render_human_report(&report, super::super::HumanOutputOptions\n{ show_details: true, show_all: false, ascii: true, color_enabled: false, },)"
---
aKode Doctor vtest
Environment
[ok] git git executable found; execution not verified
selected git /usr/bin/git
repo detected true
repo root /repo
.git entry directory
PATH entries (2) /usr/bin/git
/opt/bin/git
git execution not inspected (PATH helpers are not executed)
-------------------------------------------------------------
1 ok | 0 warn | 0 fail ok
--summary compact output --all expand truncated lists
--json redacted report

View File

@@ -0,0 +1,10 @@
---
source: cli/src/doctor/output.rs
expression: "rendered.replace('\\u{1b}', \"<ESC>\")"
---
<ESC>[38;5;10m✓<ESC>[39m state <ESC>[2m<ESC>[38;5;117m/tmp/logs_2.sqlite<ESC>[39m, <ESC>[38;5;117m~/goals_1.sqlite<ESC>[39m integrity check; try <ESC>[38;5;117m--summary<ESC>[39m or <ESC>[38;5;117mcodex doctor<ESC>[39m<ESC>[0m
<ESC>[38;5;240mlocations <ESC>[39m see <ESC>[38;5;117m./logs<ESC>[39m, <ESC>[38;5;117m../goals<ESC>[39m. C:\logs, D:/goals. c:\logs, \\server\share\logs, \\?\C:\logs, \\?\UNC\server\share\logs, \\.\pipe\codex, \??\C:\logs, \DosDevices\C:\logs, \rooted. <ESC>[38;5;117mhttp://localhost:8080<ESC>[39m: <ESC>[38;5;117mhttps://example.com<ESC>[39m; <ESC>[38;5;117mwss://example.com<ESC>[39m) and <ESC>[38;5;117m/tmp/my data/logs_2.sqlite<ESC>[39m
<ESC>[38;5;214m⚠<ESC>[39m state <ESC>[38;5;117m/tmp/logs_2.sqlite<ESC>[39m, <ESC>[38;5;117m~/goals_1.sqlite<ESC>[39m integrity check; try <ESC>[38;5;117m--summary<ESC>[39m or <ESC>[38;5;117mcodex doctor<ESC>[39m
<ESC>[38;5;240mlocations <ESC>[39m see <ESC>[38;5;117m./logs<ESC>[39m, <ESC>[38;5;117m../goals<ESC>[39m. C:\logs, D:/goals. c:\logs, \\server\share\logs, \\?\C:\logs, \\?\UNC\server\share\logs, \\.\pipe\codex, \??\C:\logs, \DosDevices\C:\logs, \rooted. <ESC>[38;5;117mhttp://localhost:8080<ESC>[39m: <ESC>[38;5;117mhttps://example.com<ESC>[39m; <ESC>[38;5;117mwss://example.com<ESC>[39m) and <ESC>[38;5;117m/tmp/my data/logs_2.sqlite<ESC>[39m
<ESC>[38;5;196m✗<ESC>[39m state <ESC>[38;5;196m/tmp/logs_2.sqlite<ESC>[39m, <ESC>[38;5;196m~/goals_1.sqlite<ESC>[39m integrity check; try <ESC>[38;5;117m--summary<ESC>[39m or <ESC>[38;5;117mcodex doctor<ESC>[39m
<ESC>[38;5;240mlocations <ESC>[39m see <ESC>[38;5;196m./logs<ESC>[39m, <ESC>[38;5;196m../goals<ESC>[39m. C:\logs, D:/goals. c:\logs, \\server\share\logs, \\?\C:\logs, \\?\UNC\server\share\logs, \\.\pipe\codex, \??\C:\logs, \DosDevices\C:\logs, \rooted. <ESC>[38;5;196mhttp://localhost:8080<ESC>[39m: <ESC>[38;5;196mhttps://example.com<ESC>[39m; <ESC>[38;5;196mwss://example.com<ESC>[39m) and <ESC>[38;5;196m/tmp/my data/logs_2.sqlite<ESC>[39m

View File

@@ -0,0 +1,10 @@
---
source: cli/src/doctor/output.rs
expression: "rendered.replace('\\u{1b}', \"<ESC>\")"
---
<ESC>[38;5;10m✓<ESC>[39m state <ESC>[2m<ESC>[38;5;117m/tmp/logs_2.sqlite<ESC>[39m, <ESC>[38;5;117m~/goals_1.sqlite<ESC>[39m integrity check; try <ESC>[38;5;117m--summary<ESC>[39m or <ESC>[38;5;117mcodex doctor<ESC>[39m<ESC>[0m
<ESC>[38;5;240mlocations <ESC>[39m see <ESC>[38;5;117m./logs<ESC>[39m, <ESC>[38;5;117m../goals<ESC>[39m. <ESC>[38;5;117mC:\logs<ESC>[39m, <ESC>[38;5;117mD:/goals<ESC>[39m. <ESC>[38;5;117mc:\logs<ESC>[39m, <ESC>[38;5;117m\\server\share\logs<ESC>[39m, <ESC>[38;5;117m\\?\C:\logs<ESC>[39m, <ESC>[38;5;117m\\?\UNC\server\share\logs<ESC>[39m, <ESC>[38;5;117m\\.\pipe\codex<ESC>[39m, <ESC>[38;5;117m\??\C:\logs<ESC>[39m, \DosDevices\C:\logs, \rooted. <ESC>[38;5;117mhttp://localhost:8080<ESC>[39m: <ESC>[38;5;117mhttps://example.com<ESC>[39m; <ESC>[38;5;117mwss://example.com<ESC>[39m) and <ESC>[38;5;117m/tmp/my data/logs_2.sqlite<ESC>[39m
<ESC>[38;5;214m⚠<ESC>[39m state <ESC>[38;5;117m/tmp/logs_2.sqlite<ESC>[39m, <ESC>[38;5;117m~/goals_1.sqlite<ESC>[39m integrity check; try <ESC>[38;5;117m--summary<ESC>[39m or <ESC>[38;5;117mcodex doctor<ESC>[39m
<ESC>[38;5;240mlocations <ESC>[39m see <ESC>[38;5;117m./logs<ESC>[39m, <ESC>[38;5;117m../goals<ESC>[39m. <ESC>[38;5;117mC:\logs<ESC>[39m, <ESC>[38;5;117mD:/goals<ESC>[39m. <ESC>[38;5;117mc:\logs<ESC>[39m, <ESC>[38;5;117m\\server\share\logs<ESC>[39m, <ESC>[38;5;117m\\?\C:\logs<ESC>[39m, <ESC>[38;5;117m\\?\UNC\server\share\logs<ESC>[39m, <ESC>[38;5;117m\\.\pipe\codex<ESC>[39m, <ESC>[38;5;117m\??\C:\logs<ESC>[39m, \DosDevices\C:\logs, \rooted. <ESC>[38;5;117mhttp://localhost:8080<ESC>[39m: <ESC>[38;5;117mhttps://example.com<ESC>[39m; <ESC>[38;5;117mwss://example.com<ESC>[39m) and <ESC>[38;5;117m/tmp/my data/logs_2.sqlite<ESC>[39m
<ESC>[38;5;196m✗<ESC>[39m state <ESC>[38;5;196m/tmp/logs_2.sqlite<ESC>[39m, <ESC>[38;5;196m~/goals_1.sqlite<ESC>[39m integrity check; try <ESC>[38;5;117m--summary<ESC>[39m or <ESC>[38;5;117mcodex doctor<ESC>[39m
<ESC>[38;5;240mlocations <ESC>[39m see <ESC>[38;5;196m./logs<ESC>[39m, <ESC>[38;5;196m../goals<ESC>[39m. <ESC>[38;5;196mC:\logs<ESC>[39m, <ESC>[38;5;196mD:/goals<ESC>[39m. <ESC>[38;5;196mc:\logs<ESC>[39m, <ESC>[38;5;196m\\server\share\logs<ESC>[39m, <ESC>[38;5;196m\\?\C:\logs<ESC>[39m, <ESC>[38;5;196m\\?\UNC\server\share\logs<ESC>[39m, <ESC>[38;5;196m\\.\pipe\codex<ESC>[39m, <ESC>[38;5;196m\??\C:\logs<ESC>[39m, \DosDevices\C:\logs, \rooted. <ESC>[38;5;196mhttp://localhost:8080<ESC>[39m: <ESC>[38;5;196mhttps://example.com<ESC>[39m; <ESC>[38;5;196mwss://example.com<ESC>[39m) and <ESC>[38;5;196m/tmp/my data/logs_2.sqlite<ESC>[39m

View File

@@ -0,0 +1,80 @@
---
source: cli/src/doctor/output.rs
expression: "render_human_report(&report, detailed_no_color_unicode_options())"
---
aKode Doctor v0.0.0
Notes
↑ desktop build 123 available (ready to install)
⚠ terminal narrow terminal
✗ auth token expired - Run `akode login`.
✗ network provider is unreachable - A macOS system proxy is configured but unused. If your organization requires it, ask your administrator whether to enable the experimental System proxy setting in `/experimental` or with `akode features enable respect_system_proxy`. Restart aKode after changing this setting.
⚠ git this worktree is not on a Windows Dev Drive - create a trusted Windows Dev Drive: https://learn.microsoft.com/en-us/windows/dev-drive/
⚠ security Microsoft Defender can interfere with aKode. Verify aKode exclusions.
─────────────────────────────────────────────────────────────
Environment
✓ system en-US
os macOS 15.0
OS language en-US
VISUAL code --wait
EDITOR vim
PAGER less -R
GIT_PAGER delta
GH_PAGER less
LESS -FRX
✓ disk sufficient free disk space (42.0 GiB)
⚠ security Microsoft Defender can interfere with aKode. Verify aKode exclusions.
endpoint products Microsoft Defender
exclusion targets verified Codex app and required helpers
▸ aKode exclusions not verified (expected aKode application and helper exclusions)
→ Microsoft Defender: Add a certificate or executable-path exclusion for aKode and its helpers. If Attack Surface Reduction blocks aKode, add a rule exclusion. If Controlled Folder Access blocks aKode, allow the app.
✓ runtime running local build on darwin-arm64
✓ install consistent
managed by npm: no · bun: no · pnpm: no · Vite+: no · package root —
✓ search search is OK (bundled)
✓ git git version 2.54.0
selected git /usr/bin/git
version git version 2.54.0
repo detected true
⚠ git this worktree is not on a Windows Dev Drive — create a trusted Windows Dev Drive: https://learn.microsoft.com/en-us/windows/dev-drive/
⚠ terminal narrow terminal
✓ title default · project codex
title source default
title items activity, project-name
project value codex
✓ state state paths inspectable
Configuration
✓ config loaded
feature flags 0 enabled · 0 overridden
configured TUI mode fullscreen
✗ auth token expired — Run `akode login`.
OPENAI_API_KEY present
Desktop App
✓ desktop the desktop application is installed
version 1.2.3
running true
log directory $HOME/Library/Logs/com.openai.codex
✓ desktop the desktop app-server initialized successfully
Updates
✓ updates update configuration is locally consistent
desktop update status ready to install
desktop latest build 123
Connectivity
✓ network network environment readable
✗ network provider is unreachable — A macOS system proxy is configured but unused. If your organization requires it, ask your administrator whether to enable the experimental System proxy setting in `/experimental` or with `akode features enable respect_system_proxy`. Restart aKode after changing this setting.
✓ websocket Responses WebSocket handshake succeeded
✓ reachability active provider endpoints are reachable over HTTP
Background Server
✓ app-server background server is not running
─────────────────────────────────────────────────────────────
16 ok · 6 notes · 3 warn · 2 fail failed
--summary compact output --all expand truncated lists
--json redacted report

View File

@@ -0,0 +1,23 @@
---
source: cli/src/doctor/output.rs
expression: "render_human_report(&report, detailed_all_no_color_unicode_options())"
---
aKode Doctor v0.0.0
Notes
⚠ mcp missing inputs
─────────────────────────────────────────────────────────────
Configuration
⚠ mcp missing inputs
demo bearer token env var DOCS_TOKEN is not set
DEMO header env var DOCS_SECRET is not set
stdio env var DOCS_TOKEN is not set
npm:@modelcontextprotocol/server-sequential.thinking env var DOCS_TOKEN is not set
typo bearer token env var <redacted> is not set
─────────────────────────────────────────────────────────────
0 ok · 1 notes · 1 warn · 0 fail degraded
--summary compact output --all expand truncated lists
--json redacted report

View File

@@ -0,0 +1,182 @@
use std::collections::BTreeMap;
use std::env;
use super::DoctorCheck;
use super::LOCALE_ENV_VARS;
const EDITOR_ENV_VARS: &[&str] = &["VISUAL", "EDITOR"];
const PAGER_ENV_VARS: &[&str] = &["PAGER", "GIT_PAGER", "GH_PAGER", "LESS"];
#[derive(Clone, Debug, Default, Eq, PartialEq)]
struct SystemCheckInputs {
os: String,
os_type: String,
os_version: String,
os_language: Option<String>,
locale_env: BTreeMap<String, String>,
editor_env: BTreeMap<String, String>,
pager_env: BTreeMap<String, String>,
}
impl SystemCheckInputs {
fn detect() -> Self {
let info = os_info::get();
let locale_env = LOCALE_ENV_VARS
.iter()
.filter_map(|name| {
env::var(name)
.ok()
.map(|value| ((*name).to_string(), value))
})
.collect();
let editor_env = EDITOR_ENV_VARS
.iter()
.map(|name| {
let value = env::var_os(name)
.map(|value| value.to_string_lossy().into_owned())
.unwrap_or_else(|| "not set".to_string());
((*name).to_string(), value)
})
.collect();
let pager_env = PAGER_ENV_VARS
.iter()
.filter_map(|name| {
env::var_os(name)
.map(|value| ((*name).to_string(), value.to_string_lossy().into_owned()))
})
.collect();
Self {
os: info.to_string(),
os_type: info.os_type().to_string(),
os_version: info.version().to_string(),
os_language: sys_locale::get_locale(),
locale_env,
editor_env,
pager_env,
}
}
}
pub(super) fn system_check() -> DoctorCheck {
system_check_from_inputs(SystemCheckInputs::detect())
}
fn system_check_from_inputs(inputs: SystemCheckInputs) -> DoctorCheck {
let mut details = vec![
format!("os: {}", inputs.os),
format!("os type: {}", inputs.os_type),
format!("os version: {}", inputs.os_version),
];
if let Some(language) = inputs.os_language.as_deref() {
details.push(format!("os language: {language}"));
} else {
details.push("os language: unavailable".to_string());
}
for name in LOCALE_ENV_VARS {
if let Some(value) = inputs.locale_env.get(*name) {
details.push(format!("{name}: {value}"));
}
}
for name in EDITOR_ENV_VARS {
if let Some(value) = inputs.editor_env.get(*name) {
details.push(format!("{name}: {value}"));
}
}
for name in PAGER_ENV_VARS {
if let Some(value) = inputs.pager_env.get(*name) {
details.push(format!("{name}: {value}"));
}
}
let summary = inputs
.os_language
.as_deref()
.map(|language| format!("OS language {language}"))
.unwrap_or_else(|| "OS language unavailable".to_string());
DoctorCheck::new(
"system.environment",
"system",
super::CheckStatus::Ok,
summary,
)
.details(details)
}
#[cfg(test)]
mod tests {
use pretty_assertions::assert_eq;
use super::*;
#[test]
fn system_check_reports_os_language_locale_editor_and_pager_env() {
let mut locale_env = BTreeMap::new();
locale_env.insert("LANG".to_string(), "en_US.UTF-8".to_string());
let editor_env = BTreeMap::from([
("EDITOR".to_string(), "vim".to_string()),
("VISUAL".to_string(), "code --wait".to_string()),
]);
let pager_env = BTreeMap::from([
("GH_PAGER".to_string(), "less".to_string()),
("GIT_PAGER".to_string(), "delta".to_string()),
("LESS".to_string(), "-FRX".to_string()),
("PAGER".to_string(), "less -R".to_string()),
]);
let check = system_check_from_inputs(SystemCheckInputs {
os: "macOS 15.0".to_string(),
os_type: "macos".to_string(),
os_version: "15.0".to_string(),
os_language: Some("en-US".to_string()),
locale_env,
editor_env,
pager_env,
});
assert_eq!(check.summary, "OS language en-US");
assert_eq!(
check.details,
vec![
"os: macOS 15.0",
"os type: macos",
"os version: 15.0",
"os language: en-US",
"LANG: en_US.UTF-8",
"VISUAL: code --wait",
"EDITOR: vim",
"PAGER: less -R",
"GIT_PAGER: delta",
"GH_PAGER: less",
"LESS: -FRX",
]
);
}
#[test]
fn system_check_handles_missing_os_language() {
let check = system_check_from_inputs(SystemCheckInputs {
os: "Linux".to_string(),
os_type: "linux".to_string(),
os_version: "unknown".to_string(),
os_language: None,
locale_env: BTreeMap::new(),
editor_env: BTreeMap::from([
("EDITOR".to_string(), "not set".to_string()),
("VISUAL".to_string(), "not set".to_string()),
]),
pager_env: BTreeMap::new(),
});
assert_eq!(check.summary, "OS language unavailable");
assert_eq!(
check.details,
vec![
"os: Linux",
"os type: linux",
"os version: unknown",
"os language: unavailable",
"VISUAL: not set",
"EDITOR: not set",
]
);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,423 @@
use std::collections::HashSet;
use std::path::Path;
use std::path::PathBuf;
use akode_config::ConfigLayerSource;
use akode_core::config::Config;
use akode_git_utils::get_git_repo_root;
use unicode_segmentation::UnicodeSegmentation;
use super::CheckStatus;
use super::DoctorCheck;
const DEFAULT_TERMINAL_TITLE_ITEMS: &[&str] = &["activity", "project-name"];
const PROJECT_TITLE_MAX_CHARS: usize = 24;
#[derive(Clone, Debug, Eq, PartialEq)]
struct TerminalTitleInputs {
configured_items: Option<Vec<String>>,
cwd: PathBuf,
project_root: Option<ProjectTitleRoot>,
}
#[derive(Clone, Debug, Eq, PartialEq)]
struct ProjectTitleRoot {
source: &'static str,
path: PathBuf,
}
pub(super) fn terminal_title_check(config: &Config) -> DoctorCheck {
terminal_title_check_from_inputs(TerminalTitleInputs {
configured_items: config.tui_terminal_title.clone(),
cwd: config.cwd.to_path_buf(),
project_root: terminal_title_project_root(config, &config.cwd),
})
}
fn terminal_title_check_from_inputs(inputs: TerminalTitleInputs) -> DoctorCheck {
let (source, items, invalid_items) = match inputs.configured_items {
Some(items) if items.is_empty() => ("disabled", Vec::new(), Vec::new()),
Some(items) => {
let (items, invalid_items) = parse_terminal_title_items(items);
("configured", items, invalid_items)
}
None => (
"default",
DEFAULT_TERMINAL_TITLE_ITEMS
.iter()
.map(ToString::to_string)
.collect(),
Vec::new(),
),
};
let mut details = vec![
format!("terminal title source: {source}"),
format!(
"terminal title items: {}",
if items.is_empty() {
"none".to_string()
} else {
items.join(", ")
}
),
format!("terminal title activity: {}", activity_enabled(&items)),
];
if !invalid_items.is_empty() {
details.push(format!(
"terminal title invalid items: {}",
invalid_items.join(", ")
));
}
if project_title_selected(&items) {
let (project_source, project_value) =
project_title_candidate(inputs.project_root, &inputs.cwd);
details.push(format!("terminal title project source: {project_source}"));
if let Some(project_value) = project_value {
details.push(format!("terminal title project value: {project_value}"));
}
}
let status = if invalid_items.is_empty() {
CheckStatus::Ok
} else {
CheckStatus::Warning
};
let summary = if invalid_items.is_empty() {
format!("terminal title {source}")
} else {
format!("terminal title {source} with invalid items")
};
let mut check = DoctorCheck::new("terminal.title", "title", status, summary).details(details);
if !invalid_items.is_empty() {
check = check.issue(
super::DoctorIssue::new(
CheckStatus::Warning,
"terminal title configuration contains unknown item identifiers",
)
.measured(invalid_items.join(", "))
.expected("known terminal title item identifiers")
.remedy("Remove or replace the unknown entries in [tui].terminal_title.")
.field("terminal title invalid items"),
);
}
check
}
fn parse_terminal_title_items(items: Vec<String>) -> (Vec<String>, Vec<String>) {
let mut invalid = Vec::new();
let mut invalid_seen = HashSet::new();
let mut parsed = Vec::new();
for item in items {
match terminal_title_item_id(&item) {
Some(id) => parsed.push(id.to_string()),
None => {
if invalid_seen.insert(item.clone()) {
invalid.push(format!(r#""{item}""#));
}
}
}
}
(parsed, invalid)
}
fn terminal_title_item_id(item: &str) -> Option<&'static str> {
match item {
"app-name" => Some("app-name"),
"project-name" | "project" => Some("project-name"),
"current-dir" => Some("current-dir"),
"activity" | "spinner" => Some("activity"),
"run-state" | "status" => Some("run-state"),
"thread-title" | "thread" => Some("thread-title"),
"git-branch" => Some("git-branch"),
"context-remaining" => Some("context-remaining"),
"context-used" | "context-usage" => Some("context-used"),
"five-hour-limit" => Some("five-hour-limit"),
"weekly-limit" => Some("weekly-limit"),
"thread-credits" => Some("thread-credits"),
"estimated-thread-cost" => Some("estimated-thread-cost"),
"codex-version" => Some("codex-version"),
"used-tokens" => Some("used-tokens"),
"total-input-tokens" => Some("total-input-tokens"),
"total-output-tokens" => Some("total-output-tokens"),
"thread-id" | "session-id" => Some("thread-id"),
"fast-mode" => Some("fast-mode"),
"model" | "model-name" => Some("model"),
"model-with-reasoning" => Some("model-with-reasoning"),
"reasoning" => Some("reasoning"),
"task-progress" => Some("task-progress"),
_ => None,
}
}
fn activity_enabled(items: &[String]) -> bool {
items
.iter()
.any(|item| item == "activity" || item == "spinner")
}
fn project_title_selected(items: &[String]) -> bool {
items
.iter()
.any(|item| item == "project-name" || item == "project")
}
fn terminal_title_project_root(config: &Config, cwd: &Path) -> Option<ProjectTitleRoot> {
if let Some(repo_root) = get_git_repo_root(cwd) {
return Some(ProjectTitleRoot {
source: "git repo root",
path: repo_root,
});
}
config
.config_layer_stack
.all_layers_low_to_high()
.find_map(|layer| match &layer.name {
ConfigLayerSource::Project { dot_codex_folder } => dot_codex_folder
.as_path()
.parent()
.map(|root| ProjectTitleRoot {
source: "project config",
path: root.to_path_buf(),
}),
_ => None,
})
}
fn project_title_candidate(
project_root: Option<ProjectTitleRoot>,
cwd: &Path,
) -> (&'static str, Option<String>) {
if let Some(project_root) = project_root {
return (
project_root.source,
Some(truncate_title_part(path_display_name(&project_root.path))),
);
}
("cwd", Some(truncate_title_part(path_display_name(cwd))))
}
fn path_display_name(path: &Path) -> String {
path.file_name()
.map(|name| name.to_string_lossy().to_string())
.unwrap_or_else(|| path.display().to_string())
}
fn truncate_title_part(value: String) -> String {
let mut graphemes = value.graphemes(true);
let head = graphemes
.by_ref()
.take(PROJECT_TITLE_MAX_CHARS)
.collect::<String>();
if graphemes.next().is_none() || PROJECT_TITLE_MAX_CHARS <= 3 {
return head;
}
let mut truncated = head
.graphemes(true)
.take(PROJECT_TITLE_MAX_CHARS - 3)
.collect::<String>();
truncated.push_str("...");
truncated
}
#[cfg(test)]
mod tests {
use pretty_assertions::assert_eq;
use super::*;
#[test]
fn terminal_title_reports_default_items_and_git_project_name() {
let check = terminal_title_check_from_inputs(TerminalTitleInputs {
configured_items: None,
cwd: PathBuf::from("/repo/subdir"),
project_root: Some(ProjectTitleRoot {
source: "git repo root",
path: PathBuf::from("/repo"),
}),
});
assert_eq!(check.summary, "terminal title default");
assert!(
check
.details
.contains(&"terminal title items: activity, project-name".to_string())
);
assert!(
check
.details
.contains(&"terminal title project source: git repo root".to_string())
);
assert!(
check
.details
.contains(&"terminal title project value: repo".to_string())
);
}
#[test]
fn terminal_title_reports_disabled_configuration() {
let check = terminal_title_check_from_inputs(TerminalTitleInputs {
configured_items: Some(Vec::new()),
cwd: PathBuf::from("/workspace"),
project_root: None,
});
assert_eq!(check.summary, "terminal title disabled");
assert!(
check
.details
.contains(&"terminal title items: none".to_string())
);
assert!(
check
.details
.contains(&"terminal title activity: false".to_string())
);
assert!(
!check
.details
.iter()
.any(|detail| detail.starts_with("terminal title project "))
);
}
#[test]
fn terminal_title_reports_project_config_fallback() {
let check = terminal_title_check_from_inputs(TerminalTitleInputs {
configured_items: Some(vec!["project".to_string()]),
cwd: PathBuf::from("/workspace/project/subdir"),
project_root: Some(ProjectTitleRoot {
source: "project config",
path: PathBuf::from("/workspace/project"),
}),
});
assert_eq!(check.summary, "terminal title configured");
assert!(
check
.details
.contains(&"terminal title project source: project config".to_string())
);
assert!(
check
.details
.contains(&"terminal title project value: project".to_string())
);
}
#[test]
fn terminal_title_accepts_configured_items() {
let check = terminal_title_check_from_inputs(TerminalTitleInputs {
configured_items: Some(vec![
"thread-credits".to_string(),
"estimated-thread-cost".to_string(),
"fast-mode".to_string(),
]),
cwd: PathBuf::from("/workspace/project"),
project_root: None,
});
assert_eq!(check.status, CheckStatus::Ok);
assert_eq!(check.summary, "terminal title configured");
assert!(check.details.contains(
&"terminal title items: thread-credits, estimated-thread-cost, fast-mode".to_string()
));
assert!(check.issues.is_empty());
}
#[test]
fn terminal_title_omits_project_when_project_item_is_not_selected() {
let check = terminal_title_check_from_inputs(TerminalTitleInputs {
configured_items: Some(vec!["model".to_string()]),
cwd: PathBuf::from("/workspace/project"),
project_root: Some(ProjectTitleRoot {
source: "project config",
path: PathBuf::from("/workspace/project"),
}),
});
assert_eq!(check.summary, "terminal title configured");
assert!(
!check
.details
.iter()
.any(|detail| detail.starts_with("terminal title project "))
);
}
#[test]
fn terminal_title_warns_for_invalid_configured_items() {
let check = terminal_title_check_from_inputs(TerminalTitleInputs {
configured_items: Some(vec![
"project".to_string(),
"bogus".to_string(),
"activity".to_string(),
"bogus".to_string(),
]),
cwd: PathBuf::from("/workspace/project"),
project_root: Some(ProjectTitleRoot {
source: "project config",
path: PathBuf::from("/workspace/project"),
}),
});
assert_eq!(check.status, CheckStatus::Warning);
assert_eq!(
check.summary,
"terminal title configured with invalid items"
);
assert!(
check
.details
.contains(&"terminal title items: project-name, activity".to_string())
);
assert!(
check
.details
.contains(&r#"terminal title invalid items: "bogus""#.to_string())
);
assert_eq!(check.issues.len(), 1);
}
#[test]
fn terminal_title_warns_when_all_configured_items_are_invalid() {
let check = terminal_title_check_from_inputs(TerminalTitleInputs {
configured_items: Some(vec!["bogus".to_string()]),
cwd: PathBuf::from("/workspace/project"),
project_root: None,
});
assert_eq!(check.status, CheckStatus::Warning);
assert!(
check
.details
.contains(&"terminal title items: none".to_string())
);
assert!(
check
.details
.contains(&r#"terminal title invalid items: "bogus""#.to_string())
);
}
#[test]
fn terminal_title_project_value_uses_tui_truncation_shape() {
let check = terminal_title_check_from_inputs(TerminalTitleInputs {
configured_items: Some(vec!["project".to_string()]),
cwd: PathBuf::from("/workspace/abcdefghijklmnopqrstuvwxyz"),
project_root: Some(ProjectTitleRoot {
source: "project config",
path: PathBuf::from("/workspace/abcdefghijklmnopqrstuvwxyz"),
}),
});
assert!(
check
.details
.contains(&"terminal title project value: abcdefghijklmnopqrstu...".to_string())
);
}
}

View File

@@ -0,0 +1,121 @@
//! Diagnoses whether Codex update paths target the running installation.
//!
//! aKode: diagnostics are local only (cached version metadata and install-channel hints).
//! There are no latest-version probes (GitHub, Homebrew) and no desktop appcast probes.
use std::path::Path;
use akode_core::config::Config;
use akode_install_context::InstallContext;
use akode_install_context::InstallMethod;
use serde::Deserialize;
use super::CheckStatus;
use super::DoctorCheck;
use super::doctor_install_context;
use super::doctor_managed_by_npm;
const VERSION_FILE_NAME: &str = "version.json";
/// Builds the update-health row for the current installation from local state only.
pub(super) async 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);
if doctor_managed_by_npm(current_exe.as_deref()) {
details
.push("npm update target: not inspected (PATH helpers are not executed)".to_string());
}
details.push("latest version probe: disabled (no network update checks)".to_string());
DoctorCheck::new(
"updates.status",
"updates",
CheckStatus::Ok,
"update configuration is locally consistent",
)
.details(details)
}
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.method {
InstallMethod::Npm => "npm install -g @openai/codex",
InstallMethod::Bun => "bun install -g @openai/codex",
InstallMethod::VitePlus => "vp install -g @openai/codex",
InstallMethod::Pnpm => "pnpm add -g @openai/codex",
InstallMethod::Brew => "brew upgrade --cask codex",
InstallMethod::Standalone { .. } => "standalone installer",
InstallMethod::Other => "manual or unknown",
}
}
#[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::*;
use pretty_assertions::assert_eq;
#[test]
fn update_action_labels_install_contexts() {
assert_eq!(
update_action_label(&InstallContext {
method: InstallMethod::Npm,
package_layout: None,
}),
"npm install -g @openai/codex"
);
assert_eq!(
update_action_label(&InstallContext {
method: InstallMethod::Pnpm,
package_layout: None,
}),
"pnpm add -g @openai/codex"
);
assert_eq!(
update_action_label(&InstallContext {
method: InstallMethod::Other,
package_layout: None,
}),
"manual or unknown"
);
}
}

View File

@@ -0,0 +1,160 @@
use std::ffi::OsString;
use std::fs::OpenOptions;
use std::io;
use std::os::windows::ffi::OsStrExt;
use std::os::windows::ffi::OsStringExt;
use std::os::windows::fs::OpenOptionsExt;
use std::os::windows::io::AsRawHandle;
use std::path::Path;
use std::path::PathBuf;
use std::ptr;
use akode_git_utils::get_git_repo_root;
use os_info::Version;
use windows_sys::Win32::Foundation::ERROR_INVALID_PARAMETER;
use windows_sys::Win32::Storage::FileSystem::FILE_FLAG_BACKUP_SEMANTICS;
use windows_sys::Win32::Storage::FileSystem::FILE_READ_ATTRIBUTES;
use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_READ;
use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_WRITE;
use windows_sys::Win32::Storage::FileSystem::GetDriveTypeW;
use windows_sys::Win32::Storage::FileSystem::GetVolumePathNameW;
use windows_sys::Win32::System::IO::DeviceIoControl;
use windows_sys::Win32::System::WindowsProgramming::DRIVE_FIXED;
use windows_sys::Win32::System::WindowsProgramming::DRIVE_NO_ROOT_DIR;
use windows_sys::Win32::System::WindowsProgramming::DRIVE_UNKNOWN;
use super::CheckStatus;
use super::DoctorCheck;
const ID: &str = "git.worktree.dev_drive";
const DEV_VOLUME: u32 = 0x0000_2000;
const TRUSTED_VOLUME: u32 = 0x0000_4000;
const QUERY_PERSISTENT_VOLUME_STATE: u32 = 0x0009_023c;
#[repr(C)]
struct PersistentVolumeState {
flags: u32,
mask: u32,
version: u32,
reserved: u32,
}
pub(super) fn check(cwd: &Path) -> DoctorCheck {
let Some(worktree) = get_git_repo_root(cwd) else {
return DoctorCheck::new(ID, "git", CheckStatus::Ok, "no Git worktree is active");
};
if matches!(
os_info::get().version(),
Version::Semantic(_, _, build) if *build < 22_621
) {
return DoctorCheck::new(
ID,
"git",
CheckStatus::Ok,
"Windows Dev Drives are unavailable on this Windows version",
);
}
match volume_flags(&worktree) {
Ok(flags) if flags & DEV_VOLUME == 0 => DoctorCheck::new(
ID,
"git",
CheckStatus::Warning,
"this worktree is not on a Windows Dev Drive; moving it to a trusted Dev Drive can significantly improve repository and filesystem performance",
)
.remediation(
"create a trusted Windows Dev Drive for source repositories: https://learn.microsoft.com/en-us/windows/dev-drive/",
),
Ok(flags) if flags & TRUSTED_VOLUME == 0 => DoctorCheck::new(
ID,
"git",
CheckStatus::Warning,
"the active Git worktree is on an untrusted Windows Dev Drive",
)
.remediation(
"ask your administrator to trust the Windows Dev Drive: https://learn.microsoft.com/en-us/windows/dev-drive/#how-do-i-designate-a-dev-drive-as-trusted",
),
Ok(_) => DoctorCheck::new(
ID,
"git",
CheckStatus::Ok,
"the active Git worktree is on a trusted Windows Dev Drive",
),
Err(error) => DoctorCheck::new(
ID,
"git",
CheckStatus::Warning,
"the active Git worktree's Windows Dev Drive state could not be inspected",
)
.detail(format!("filesystem error: {:?}", error.kind()))
.remediation("check access to the Git worktree and its Windows storage volume"),
}
}
fn volume_flags(path: &Path) -> io::Result<u32> {
let path = path
.as_os_str()
.encode_wide()
.chain(std::iter::once(0))
.collect::<Vec<_>>();
let mut volume = vec![0_u16; path.len().max(261)];
if unsafe { GetVolumePathNameW(path.as_ptr(), volume.as_mut_ptr(), volume.len() as u32) } == 0 {
return Err(io::Error::last_os_error());
}
match unsafe { GetDriveTypeW(volume.as_ptr()) } {
DRIVE_UNKNOWN | DRIVE_NO_ROOT_DIR => {
return Err(io::Error::new(
io::ErrorKind::NotFound,
"the Windows storage volume could not be determined",
));
}
DRIVE_FIXED => {}
_ => return Ok(0),
}
let length = volume
.iter()
.position(|character| *character == 0)
.unwrap_or(volume.len());
let root = PathBuf::from(OsString::from_wide(&volume[..length]));
let handle = OpenOptions::new()
.access_mode(FILE_READ_ATTRIBUTES)
.share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE)
.custom_flags(FILE_FLAG_BACKUP_SEMANTICS)
.open(root)?;
let mut state = PersistentVolumeState {
flags: 0,
mask: DEV_VOLUME | TRUSTED_VOLUME,
version: 1,
reserved: 0,
};
let state_size = std::mem::size_of::<PersistentVolumeState>() as u32;
let state_ptr = ptr::from_mut(&mut state);
let mut bytes_returned = 0;
if unsafe {
DeviceIoControl(
handle.as_raw_handle(),
QUERY_PERSISTENT_VOLUME_STATE,
state_ptr.cast_const().cast(),
state_size,
state_ptr.cast(),
state_size,
&mut bytes_returned,
ptr::null_mut(),
)
} == 0
{
let error = io::Error::last_os_error();
return if error.raw_os_error() == Some(ERROR_INVALID_PARAMETER as i32) {
Ok(0)
} else {
Err(error)
};
}
Ok(state.flags)
}
#[cfg(test)]
#[path = "windows_dev_drive_tests.rs"]
mod tests;

View File

@@ -0,0 +1,16 @@
use std::path::PathBuf;
use pretty_assertions::assert_eq;
use super::DEV_VOLUME;
use super::volume_flags;
#[test]
fn the_windows_system_volume_is_not_a_dev_drive() {
let system_root = std::env::var_os("SystemRoot")
.map(PathBuf::from)
.expect("Windows exposes its system directory");
let flags = volume_flags(&system_root).expect("the system volume can be inspected");
assert_eq!(flags & DEV_VOLUME, 0);
}

View File

@@ -0,0 +1,29 @@
#![cfg(test)]
use super::*;
use clap::error::ErrorKind;
use pretty_assertions::assert_eq;
#[test]
fn exec_server_help_documents_remote_options() {
let command = MultitoolCli::command()
.term_width(80)
.mut_subcommand("exec-server", |command| {
command
.mut_arg("exit_on_stdin_close", |arg| arg.hide_env_values(true))
.mut_arg("proxy_private_ips_via_upstream", |arg| {
arg.hide_env_values(true)
})
});
let help = command
.try_get_matches_from(["codex", "exec-server", "--help"])
.expect_err("help should exit before running the executor");
assert_eq!(help.kind(), ErrorKind::DisplayHelp);
let help_text = help
.to_string()
.lines()
.map(str::trim_end)
.collect::<Vec<_>>()
.join("\n");
insta::assert_snapshot!(help_text);
}

View File

@@ -0,0 +1,23 @@
#[cfg(unix)]
pub(crate) fn handle_exit_status(status: std::process::ExitStatus) -> ! {
use std::os::unix::process::ExitStatusExt;
// Use ExitStatus to derive the exit code.
if let Some(code) = status.code() {
std::process::exit(code);
} else if let Some(signal) = status.signal() {
std::process::exit(128 + signal);
} else {
std::process::exit(1);
}
}
#[cfg(windows)]
pub(crate) fn handle_exit_status(status: std::process::ExitStatus) -> ! {
if let Some(code) = status.code() {
std::process::exit(code);
} else {
// Rare on Windows, but if it happens: use fallback code.
std::process::exit(1);
}
}

188
akode-rs/cli/src/lib.rs Normal file
View File

@@ -0,0 +1,188 @@
pub(crate) mod debug_sandbox;
mod exit_status;
pub mod local_config;
pub(crate) mod login;
use clap::Args;
use clap::Parser;
use akode_utils_absolute_path::AbsolutePathBuf;
use akode_utils_cli::CliConfigOverrides;
use akode_utils_cli::ProfileV2Name;
use std::path::PathBuf;
pub use debug_sandbox::run_command_under_landlock;
pub use debug_sandbox::run_command_under_seatbelt;
pub use debug_sandbox::run_command_under_windows_sandbox;
pub use login::read_api_key_from_stdin;
pub use login::run_login_provider_api_key;
pub use login::run_login_status;
pub use login::run_login_with_api_key;
pub use login::run_logout;
pub use login::run_logout_provider;
#[derive(Debug, Default, Args)]
pub struct SandboxStateArgs {
/// Opaque JSON value from `codex/sandbox-state` to apply directly.
#[arg(
long = "sandbox-state-json",
value_name = "JSON",
conflicts_with_all = ["permissions_profile", "cwd", "include_managed_config"]
)]
pub sandbox_state_json: Option<String>,
/// Add a readable root to the supplied sandbox state. Repeat for multiple roots.
#[arg(
long,
requires = "sandbox_state_json",
value_parser = parse_absolute_path
)]
pub sandbox_state_readable_root: Vec<AbsolutePathBuf>,
/// Disable direct network access in the supplied sandbox state.
#[arg(long, requires = "sandbox_state_json", default_value_t = false)]
pub sandbox_state_disable_network: bool,
}
// These command structs share common sandbox options, but remain separate
// because each host backend has a slightly different option surface.
#[derive(Debug, Parser)]
pub struct SeatbeltCommand {
#[command(flatten)]
pub sandbox_state: SandboxStateArgs,
/// Named permissions profile to apply from the active configuration stack.
#[arg(
long = "permission-profile",
alias = "permissions-profile",
short = 'P',
value_name = "NAME"
)]
pub permissions_profile: Option<String>,
/// Layer $AKODE_HOME/<name>.config.toml on top of the base user config.
#[arg(long = "profile", short = 'p')]
pub config_profile: Option<ProfileV2Name>,
/// Working directory used for profile resolution and command execution.
#[arg(
short = 'C',
long = "cd",
value_name = "DIR",
requires = "permissions_profile"
)]
pub cwd: Option<PathBuf>,
/// Include managed requirements while resolving an explicit permissions profile.
#[arg(
long = "include-managed-config",
default_value_t = false,
requires = "permissions_profile"
)]
pub include_managed_config: bool,
/// Allow the sandboxed command to bind/connect AF_UNIX sockets rooted at this path. Relative paths are resolved against the current directory. Repeat to allow multiple paths.
#[arg(long = "allow-unix-socket", value_parser = parse_absolute_path)]
pub allow_unix_sockets: Vec<AbsolutePathBuf>,
/// While the command runs, capture macOS sandbox denials via `log stream` and print them after exit
#[arg(long = "log-denials", default_value_t = false)]
pub log_denials: bool,
#[clap(skip)]
pub config_overrides: CliConfigOverrides,
/// Full command args to run under seatbelt.
#[arg(trailing_var_arg = true)]
pub command: Vec<String>,
}
fn parse_absolute_path(raw: &str) -> Result<AbsolutePathBuf, String> {
AbsolutePathBuf::relative_to_current_dir(raw)
.map_err(|err| format!("invalid path {raw}: {err}"))
}
#[derive(Debug, Parser)]
pub struct LandlockCommand {
#[command(flatten)]
pub sandbox_state: SandboxStateArgs,
/// Named permissions profile to apply from the active configuration stack.
#[arg(
long = "permission-profile",
alias = "permissions-profile",
short = 'P',
value_name = "NAME"
)]
pub permissions_profile: Option<String>,
/// Layer $AKODE_HOME/<name>.config.toml on top of the base user config.
#[arg(long = "profile", short = 'p')]
pub config_profile: Option<ProfileV2Name>,
/// Working directory used for profile resolution and command execution.
#[arg(
short = 'C',
long = "cd",
value_name = "DIR",
requires = "permissions_profile"
)]
pub cwd: Option<PathBuf>,
/// Include managed requirements while resolving an explicit permissions profile.
#[arg(
long = "include-managed-config",
default_value_t = false,
requires = "permissions_profile"
)]
pub include_managed_config: bool,
#[clap(skip)]
pub config_overrides: CliConfigOverrides,
/// Full command args to run under the Linux sandbox.
#[arg(trailing_var_arg = true)]
pub command: Vec<String>,
}
#[derive(Debug, Parser)]
pub struct WindowsCommand {
#[command(flatten)]
pub sandbox_state: SandboxStateArgs,
/// Named permissions profile to apply from the active configuration stack.
#[arg(
long = "permission-profile",
alias = "permissions-profile",
short = 'P',
value_name = "NAME"
)]
pub permissions_profile: Option<String>,
/// Layer $AKODE_HOME/<name>.config.toml on top of the base user config.
#[arg(long = "profile", short = 'p')]
pub config_profile: Option<ProfileV2Name>,
/// Working directory used for profile resolution and command execution.
#[arg(
short = 'C',
long = "cd",
value_name = "DIR",
requires = "permissions_profile"
)]
pub cwd: Option<PathBuf>,
/// Include managed requirements while resolving an explicit permissions profile.
#[arg(
long = "include-managed-config",
default_value_t = false,
requires = "permissions_profile"
)]
pub include_managed_config: bool,
#[clap(skip)]
pub config_overrides: CliConfigOverrides,
/// Full command args to run under Windows restricted token sandbox.
#[arg(trailing_var_arg = true)]
pub command: Vec<String>,
}

View File

@@ -0,0 +1,53 @@
use anyhow::Context;
use anyhow::Result;
use akode_app_server::in_process::EmbeddedNetworkPolicy;
use akode_core::config::Config;
use akode_core::config::ConfigBuilder;
use akode_core::config::ConfigOverrides;
use akode_core::config::LoaderOverrides;
use akode_core::config::find_codex_home;
use akode_utils_absolute_path::AbsolutePathBuf;
use akode_utils_cli::CliConfigOverrides;
pub async fn load_config(
config_overrides: &CliConfigOverrides,
loader_overrides: LoaderOverrides,
) -> Result<Config> {
let mut config = config_builder(
config_overrides,
loader_overrides,
ConfigOverrides::default(),
)
.await?
.build()
.await
.context("failed to load configuration")?;
config.config_layer_stack.ensure_config_server_applied()?;
EmbeddedNetworkPolicy::default().activate(&mut config);
Ok(config)
}
/// Builds a config from local files only; aKode never fetches managed config
/// bundles from a remote service.
pub async fn config_builder(
config_overrides: &CliConfigOverrides,
loader_overrides: LoaderOverrides,
harness_overrides: ConfigOverrides,
) -> Result<ConfigBuilder> {
let cli_overrides = config_overrides
.parse_overrides()
.map_err(anyhow::Error::msg)?;
let codex_home = find_codex_home().context("failed to resolve AKODE_HOME")?;
let cwd = match harness_overrides.cwd.as_deref() {
Some(cwd) => AbsolutePathBuf::relative_to_current_dir(cwd),
None => AbsolutePathBuf::current_dir(),
}
.context("failed to resolve current directory")?;
Ok(ConfigBuilder::default()
.codex_home(codex_home.to_path_buf())
.cli_overrides(cli_overrides)
.loader_overrides(loader_overrides)
.harness_overrides(harness_overrides)
.fallback_cwd(Some(cwd.to_path_buf())))
}

400
akode-rs/cli/src/login.rs Normal file
View File

@@ -0,0 +1,400 @@
//! CLI login commands and their direct-user observability surfaces.
//!
//! The TUI path already installs a broader tracing stack with feedback, OpenTelemetry, and other
//! interactive-session layers. Direct `akode login` intentionally does less: it preserves the
//! existing stderr/browser UX and adds only a small file-backed tracing layer for login-specific
//! targets. Keeping that setup local avoids pulling the TUI's session-oriented logging machinery
//! into a one-shot CLI command while still producing a durable `akode-login.log` artifact that
//! support can request from users.
use akode_core::config::Config;
use akode_login::login_with_api_key;
use akode_protocol::auth::AuthMode;
use akode_protocol::config_types::ForcedLoginMethod;
use akode_utils_cli::CliConfigOverrides;
use std::fs::OpenOptions;
use std::io::IsTerminal;
use std::io::Read;
use tracing_appender::non_blocking;
use tracing_appender::non_blocking::WorkerGuard;
use tracing_subscriber::EnvFilter;
use tracing_subscriber::Layer;
use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;
const API_KEY_LOGIN_DISABLED_MESSAGE: &str =
"API key login is disabled by the configured login restrictions.";
const API_KEY_AUTHENTICATION_NOTICE: &str = "Authentication is checked when you send a request.";
const DEFAULT_LOGIN_LOG_FILTER: &str =
"akode_cli=info,akode_core=info,akode_login=info,akode_otel::auth_storage=warn";
/// Installs a small file-backed tracing layer for direct `akode login` flows.
///
/// This deliberately duplicates a narrow slice of the TUI logging setup instead of reusing it
/// wholesale. The TUI stack includes session-oriented layers that are valuable for interactive
/// runs but unnecessary for a one-shot login command. Keeping the direct CLI path local lets this
/// command produce a durable `akode-login.log` artifact without coupling it to the TUI's broader
/// telemetry and feedback initialization.
fn init_login_file_logging(config: &Config) -> Option<WorkerGuard> {
let log_dir = match akode_core::config::log_dir(config) {
Ok(log_dir) => log_dir,
Err(err) => {
eprintln!("Warning: failed to resolve login log directory: {err}");
return None;
}
};
if let Err(err) = std::fs::create_dir_all(&log_dir) {
eprintln!(
"Warning: failed to create login log directory {}: {err}",
log_dir.display()
);
return None;
}
let mut log_file_opts = OpenOptions::new();
log_file_opts.create(true).append(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
log_file_opts.mode(0o600);
}
let log_path = log_dir.join("akode-login.log");
let log_file = match log_file_opts.open(&log_path) {
Ok(log_file) => log_file,
Err(err) => {
eprintln!(
"Warning: failed to open login log file {}: {err}",
log_path.display()
);
return None;
}
};
let (non_blocking, guard) = non_blocking(log_file);
let env_filter = EnvFilter::try_from_default_env()
.unwrap_or_else(|_| EnvFilter::new(DEFAULT_LOGIN_LOG_FILTER));
let file_layer = tracing_subscriber::fmt::layer()
.with_writer(non_blocking)
.with_target(true)
.with_ansi(false)
.with_filter(env_filter);
// Direct `akode login` otherwise relies on ephemeral stderr and browser output.
// Persist the same login targets to a file so support can inspect auth failures
// without reproducing them through TUI or app-server.
if let Err(err) = tracing_subscriber::registry().with(file_layer).try_init() {
eprintln!(
"Warning: failed to initialize login log file {}: {err}",
log_path.display()
);
return None;
}
Some(guard)
}
/// Remote managed configuration (config server / cloud bundles) is not
/// supported in aKode: requirements that demand it cannot be satisfied.
async fn sign_in_to_config_server_and_reload_config(
_config: &mut Config,
_cli_config_overrides: &CliConfigOverrides,
) -> std::io::Result<()> {
Err(std::io::Error::new(
std::io::ErrorKind::Unsupported,
"remote managed configuration is not supported in aKode",
))
}
fn finish_login(result: std::io::Result<()>) -> ! {
match result {
Ok(_) => std::process::exit(0),
Err(e) => {
eprintln!("Error logging in: {e}");
std::process::exit(1);
}
}
}
pub async fn run_login_with_api_key(
cli_config_overrides: CliConfigOverrides,
api_key: String,
) -> ! {
let config = load_managed_login_config_or_exit(cli_config_overrides).await;
let _login_log_guard = init_login_file_logging(&config);
tracing::info!("starting api key login flow");
if !config
.auth_config()
.is_login_method_allowed(ForcedLoginMethod::Api)
{
eprintln!("{API_KEY_LOGIN_DISABLED_MESSAGE}");
std::process::exit(1);
}
match login_with_api_key(
&config.codex_home,
&api_key,
config.cli_auth_credentials_store_mode,
config.auth_keyring_backend_kind(),
) {
Ok(_) => {
eprintln!("API key saved. {API_KEY_AUTHENTICATION_NOTICE}");
std::process::exit(0);
}
Err(e) => {
eprintln!("Error logging in: {e}");
std::process::exit(1);
}
}
}
pub fn read_api_key_from_stdin() -> String {
read_stdin_secret(
"--with-api-key expects the API key on stdin. Try piping it, e.g. `printenv OPENAI_API_KEY | akode login --with-api-key`.",
"Reading API key from stdin...",
"No API key provided via stdin.",
)
}
fn read_stdin_secret(terminal_message: &str, reading_message: &str, empty_message: &str) -> String {
let mut stdin = std::io::stdin();
if stdin.is_terminal() {
eprintln!("{terminal_message}");
std::process::exit(1);
}
eprintln!("{reading_message}");
let mut buffer = String::new();
if let Err(err) = stdin.read_to_string(&mut buffer) {
eprintln!("Failed to read stdin: {err}");
std::process::exit(1);
}
let secret = buffer.trim().to_string();
if secret.is_empty() {
eprintln!("{empty_message}");
std::process::exit(1);
}
secret
}
/// Stores the API key of one model provider (`api_key = "keyring"`) in the configured
/// provider key store (system keyring, or the private fallback file).
pub async fn run_login_provider_api_key(
cli_config_overrides: CliConfigOverrides,
provider_id: String,
api_key: String,
) -> ! {
let config = load_config_or_exit(cli_config_overrides).await;
let _login_log_guard = init_login_file_logging(&config);
tracing::info!("storing a provider API key");
match config.model_providers.get(&provider_id) {
Some(provider)
if provider.api_key
== Some(akode_model_provider_info::ProviderApiKeySource::Keyring) => {}
Some(_) => eprintln!(
"Warning: model_providers.{provider_id} does not set api_key = \"keyring\"; the stored key is used only after you add it."
),
None => eprintln!(
"Warning: model provider `{provider_id}` is not defined in config.toml yet; add [model_providers.{provider_id}] with api_key = \"keyring\"."
),
}
match akode_model_provider_info::save_provider_api_key(&provider_id, &api_key) {
Ok(location) => {
eprintln!(
"API key for `{provider_id}` saved in {location}. {API_KEY_AUTHENTICATION_NOTICE}"
);
std::process::exit(0);
}
Err(error) => {
eprintln!("Error saving the API key: {error}");
std::process::exit(1);
}
}
}
/// Removes the stored API key of one model provider.
pub async fn run_logout_provider(
cli_config_overrides: CliConfigOverrides,
provider_id: String,
) -> ! {
let _config = load_config_or_exit(cli_config_overrides).await;
match akode_model_provider_info::delete_provider_api_key(&provider_id) {
Ok(true) => eprintln!("Removed the stored API key for `{provider_id}`"),
Ok(false) => eprintln!("No API key is stored for `{provider_id}`"),
Err(error) => {
eprintln!("Error removing the API key: {error}");
std::process::exit(1);
}
}
std::process::exit(0);
}
/// Prints where each `api_key = "keyring"` provider key is stored (never the key itself).
/// Returns whether any provider key is available.
fn print_provider_key_status(config: &Config) -> bool {
let mut any = false;
let mut ids = config.model_providers.keys().collect::<Vec<_>>();
ids.sort();
for id in ids {
let provider = &config.model_providers[id];
if provider.api_key == Some(akode_model_provider_info::ProviderApiKeySource::Keyring) {
match akode_model_provider_info::locate_provider_api_key(id) {
Ok(Some(location)) => {
any = true;
eprintln!("Provider `{id}`: API key stored in {location}");
}
Ok(None) => eprintln!(
"Provider `{id}`: no API key stored (akode login --provider {id} --with-api-key)"
),
Err(error) => eprintln!("Provider `{id}`: cannot read the key store: {error}"),
}
} else if let Some(env_key) = &provider.env_key {
let present = std::env::var(env_key).is_ok_and(|value| !value.trim().is_empty());
any |= present;
eprintln!(
"Provider `{id}`: API key from ${env_key} ({})",
if present { "set" } else { "not set" }
);
}
}
any
}
/// Login using the OAuth device code flow.
pub async fn run_login_status(cli_config_overrides: CliConfigOverrides) -> ! {
let config = load_config_or_exit(cli_config_overrides).await;
let auth_config = config.auth_config();
match auth_config
.load_auth(/*enable_codex_api_key_env*/ false)
.await
{
Ok(Some(auth)) => match auth.auth_mode() {
AuthMode::ApiKey => match auth.get_token() {
Ok(api_key) => {
eprintln!("API key configured - {}", safe_format_key(&api_key));
print_provider_key_status(&config);
eprintln!("{API_KEY_AUTHENTICATION_NOTICE}");
std::process::exit(0);
}
Err(e) => {
eprintln!("Unexpected error retrieving API key: {e}");
std::process::exit(1);
}
},
AuthMode::Headers => {
unreachable!("header auth cannot be loaded from auth storage")
}
},
Ok(None) => {
if print_provider_key_status(&config) {
std::process::exit(0);
}
eprintln!("Not logged in");
std::process::exit(1);
}
Err(err) => {
eprintln!("Error checking login status: {err}");
std::process::exit(1);
}
}
}
pub async fn run_logout(cli_config_overrides: CliConfigOverrides) -> ! {
let config = load_config_or_exit(cli_config_overrides).await;
let logged_out = match akode_login::logout(
&config.codex_home,
config.cli_auth_credentials_store_mode,
config.auth_keyring_backend_kind(),
) {
Ok(logged_out) => logged_out,
Err(err) => {
eprintln!("Error logging out: {err}");
std::process::exit(1);
}
};
if logged_out {
eprintln!("Successfully logged out");
} else {
eprintln!("Not logged in");
}
std::process::exit(0);
}
async fn load_managed_login_config_or_exit(cli_config_overrides: CliConfigOverrides) -> Config {
let mut config = load_config_or_exit(cli_config_overrides.clone()).await;
if config
.config_layer_stack
.requirements_toml()
.requires_remote_config()
&& let Err(error) =
sign_in_to_config_server_and_reload_config(&mut config, &cli_config_overrides).await
{
finish_login(Err(error));
}
config
}
async fn load_config_or_exit(cli_config_overrides: CliConfigOverrides) -> Config {
let cli_overrides = match cli_config_overrides.parse_overrides() {
Ok(v) => v,
Err(e) => {
eprintln!("Error parsing -c overrides: {e}");
std::process::exit(1);
}
};
match Config::load_with_cli_overrides(cli_overrides).await {
Ok(config) => match config.auth_config().validate() {
Ok(()) => config,
Err(e) => {
eprintln!("Error loading configuration: {e}");
std::process::exit(1);
}
},
Err(e) => {
eprintln!("Error loading configuration: {e}");
std::process::exit(1);
}
}
}
fn safe_format_key(key: &str) -> String {
if key.len() <= 13 {
return "***".to_string();
}
let prefix = &key[..8];
let suffix = &key[key.len() - 5..];
format!("{prefix}***{suffix}")
}
#[cfg(test)]
#[path = "login_storage_tests.rs"]
mod storage_tests;
#[cfg(test)]
mod tests {
use pretty_assertions::assert_eq;
use super::safe_format_key;
#[test]
fn formats_long_key() {
let key = "sk-proj-1234567890ABCDE";
assert_eq!(safe_format_key(key), "sk-proj-***ABCDE");
}
#[test]
fn short_key_returns_stars() {
let key = "sk-proj-12345";
assert_eq!(safe_format_key(key), "***");
}
}

View File

@@ -0,0 +1,87 @@
//! Verifies storage failures remain visible in direct login diagnostics.
use super::DEFAULT_LOGIN_LOG_FILTER;
use akode_config::types::AuthCredentialsStoreMode;
use akode_login::AuthKeyringBackendKind;
use akode_login::login_with_api_key;
use pretty_assertions::assert_eq;
use tempfile::tempdir;
use tracing_subscriber::EnvFilter;
#[test]
fn login_default_filter_records_sanitized_storage_fallback() -> anyhow::Result<()> {
let home = tempdir()?;
// Fail before accessing the real keyring, then allow the plaintext fallback to succeed.
std::fs::write(home.path().join("secrets"), "not a directory")?;
let log_path = home.path().join("login.log");
let subscriber = tracing_subscriber::fmt()
.without_time()
.with_ansi(false)
.with_env_filter(EnvFilter::new(DEFAULT_LOGIN_LOG_FILTER))
.with_writer(std::fs::File::create(&log_path)?)
.finish();
tracing::subscriber::with_default(subscriber, || {
login_with_api_key(
home.path(),
"private-api-key",
AuthCredentialsStoreMode::Auto,
AuthKeyringBackendKind::Secrets,
)
})?;
let logs = std::fs::read_to_string(log_path)?;
assert_eq!(logs.lines().count(), 2);
let failure = logs.lines().next().unwrap();
assert!(
failure.contains("failed to save auth to keyring, falling back to file storage"),
"{logs}"
);
assert!(failure.contains("failed to create secrets dir"), "{logs}");
assert!(
logs.contains("credential storage file fallback completed"),
"{logs}"
);
assert!(logs.contains("fallback_reason=\"secure_error\""), "{logs}");
assert!(logs.contains("outcome=\"success\""), "{logs}");
assert!(!logs.contains("private-api-key"));
let completion = logs.lines().last().unwrap();
assert!(!completion.contains(home.path().to_str().unwrap()));
let cause = std::fs::create_dir_all(home.path().join("secrets"))
.unwrap_err()
.to_string();
insta::assert_snapshot!(
logs.replace(
home.path().join("secrets").to_str().unwrap(),
"[SECRETS_PATH]"
)
.replace(&cause, "[OS_ERROR]")
);
Ok(())
}
#[test]
fn login_storage_error_displays_context_and_cause() -> anyhow::Result<()> {
let home = tempdir()?;
let secrets_path = home.path().join("secrets");
std::fs::write(&secrets_path, "not a directory")?;
let cause = std::fs::create_dir_all(&secrets_path)
.unwrap_err()
.to_string();
let error = login_with_api_key(
home.path(),
"private-api-key",
AuthCredentialsStoreMode::Keyring,
AuthKeyringBackendKind::Secrets,
)
.unwrap_err();
let message = error.to_string();
assert!(message.contains(&cause), "{message}");
assert!(!message.contains("private-api-key"));
// The temporary path and native filesystem error differ across platforms.
insta::assert_snapshot!(
message
.replace(secrets_path.to_str().unwrap(), "[SECRETS_PATH]")
.replace(&cause, "[OS_ERROR]")
);
Ok(())
}

4771
akode-rs/cli/src/main.rs Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,587 @@
use anyhow::Context;
use anyhow::Result;
use anyhow::bail;
use clap::Parser;
use akode_core::config::Config;
use akode_core::config::ConfigOverrides;
use akode_core::config::LoaderOverrides;
use akode_core::plugins_manager_for_config;
use akode_core_plugins::PluginMarketplaceUpgradeOutcome;
use akode_core_plugins::PluginsConfigInput;
use akode_core_plugins::installed_marketplaces::marketplace_install_root;
use akode_core_plugins::installed_marketplaces::resolve_configured_marketplace_root;
use akode_core_plugins::marketplace::marketplace_root_dir;
use akode_core_plugins::marketplace_add::MarketplaceAddOutcome;
use akode_core_plugins::marketplace_add::MarketplaceAddRequest;
use akode_core_plugins::marketplace_add::add_marketplace;
use akode_core_plugins::marketplace_remove::MarketplaceRemoveOutcome;
use akode_core_plugins::marketplace_remove::MarketplaceRemoveRequest;
use akode_core_plugins::marketplace_remove::remove_marketplace;
use akode_utils_cli::CliConfigOverrides;
use serde::Serialize;
use std::collections::HashMap;
use std::collections::HashSet;
use std::path::Path;
use std::path::PathBuf;
use crate::local_config;
use crate::plugin_cmd::JsonMarketplaceSource;
use crate::plugin_cmd::configured_marketplace_snapshot_issues;
use crate::plugin_cmd::configured_marketplace_sources;
use crate::plugin_cmd::load_cli_auth_manager;
#[derive(Debug, Parser)]
#[command(bin_name = "akode plugin marketplace")]
pub struct MarketplaceCli {
#[clap(flatten)]
pub config_overrides: CliConfigOverrides,
#[command(subcommand)]
subcommand: MarketplaceSubcommand,
}
#[derive(Debug, clap::Subcommand)]
enum MarketplaceSubcommand {
/// Add a local or Git marketplace to the configured marketplace sources.
Add(AddMarketplaceArgs),
/// List plugin marketplaces aKode is currently considering and their roots.
List(ListMarketplaceArgs),
/// Refresh configured Git marketplace snapshots.
///
/// Omit MARKETPLACE_NAME to upgrade all configured Git marketplaces.
Upgrade(UpgradeMarketplaceArgs),
/// Remove a configured marketplace source by name.
Remove(RemoveMarketplaceArgs),
}
#[derive(Debug, Parser)]
#[command(
bin_name = "akode plugin marketplace add",
after_help = "Examples:\n akode plugin marketplace add ./path/to/marketplace\n akode plugin marketplace add owner/repo --ref main\n akode plugin marketplace add https://github.com/owner/repo --sparse plugins/foo"
)]
struct AddMarketplaceArgs {
/// Marketplace source: a local path, owner/repo[@ref], HTTPS Git URL, or SSH Git URL.
#[arg(value_name = "SOURCE")]
source: String,
/// Git ref to fetch for Git marketplace sources.
#[arg(long = "ref", value_name = "REF")]
ref_name: Option<String>,
/// Sparse checkout path for Git marketplace sources. Can be repeated.
#[arg(
long = "sparse",
value_name = "PATH",
action = clap::ArgAction::Append
)]
sparse_paths: Vec<String>,
/// Output add result as JSON.
#[arg(long = "json")]
json: bool,
}
#[derive(Debug, Parser)]
#[command(bin_name = "akode plugin marketplace list")]
struct ListMarketplaceArgs {
/// Output marketplace list as JSON.
#[arg(long = "json")]
json: bool,
}
#[derive(Debug, Parser)]
#[command(
bin_name = "akode plugin marketplace upgrade",
after_help = "Examples:\n akode plugin marketplace upgrade\n akode plugin marketplace upgrade debug"
)]
struct UpgradeMarketplaceArgs {
/// Optional configured marketplace name to upgrade. Omit to upgrade all Git marketplaces.
#[arg(value_name = "MARKETPLACE_NAME")]
marketplace_name: Option<String>,
/// Output upgrade result as JSON.
#[arg(long = "json")]
json: bool,
}
#[derive(Debug, Parser)]
#[command(
bin_name = "akode plugin marketplace remove",
after_help = "Example:\n akode plugin marketplace remove debug"
)]
struct RemoveMarketplaceArgs {
/// Configured marketplace name to remove.
#[arg(value_name = "MARKETPLACE_NAME")]
marketplace_name: String,
/// Output remove result as JSON.
#[arg(long = "json")]
json: bool,
}
impl MarketplaceCli {
pub async fn run(self) -> Result<()> {
let MarketplaceCli {
config_overrides,
subcommand,
} = self;
let builder = local_config::config_builder(
&config_overrides,
LoaderOverrides::default(),
ConfigOverrides::default(),
)
.await?;
let config = builder.clone().build().await?;
match subcommand {
MarketplaceSubcommand::Add(args) => run_add(config, args).await?,
MarketplaceSubcommand::List(args) => run_list(config, args).await?,
MarketplaceSubcommand::Upgrade(args) => run_upgrade(config, args, builder).await?,
MarketplaceSubcommand::Remove(args) => run_remove(config, args).await?,
}
Ok(())
}
}
async fn run_add(config: Config, args: AddMarketplaceArgs) -> Result<()> {
let AddMarketplaceArgs {
source,
ref_name,
sparse_paths,
json,
} = args;
let outcome = add_marketplace(
config.codex_home.to_path_buf(),
config.config_layer_stack.requirements().clone(),
MarketplaceAddRequest {
source,
ref_name,
sparse_paths,
},
)
.await?;
if json {
let output = JsonMarketplaceAddOutput::from_outcome(outcome);
println!("{}", serde_json::to_string_pretty(&output)?);
return Ok(());
}
if outcome.already_added {
println!(
"Marketplace `{}` is already added from {}.",
outcome.marketplace_name, outcome.source_display
);
} else {
println!(
"Added marketplace `{}` from {}.",
outcome.marketplace_name, outcome.source_display
);
}
println!(
"Installed marketplace root: {}",
outcome.installed_root.as_path().display()
);
Ok(())
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct JsonMarketplaceAddOutput {
marketplace_name: String,
installed_root: String,
already_added: bool,
}
impl JsonMarketplaceAddOutput {
fn from_outcome(outcome: MarketplaceAddOutcome) -> Self {
Self {
marketplace_name: outcome.marketplace_name,
installed_root: outcome.installed_root.as_path().display().to_string(),
already_added: outcome.already_added,
}
}
}
async fn run_list(config: Config, args: ListMarketplaceArgs) -> Result<()> {
let manager = plugins_manager_for_config(&config, load_cli_auth_manager(&config).await?);
let plugins_input = config.plugins_config_input();
let marketplace_listing = manager
.discover_marketplaces_for_config(&plugins_input, &[])
.context("failed to list plugin marketplaces")?;
let mut load_issues = configured_marketplace_snapshot_issues(
config.codex_home.as_path(),
&plugins_input,
&marketplace_listing.errors,
/*marketplace_name*/ None,
);
let mut issue_paths = load_issues
.iter()
.map(|issue| issue.path.clone())
.collect::<HashSet<_>>();
for error in &marketplace_listing.errors {
if issue_paths.insert(error.path.to_path_buf()) {
load_issues.push(crate::plugin_cmd::ConfiguredMarketplaceSnapshotIssue {
marketplace_name: error.path.display().to_string(),
path: error.path.to_path_buf(),
message: error.message.clone(),
});
}
}
if !load_issues.is_empty() {
let issue_lines = load_issues
.iter()
.map(|issue| {
format!(
"- `{}` at {}: {}",
issue.marketplace_name,
issue.path.display(),
issue.message
)
})
.collect::<Vec<_>>()
.join("\n");
bail!("failed to load marketplace(s):\n{issue_lines}");
}
let marketplaces = marketplace_listing.marketplaces;
if args.json {
let marketplace_sources =
configured_marketplace_sources_by_root(config.codex_home.as_path(), &plugins_input);
let output =
JsonMarketplaceListOutput::from_marketplaces(marketplaces, &marketplace_sources);
println!("{}", serde_json::to_string_pretty(&output)?);
return Ok(());
}
if marketplaces.is_empty() {
println!("No plugin marketplaces in scope.");
return Ok(());
}
let mut seen_roots = HashSet::new();
let mut rows = Vec::new();
for marketplace in marketplaces {
let Ok(root) = marketplace_root_dir(&marketplace.path) else {
continue;
};
if !seen_roots.insert(root.clone()) {
continue;
}
rows.push((marketplace.name, root));
}
let marketplace_width = rows
.iter()
.map(|(name, _)| name.len())
.max()
.unwrap_or("MARKETPLACE".len())
.max("MARKETPLACE".len());
println!("{:<marketplace_width$} ROOT", "MARKETPLACE");
for (marketplace_name, root) in rows {
println!(
"{:<marketplace_width$} {}",
marketplace_name,
root.display()
);
}
Ok(())
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct JsonMarketplaceListOutput {
marketplaces: Vec<JsonMarketplaceListEntry>,
}
impl JsonMarketplaceListOutput {
fn from_marketplaces(
marketplaces: Vec<akode_core_plugins::marketplace::Marketplace>,
marketplace_sources: &HashMap<PathBuf, JsonMarketplaceSource>,
) -> Self {
let mut seen_roots = HashSet::new();
let marketplaces = marketplaces
.into_iter()
.filter_map(|marketplace| {
let root = marketplace_root_dir(&marketplace.path).ok()?;
if !seen_roots.insert(root.clone()) {
return None;
}
Some(JsonMarketplaceListEntry {
marketplace_source: marketplace_sources.get(root.as_path()).cloned(),
name: marketplace.name,
root: root.display().to_string(),
})
})
.collect();
Self { marketplaces }
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct JsonMarketplaceListEntry {
name: String,
root: String,
#[serde(skip_serializing_if = "Option::is_none")]
marketplace_source: Option<JsonMarketplaceSource>,
}
fn configured_marketplace_sources_by_root(
codex_home: &Path,
plugins_input: &PluginsConfigInput,
) -> HashMap<PathBuf, JsonMarketplaceSource> {
let marketplace_sources = configured_marketplace_sources(plugins_input, codex_home);
let effective_config = plugins_input.config_layer_stack.effective_config();
let Some(marketplaces) = effective_config
.get("marketplaces")
.and_then(toml::Value::as_table)
else {
return HashMap::new();
};
let default_install_root = marketplace_install_root(codex_home);
marketplaces
.iter()
.filter_map(|(marketplace_name, marketplace)| {
let marketplace_source = marketplace_sources.get(marketplace_name)?;
let root = resolve_configured_marketplace_root(
marketplace_name,
marketplace,
&default_install_root,
)?;
Some((root, marketplace_source.clone()))
})
.collect()
}
async fn run_upgrade(
config: Config,
args: UpgradeMarketplaceArgs,
builder: akode_core::config::ConfigBuilder,
) -> Result<()> {
let UpgradeMarketplaceArgs {
marketplace_name,
json,
} = args;
let manager = plugins_manager_for_config(&config, load_cli_auth_manager(&config).await?);
let plugins_input = config.plugins_config_input();
let runtime = tokio::runtime::Handle::current();
let reload_config: akode_core_plugins::ConfigLayerReload = std::sync::Arc::new(move || {
runtime
.block_on(builder.clone().build())
.map(|config| config.config_layer_stack)
});
let requested_name = marketplace_name.clone();
let outcome = tokio::task::spawn_blocking(move || {
manager.upgrade_configured_marketplaces_for_config(
&plugins_input,
requested_name.as_deref(),
&reload_config,
)
})
.await?
.map_err(anyhow::Error::msg)?;
if json {
print_upgrade_outcome_json(&outcome)
} else {
print_upgrade_outcome(&outcome, marketplace_name.as_deref())
}
}
async fn run_remove(config: Config, args: RemoveMarketplaceArgs) -> Result<()> {
let RemoveMarketplaceArgs {
marketplace_name,
json,
} = args;
let outcome = remove_marketplace(
config.codex_home.to_path_buf(),
config.config_layer_stack,
MarketplaceRemoveRequest { marketplace_name },
)
.await?;
if json {
let output = JsonMarketplaceRemoveOutput::from_outcome(outcome);
println!("{}", serde_json::to_string_pretty(&output)?);
return Ok(());
}
println!("Removed marketplace `{}`.", outcome.marketplace_name);
if let Some(installed_root) = outcome.removed_installed_root {
println!(
"Removed installed marketplace root: {}",
installed_root.as_path().display()
);
}
Ok(())
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct JsonMarketplaceRemoveOutput {
marketplace_name: String,
installed_root: Option<String>,
}
impl JsonMarketplaceRemoveOutput {
fn from_outcome(outcome: MarketplaceRemoveOutcome) -> Self {
Self {
marketplace_name: outcome.marketplace_name,
installed_root: outcome
.removed_installed_root
.map(|root| root.as_path().display().to_string()),
}
}
}
fn print_upgrade_outcome_json(outcome: &PluginMarketplaceUpgradeOutcome) -> Result<()> {
for error in &outcome.errors {
eprintln!(
"Failed to upgrade marketplace `{}`: {}",
error.marketplace_name, error.message
);
}
if !outcome.all_succeeded() {
bail!("{} upgrade failure(s) occurred.", outcome.errors.len());
}
let output = JsonMarketplaceUpgradeOutput::from_outcome(outcome);
println!("{}", serde_json::to_string_pretty(&output)?);
Ok(())
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct JsonMarketplaceUpgradeOutput {
selected_marketplaces: Vec<String>,
upgraded_roots: Vec<String>,
errors: Vec<JsonMarketplaceUpgradeError>,
}
impl JsonMarketplaceUpgradeOutput {
fn from_outcome(outcome: &PluginMarketplaceUpgradeOutcome) -> Self {
Self {
selected_marketplaces: outcome.selected_marketplaces.clone(),
upgraded_roots: outcome
.upgraded_roots
.iter()
.map(|root| root.display().to_string())
.collect(),
errors: outcome
.errors
.iter()
.map(|error| JsonMarketplaceUpgradeError {
marketplace_name: error.marketplace_name.clone(),
message: error.message.clone(),
})
.collect(),
}
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct JsonMarketplaceUpgradeError {
marketplace_name: String,
message: String,
}
fn print_upgrade_outcome(
outcome: &PluginMarketplaceUpgradeOutcome,
marketplace_name: Option<&str>,
) -> Result<()> {
for error in &outcome.errors {
eprintln!(
"Failed to upgrade marketplace `{}`: {}",
error.marketplace_name, error.message
);
}
if !outcome.all_succeeded() {
bail!("{} upgrade failure(s) occurred.", outcome.errors.len());
}
let selection_label = marketplace_name.unwrap_or("all configured Git marketplaces");
if outcome.selected_marketplaces.is_empty() {
println!("No configured Git marketplaces to upgrade.");
} else if outcome.upgraded_roots.is_empty() {
if marketplace_name.is_some() {
println!("Marketplace `{selection_label}` is already up to date.");
} else {
println!("All configured Git marketplaces are already up to date.");
}
} else if marketplace_name.is_some() {
println!("Upgraded marketplace `{selection_label}` to the latest configured revision.");
for root in &outcome.upgraded_roots {
println!("Installed marketplace root: {}", root.display());
}
} else {
println!("Upgraded {} marketplace(s).", outcome.upgraded_roots.len());
for root in &outcome.upgraded_roots {
println!("Installed marketplace root: {}", root.display());
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn sparse_paths_parse_before_or_after_source() {
let sparse_before_source =
AddMarketplaceArgs::try_parse_from(["add", "--sparse", "plugins/foo", "owner/repo"])
.unwrap();
assert_eq!(sparse_before_source.source, "owner/repo");
assert_eq!(sparse_before_source.sparse_paths, vec!["plugins/foo"]);
let sparse_after_source =
AddMarketplaceArgs::try_parse_from(["add", "owner/repo", "--sparse", "plugins/foo"])
.unwrap();
assert_eq!(sparse_after_source.source, "owner/repo");
assert_eq!(sparse_after_source.sparse_paths, vec!["plugins/foo"]);
let repeated_sparse = AddMarketplaceArgs::try_parse_from([
"add",
"--sparse",
"plugins/foo",
"--sparse",
"skills/bar",
"owner/repo",
])
.unwrap();
assert_eq!(repeated_sparse.source, "owner/repo");
assert_eq!(
repeated_sparse.sparse_paths,
vec!["plugins/foo", "skills/bar"]
);
}
#[test]
fn upgrade_subcommand_parses_optional_marketplace_name() {
let upgrade_all = UpgradeMarketplaceArgs::try_parse_from(["upgrade"]).unwrap();
assert_eq!(upgrade_all.marketplace_name, None);
let upgrade_one = UpgradeMarketplaceArgs::try_parse_from(["upgrade", "debug"]).unwrap();
assert_eq!(upgrade_one.marketplace_name.as_deref(), Some("debug"));
}
#[test]
fn remove_subcommand_parses_marketplace_name() {
let remove = RemoveMarketplaceArgs::try_parse_from(["remove", "debug"]).unwrap();
assert_eq!(remove.marketplace_name, "debug");
}
}

1132
akode-rs/cli/src/mcp_cmd.rs Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,346 @@
//! Verifies MCP argument handling and managed networking in standalone commands.
use clap::Parser;
use akode_http_client::ClientRouteClass;
use akode_http_client::HttpError;
use akode_http_client::NetworkPolicyDenied;
use pretty_assertions::assert_eq;
use std::path::PathBuf;
use std::time::Duration;
use tokio::process::Command;
use tokio::time::timeout;
use super::McpCli;
use super::McpSubcommand;
#[test]
fn oauth_client_secret_is_redacted_in_parsed_command_debug() {
let cli = McpCli::try_parse_from([
"mcp",
"add",
"private",
"--url",
"https://example.com/mcp",
"--oauth-client-id",
"registered-client",
"--oauth-client-secret",
"cli-secret-marker",
])
.expect("parse confidential client arguments");
let debug = format!("{cli:?}");
assert!(!debug.contains("cli-secret-marker"));
assert!(debug.contains("oauth_client_secret: Some(<redacted>)"));
let McpSubcommand::Add(add) = cli.subcommand else {
panic!("expected MCP add");
};
let http = add.transport_args.streamable_http.expect("HTTP arguments");
assert_eq!(
http.oauth_client_secret
.as_ref()
.map(|secret| secret.as_str()),
Some("cli-secret-marker")
);
}
#[test]
fn oauth_client_secret_requires_url_and_client_id_without_disclosure() {
for args in [
vec!["--url", "https://example.com/mcp"],
vec!["--oauth-client-id", "registered-client"],
] {
let error = McpCli::try_parse_from(
[
"mcp",
"add",
"private",
"--oauth-client-secret",
"cli-secret-marker",
]
.into_iter()
.chain(args),
)
.expect_err("client secret requires both HTTP URL and client ID");
assert_eq!(
error.kind(),
clap::error::ErrorKind::MissingRequiredArgument
);
assert!(!error.to_string().contains("cli-secret-marker"));
}
}
async fn isolated_test_home(test_name: &str) -> anyhow::Result<Option<PathBuf>> {
const CHILD: &str = "AKODE_MCP_NETWORK_TEST_CHILD";
let test_name = format!("mcp_cmd::tests::{test_name}");
if std::env::var(CHILD).as_deref() == Ok(test_name.as_str()) {
return Ok(Some(akode_core::config::find_codex_home()?.to_path_buf()));
}
// Only the child receives the temporary home; the production loader resolves
// AKODE_HOME normally and the parent test process keeps its environment.
let home = tempfile::tempdir()?;
let output = timeout(
Duration::from_secs(45),
Command::new(std::env::current_exe()?)
.args(["--exact", &test_name, "--nocapture"])
.kill_on_drop(true)
.env(CHILD, &test_name)
.env("AKODE_HOME", home.path())
.env("NO_PROXY", "127.0.0.1,localhost")
.env("no_proxy", "127.0.0.1,localhost")
.env_remove("OPENAI_API_KEY")
.env_remove("AKODE_API_KEY")
.env_remove("AKODE_ACCESS_TOKEN")
.current_dir(home.path())
.output(),
)
.await??;
let stdout = String::from_utf8_lossy(&output.stdout);
assert!(
output.status.success() && stdout.contains("1 passed; 0 failed"),
"{test_name}: {stdout}\n{}",
String::from_utf8_lossy(&output.stderr)
);
Ok(None)
}
async fn config_with_application_network(
home: &std::path::Path,
requirements: &str,
extra_config: &str,
) -> anyhow::Result<akode_core::config::Config> {
std::fs::write(
home.join("config.toml"),
format!(
"forced_login_method = 'api'\n\
cli_auth_credentials_store = 'file'\n\
mcp_oauth_credentials_store = 'file'\n\
[features]\nplugins = false\nrecommended_plugins = false\n\
{extra_config}"
),
)?;
let requirements_path = home.join("requirements.toml");
std::fs::write(&requirements_path, requirements)?;
crate::local_config::load_config(
&akode_utils_cli::CliConfigOverrides::default(),
akode_core::config::LoaderOverrides {
system_config_path: Some(home.join("absent-system-config.toml")),
system_requirements_path: Some(requirements_path),
ignore_project_config: true,
..codex_core::config::LoaderOverrides::without_managed_config_for_tests()
},
)
.await
}
fn http_add_args(url: &str) -> super::AddArgs {
let cli = McpCli::try_parse_from(["mcp", "add", "policy-probe", "--url", url])
.expect("parse HTTP add arguments");
let McpSubcommand::Add(args) = cli.subcommand else {
panic!("expected MCP add");
};
args
}
#[tokio::test]
async fn application_network_mcp_add_denies_initial_oauth_discovery_before_connect()
-> anyhow::Result<()> {
let Some(home) = isolated_test_home(
"application_network_mcp_add_denies_initial_oauth_discovery_before_connect",
)
.await?
else {
return Ok(());
};
let listener = std::net::TcpListener::bind("127.0.0.1:0")?;
listener.set_nonblocking(true)?;
let url = format!("https://{}/mcp", listener.local_addr()?);
let config = config_with_application_network(&home, "[application.network]\n", "").await?;
// Add deliberately saves the server when discovery is unknown. A successful
// command is therefore not evidence that its network request was permitted.
tokio::time::timeout(
std::time::Duration::from_secs(5),
super::run_add(&config, http_add_args(&url)),
)
.await??;
let saved: toml::Value = toml::from_str(&std::fs::read_to_string(home.join("config.toml"))?)?;
assert_eq!(
saved["mcp_servers"]["policy-probe"]["url"].as_str(),
Some(url.as_str())
);
// No accepted TCP connection also proves no HTTP discovery request arrived.
assert_eq!(
listener.accept().unwrap_err().kind(),
std::io::ErrorKind::WouldBlock
);
Ok(())
}
#[tokio::test]
async fn application_network_mcp_add_discovers_when_policy_is_disabled() -> anyhow::Result<()> {
let Some(home) =
isolated_test_home("application_network_mcp_add_discovers_when_policy_is_disabled").await?
else {
return Ok(());
};
let server = wiremock::MockServer::start().await;
wiremock::Mock::given(wiremock::matchers::any())
.respond_with(wiremock::ResponseTemplate::new(404))
.mount(&server)
.await;
let url = format!("{}/mcp", server.uri());
let config =
config_with_application_network(&home, "[application.network]\nenabled = false\n", "")
.await?;
tokio::time::timeout(
std::time::Duration::from_secs(5),
super::run_add(&config, http_add_args(&url)),
)
.await??;
let requests = server.received_requests().await.expect("recorded requests");
assert!(
requests.iter().any(|request| request.url.path() == "/mcp"),
"the positive control must perform real OAuth discovery"
);
// The 404 response has no OAuth support, so this cannot open a browser.
Ok(())
}
#[tokio::test]
async fn application_network_mcp_login_denies_even_an_allowed_mcp_server() -> anyhow::Result<()> {
let Some(home) =
isolated_test_home("application_network_mcp_login_denies_even_an_allowed_mcp_server")
.await?
else {
return Ok(());
};
let listener = std::net::TcpListener::bind("127.0.0.1:0")?;
listener.set_nonblocking(true)?;
let url = format!("https://{}/mcp", listener.local_addr()?);
let requirements =
format!("[application.network]\n[mcp_servers.policy-probe.identity]\nurl = {url:?}\n");
let extra_config = format!("[mcp_servers.policy-probe]\nurl = {url:?}\n");
let config = config_with_application_network(&home, &requirements, &extra_config).await?;
let server = &config.mcp_servers.get()["policy-probe"];
assert!(
server.enabled,
"MCP identity allowlist must permit this server"
);
assert!(server.disabled_reason.is_none());
let error = tokio::time::timeout(
std::time::Duration::from_secs(5),
super::run_login(
&config,
super::LoginArgs {
name: "policy-probe".to_string(),
no_browser: true,
scopes: Vec::new(),
oauth_client_registration: None,
},
),
)
.await?
.expect_err("MCP permission must not override application network restrictions");
let message = format!("{error:#}");
assert!(
message.contains("destination denied by application network policy"),
"{message}"
);
assert_eq!(
listener.accept().unwrap_err().kind(),
std::io::ErrorKind::WouldBlock
);
Ok(())
}
#[tokio::test]
async fn application_network_loader_denies_unlisted_destination_before_connect()
-> anyhow::Result<()> {
let Some(home) =
isolated_test_home("application_network_loader_denies_unlisted_destination_before_connect")
.await?
else {
return Ok(());
};
let listener = std::net::TcpListener::bind("127.0.0.1:0")?;
listener.set_nonblocking(true)?;
let url = format!("https://{}/must-not-connect", listener.local_addr()?);
let config = config_with_application_network(
&home,
"[application.network.domains]\n'allowed.example' = 'allow'\n",
"",
)
.await?;
let factory = config.http_client_factory();
factory
.network_policy()
.acquire(&"https://allowed.example/v1".parse()?)?;
let client = factory.build_client(&url, ClientRouteClass::Other)?;
assert!(matches!(
timeout(Duration::from_secs(2), client.get(&url).send()).await?,
Err(HttpError::Policy(NetworkPolicyDenied::Destination))
));
assert_eq!(
listener.accept().unwrap_err().kind(),
std::io::ErrorKind::WouldBlock
);
Ok(())
}
#[tokio::test]
async fn application_network_loader_allows_listed_https_destination_to_connect()
-> anyhow::Result<()> {
let Some(home) =
isolated_test_home("application_network_loader_allows_listed_https_destination_to_connect")
.await?
else {
return Ok(());
};
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
let url = format!("https://{}/allowed", listener.local_addr()?);
let config = config_with_application_network(
&home,
"[application.network.domains]\n'127.0.0.1' = 'allow'\n",
"",
)
.await?;
let client = config
.http_client_factory()
.build_client(&url, ClientRouteClass::Other)?;
let (response, connection) = timeout(Duration::from_secs(2), async {
tokio::join!(client.get(&url).send(), async {
let (stream, _) = listener.accept().await?;
// This listener proves TCP permission; it deliberately does not provide TLS.
drop(stream);
Ok::<_, std::io::Error>(())
})
})
.await?;
connection?;
assert!(response.is_err(), "the raw listener cannot complete TLS");
assert!(!matches!(response, Err(HttpError::Policy(_))));
Ok(())
}
#[tokio::test]
async fn application_network_loader_rejects_malformed_managed_policy() -> anyhow::Result<()> {
let Some(home) =
isolated_test_home("application_network_loader_rejects_malformed_managed_policy").await?
else {
return Ok(());
};
let error = config_with_application_network(
&home,
"[application.network.domains]\n'*.example.com' = 'allow'\n",
"",
)
.await
.expect_err("invalid application policy must not load as unrestricted");
let message = format!("{error:#}");
assert!(message.contains("requirements.toml"), "{message}");
assert!(
message.contains("application.network.domains requires exact ASCII domain names"),
"{message}"
);
Ok(())
}

View File

@@ -0,0 +1,266 @@
//! CLI MCP OAuth login modes and bounded, hidden callback input.
//!
//! Manual input remains cancellable while the OAuth flow waits for its HTTP
//! callback, and dropping terminal input restores the terminal immediately.
//! Ctrl-C also cancels token exchange and scope retries in manual login mode.
use std::collections::HashMap;
use std::io;
use std::io::BufRead;
use std::io::IsTerminal;
use std::io::Write;
use std::sync::Arc;
use anyhow::Context;
use anyhow::Result;
use anyhow::bail;
use akode_config::McpServerOAuthConfig;
use akode_config::types::AuthKeyringBackendKind;
use akode_config::types::OAuthCredentialsStoreMode;
use akode_exec_server::HttpClient;
use akode_mcp::ResolvedMcpOAuthScopes;
use akode_mcp::should_retry_without_scopes;
use akode_rmcp_client::McpOAuthClientRegistration;
use akode_rmcp_client::perform_oauth_login;
use akode_rmcp_client::perform_oauth_login_with_callback_input;
use crossterm::event::Event;
use crossterm::event::EventStream;
use crossterm::event::KeyCode;
use crossterm::event::KeyEventKind;
use crossterm::event::KeyModifiers;
use crossterm::terminal;
use futures::StreamExt;
use tokio::sync::oneshot;
const MAX_CALLBACK_BYTES: usize = 64 * 1024;
#[derive(Clone, Copy)]
pub(crate) enum McpLoginMode {
Browser,
PasteCallback,
}
/// Retry provider-rejected discovered scopes once, retaining the selected input mode.
#[allow(clippy::too_many_arguments)]
pub(crate) async fn perform_oauth_login_retry_without_scopes(
name: &str,
url: &str,
store_mode: OAuthCredentialsStoreMode,
keyring_backend_kind: AuthKeyringBackendKind,
http_headers: Option<HashMap<String, String>>,
env_http_headers: Option<HashMap<String, String>>,
resolved_scopes: &ResolvedMcpOAuthScopes,
oauth_config: Option<&McpServerOAuthConfig>,
client_registration: McpOAuthClientRegistration,
oauth_resource: Option<&str>,
callback_port: Option<u16>,
callback_url: Option<&str>,
global_callback_url: Option<&str>,
http_client: Arc<dyn HttpClient>,
mode: McpLoginMode,
) -> Result<()> {
let mut pending_input = None;
// Tokio retains its process-wide signal handler, so keep listening throughout
// token exchange and scope retries after the callback input reader is dropped.
let ctrl_c = tokio::signal::ctrl_c();
tokio::pin!(ctrl_c);
for (attempt, scopes) in [resolved_scopes.scopes.as_slice(), &[]]
.into_iter()
.enumerate()
{
let login = async {
match mode {
McpLoginMode::Browser => {
perform_oauth_login(
name,
url,
store_mode,
keyring_backend_kind,
http_headers.clone(),
env_http_headers.clone(),
scopes,
oauth_config,
client_registration,
oauth_resource,
callback_port,
callback_url,
global_callback_url,
Arc::clone(&http_client),
)
.await
}
McpLoginMode::PasteCallback => {
let input = &mut pending_input;
perform_oauth_login_with_callback_input(
name,
url,
store_mode,
keyring_backend_kind,
http_headers.clone(),
env_http_headers.clone(),
scopes,
oauth_config,
client_registration,
oauth_resource,
callback_port,
callback_url,
global_callback_url,
Arc::clone(&http_client),
move |authorization_url| read_callback(authorization_url, input),
)
.await
}
}
};
let result = tokio::select! {
result = login => result,
result = &mut ctrl_c, if matches!(mode, McpLoginMode::PasteCallback) => {
result.context("failed to listen for Ctrl-C")?;
bail!("OAuth login cancelled");
}
};
match result {
Err(error) if attempt == 0 && should_retry_without_scopes(resolved_scopes, &error) => {
println!("OAuth provider rejected discovered scopes. Retrying without scopes…");
}
result => return result,
}
}
unreachable!("the empty-scope attempt always returns")
}
async fn read_callback(
authorization_url: String,
pending_input: &mut Option<oneshot::Receiver<Result<String>>>,
) -> Result<String> {
println!(
"Authorize the MCP server by opening this URL in your browser:\n{authorization_url}\n"
);
println!(
"After signing in, copy the full URL from your browser's address bar.\n\
If the callback page cannot load, paste that URL here anyway."
);
if io::stdin().is_terminal() {
return read_terminal_callback().await;
}
print_callback_prompt()?;
// A pipe may stay open after the HTTP callback wins. A detached thread avoids
// making runtime shutdown wait for an uncancellable blocking stdin read.
// Retain an unfinished read if an HTTP provider error triggers a scope retry.
// Otherwise its detached reader could consume the next attempt's pasted URL.
if pending_input.is_none() {
let (tx, rx) = oneshot::channel();
std::thread::Builder::new()
.name("mcp-oauth-callback-input".to_string())
.spawn(move || {
let result = read_callback_line(io::stdin().lock());
let _ = tx.send(result);
})
.context("failed to start callback input reader")?;
*pending_input = Some(rx);
}
let reader = pending_input
.as_mut()
.context("callback input reader was unavailable")?;
let result = reader.await;
*pending_input = None;
result.context("callback input reader stopped")?
}
fn read_callback_line(reader: impl BufRead) -> Result<String> {
let mut bytes = Vec::new();
reader
.take((MAX_CALLBACK_BYTES + 3) as u64)
.read_until(b'\n', &mut bytes)
.context("failed to read callback URL")?;
if bytes.ends_with(b"\n") {
bytes.pop();
}
if bytes.ends_with(b"\r") {
bytes.pop();
}
if bytes.len() > MAX_CALLBACK_BYTES {
bail!("OAuth callback URL exceeds 64 KiB");
}
if bytes.is_empty() {
bail!("No OAuth callback URL received before input closed");
}
String::from_utf8(bytes).map_err(|_| anyhow::anyhow!("OAuth callback URL must be valid UTF-8"))
}
struct TerminalInputGuard;
impl Drop for TerminalInputGuard {
fn drop(&mut self) {
let _ = terminal::disable_raw_mode();
eprintln!();
}
}
fn print_callback_prompt() -> Result<()> {
eprint!("Callback URL (input hidden): ");
io::stderr()
.flush()
.context("failed to display callback prompt")
}
async fn read_terminal_callback() -> Result<String> {
terminal::enable_raw_mode().context("failed to hide callback input")?;
let _guard = TerminalInputGuard;
print_callback_prompt()?;
let mut events = EventStream::new();
let mut input = String::new();
loop {
let event = events
.next()
.await
.context("callback input stream closed")?
.context("failed to read callback input")?;
match event {
Event::Key(key) if key.kind != KeyEventKind::Release => match key.code {
KeyCode::Enter => {
if input.is_empty() {
bail!("No OAuth callback URL entered");
}
return Ok(input);
}
KeyCode::Char('c') if key.modifiers.contains(KeyModifiers::CONTROL) => {
bail!("OAuth login cancelled");
}
KeyCode::Char('d') if key.modifiers.contains(KeyModifiers::CONTROL) => {
bail!("No OAuth callback URL received before input closed");
}
KeyCode::Char('u') if key.modifiers.contains(KeyModifiers::CONTROL) => {
input.clear()
}
KeyCode::Backspace => {
input.pop();
}
KeyCode::Char(character)
if !character.is_control()
&& !key.modifiers.contains(KeyModifiers::CONTROL) =>
{
if input.len() + character.len_utf8() > MAX_CALLBACK_BYTES {
bail!("OAuth callback URL exceeds 64 KiB");
}
input.push(character);
}
_ => {}
},
Event::Paste(paste) => {
if input.len() + paste.len() > MAX_CALLBACK_BYTES {
bail!("OAuth callback URL exceeds 64 KiB");
}
input.push_str(&paste);
}
_ => {}
}
// Yield even with queued input so callback completion and timeout stay responsive.
tokio::task::yield_now().await;
}
}
#[cfg(test)]
#[path = "mcp_login_tests.rs"]
mod tests;

View File

@@ -0,0 +1,46 @@
//! Checks bounded callback input independently of terminal state.
use super::MAX_CALLBACK_BYTES;
use super::read_callback_line;
use pretty_assertions::assert_eq;
use std::io::Cursor;
#[test]
fn callback_line_accepts_crlf_and_eof_after_input() {
for input in [
"https://example.test/callback?code=abc\r\n",
"https://example.test/callback?code=abc",
] {
assert_eq!(
read_callback_line(Cursor::new(input)).expect("read callback URL"),
"https://example.test/callback?code=abc"
);
}
}
#[test]
fn callback_line_is_bounded_and_does_not_expose_input_in_errors() {
let maximum_input = "s".repeat(MAX_CALLBACK_BYTES);
assert_eq!(
read_callback_line(Cursor::new(format!("{maximum_input}\r\n"))).expect("bounded input"),
maximum_input
);
let input = "s".repeat(MAX_CALLBACK_BYTES + 1);
assert_eq!(
read_callback_line(Cursor::new(input))
.unwrap_err()
.to_string(),
"OAuth callback URL exceeds 64 KiB"
);
assert_eq!(
read_callback_line(Cursor::new("")).unwrap_err().to_string(),
"No OAuth callback URL received before input closed"
);
assert_eq!(
format!(
"{:?}",
read_callback_line(Cursor::new(b"sensitive\xff")).unwrap_err()
),
"OAuth callback URL must be valid UTF-8"
);
}

View File

@@ -0,0 +1,117 @@
//! Confirms explicit database migration and reports the shared migrator's results.
//! Other SQLite clients must remain stopped during replacement, and NFS must enforce
//! cross-client POSIX locks.
use anyhow::Context;
use anyhow::ensure;
use clap::Parser;
use akode_config::LoaderOverrides;
use akode_core::config::ConfigBuilder;
use akode_state::NfsDbMigration;
use akode_state::NfsDbMigrationOutcome;
use akode_utils_cli::CliConfigOverrides;
use owo_colors::OwoColorize;
use std::path::PathBuf;
#[derive(Debug, Parser)]
#[command(
after_help = "Stop SQLite clients on every host and keep them stopped through cutover.\nThe NFS mount must support cross-client POSIX locks (no nolock/local_lock=all).\nThis command replaces configured databases in place and retains their WAL backups."
)]
pub(crate) struct MigrateNfsDbCommand {
/// Use a local directory with space for the database and WAL files.
/// The default is the system temporary directory.
#[arg(long, default_value_os_t = std::env::temp_dir())]
staging_dir: PathBuf,
}
pub(crate) async fn run(
command: MigrateNfsDbCommand,
config_overrides: CliConfigOverrides,
loader_overrides: LoaderOverrides,
) -> anyhow::Result<()> {
ensure!(
cfg!(unix),
"migrate-nfs-db currently requires Unix filesystem locking and directory fsync"
);
let warning = "WARNING: This operation is unsafe under concurrency.";
if supports_color::on(supports_color::Stream::Stderr).is_some() {
eprintln!("{}", warning.red().bold());
} else {
eprintln!("{warning}");
}
eprintln!(
"Stop all aKode instances on every host that uses these databases.\nKeep them stopped until the migration completes successfully."
);
let config = ConfigBuilder::default()
.cli_overrides(
config_overrides
.parse_overrides()
.map_err(anyhow::Error::msg)?,
)
.loader_overrides(loader_overrides)
.build()
.await?;
// Check the merged config for an explicit log directory.
let effective_config = config.config_layer_stack.effective_config();
let skip_logs = effective_config.get("log_dir").is_some();
let sqlite = config.sqlite_config();
if !sqlite.home().try_exists()? {
println!("No databases found.");
return Ok(());
}
let mut needs_permission_confirmation = false;
for database in sqlite.runtime_db_paths() {
if skip_logs && database.path == sqlite.logs_db_path() {
continue;
}
needs_permission_confirmation |=
NfsDbMigration::needs_permission_confirmation(&database.path)?;
}
if needs_permission_confirmation {
eprintln!(
"Some database files have permissions other than 0600.\nMigration preserves file mode bits, including group and other access."
);
}
eprintln!(
"Replacement files belong to you; the original owner, group, and extended ACLs are not copied.\nThis can remove another user's access even when file permissions are 0600.\nOriginal files remain in a private backup directory.\nYou need write access to the database directory and its migration lock."
);
let prompt = if needs_permission_confirmation {
"Migrate databases, including files with permissions other than 0600? [y/N]:"
} else {
"Continue? [y/N]:"
};
ensure!(
crate::confirm(prompt)?,
"Migration cancelled. No databases were changed."
);
let mut migration = NfsDbMigration::lock(sqlite.home())?;
let mut databases_found = 0;
for database in sqlite.runtime_db_paths() {
if skip_logs && database.path == sqlite.logs_db_path() {
println!("Skipped logs database: log_dir is configured.");
continue;
}
let outcome = migration.migrate(&database.path, &command.staging_dir).await.with_context(|| format!(
"migration failed for {}. Keep all aKode instances stopped. Correct the error and rerun codex migrate-nfs-db",
database.path.display()
))?;
match outcome {
NfsDbMigrationOutcome::Missing => continue,
NfsDbMigrationOutcome::AlreadyDelete => {
println!("Already in DELETE mode: {}", database.path.display())
}
NfsDbMigrationOutcome::Migrated { backup_directory } => println!(
"Migrated database: {}\nWAL backup: {}",
database.path.display(),
backup_directory.display()
),
}
databases_found += 1;
}
if databases_found == 0 {
println!("No databases found.");
return Ok(());
}
println!("Migration completed successfully. You can restart aKode.");
Ok(())
}

View File

@@ -0,0 +1,439 @@
use std::io;
use std::io::IsTerminal;
use std::io::Write;
use std::path::Path;
use std::time::Duration;
use std::time::Instant;
use anyhow::Context;
use clap::Parser;
use akode_core::config::ConfigBuilder;
use akode_protocol::ThreadId;
use akode_thread_store::LocalThreadStore;
use akode_thread_store::LocalThreadStoreConfig;
use akode_thread_store::RolloutMigrationMode;
use akode_thread_store::RolloutMigrationOptions;
use akode_thread_store::RolloutMigrationProgress;
use akode_thread_store::RolloutMigrationReport;
use akode_thread_store::RolloutMigrationStatus;
use akode_utils_cli::CliConfigOverrides;
#[derive(Debug, Parser)]
pub(crate) struct MigrateRolloutsCommand {
/// Publish the migration. Without this flag the command only reports eligible sessions.
#[arg(long)]
apply: bool,
/// Restrict inspection or migration to one or more thread IDs.
#[arg(long, value_name = "THREAD_ID", value_parser = ThreadId::from_string)]
thread: Vec<ThreadId>,
/// Limit aggregate rollout read and write throughput, in MiB per second.
#[arg(
long,
value_name = "MIB",
value_parser = clap::value_parser!(u64).range(1..)
)]
max_mib_per_second: Option<u64>,
/// Emit the complete per-thread report as JSON.
#[arg(long)]
json: bool,
/// Print one line for every inspected rollout.
#[arg(long)]
verbose: bool,
}
pub(crate) async fn run(
command: MigrateRolloutsCommand,
config_overrides: CliConfigOverrides,
) -> anyhow::Result<()> {
let overrides = config_overrides
.parse_overrides()
.map_err(anyhow::Error::msg)?;
let config = ConfigBuilder::default()
.cli_overrides(overrides)
.build()
.await?;
let mode = if command.apply {
RolloutMigrationMode::Apply
} else {
RolloutMigrationMode::DryRun
};
let json = command.json;
let verbose = command.verbose;
let thread_history_db_path = config.sqlite.thread_history_db_path();
let thread_storage_before = if mode == RolloutMigrationMode::Apply && !json {
thread_storage_bytes(
config.codex_home.as_path(),
thread_history_db_path.as_path(),
)
.await
.ok()
} else {
None
};
let state_db = if mode == RolloutMigrationMode::Apply {
Some(
akode_rollout::state_db::try_init(&config)
.await
.context("failed to initialize local thread metadata")?,
)
} else {
None
};
let store = LocalThreadStore::new(LocalThreadStoreConfig::from_config(&config), state_db);
let mut progress = MigrationProgress::new(mode, json);
progress.begin();
let result = store
.migrate_rollouts_with_progress(
RolloutMigrationOptions {
mode,
thread_ids: command.thread,
max_mib_per_second: command.max_mib_per_second,
},
|update| progress.update(update),
)
.await;
progress.finish();
let report = result?;
let thread_storage = match thread_storage_before {
Some(before) => thread_storage_bytes(
config.codex_home.as_path(),
thread_history_db_path.as_path(),
)
.await
.ok()
.map(|after| (before, after)),
None => None,
};
if json {
println!("{}", serde_json::to_string_pretty(&report)?);
} else {
print_human_report(&report, mode, verbose, progress.elapsed(), thread_storage);
}
if report
.outcomes
.iter()
.any(|outcome| outcome.status == RolloutMigrationStatus::Failed)
{
anyhow::bail!("one or more rollout migrations failed");
}
Ok(())
}
const TTY_PROGRESS_INTERVAL: Duration = Duration::from_millis(250);
const NON_TTY_PROGRESS_INTERVAL: usize = 1_000;
const MAX_EXCEPTION_DETAILS: usize = 20;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum ProgressOutput {
Quiet,
Tty,
Plain,
}
struct MigrationProgress {
mode: RolloutMigrationMode,
output: ProgressOutput,
started_at: Instant,
last_rendered_at: Instant,
last_plain_processed: usize,
counts: MigrationCounts,
wrote_tty_line: bool,
}
impl MigrationProgress {
fn new(mode: RolloutMigrationMode, json: bool) -> Self {
let now = Instant::now();
let output = if json {
ProgressOutput::Quiet
} else if io::stderr().is_terminal()
&& std::env::var("TERM").ok().as_deref() != Some("dumb")
{
ProgressOutput::Tty
} else {
ProgressOutput::Plain
};
Self {
mode,
output,
started_at: now,
last_rendered_at: now,
last_plain_processed: 0,
counts: MigrationCounts::default(),
wrote_tty_line: false,
}
}
fn begin(&self) {
if self.output != ProgressOutput::Quiet {
eprintln!("Scanning local rollouts...");
}
}
fn update(&mut self, update: RolloutMigrationProgress) {
if let Some(status) = update.outcome_status {
self.counts.observe(status);
}
match self.output {
ProgressOutput::Quiet => {}
ProgressOutput::Tty
if update.processed_paths == update.total_paths
|| self.last_rendered_at.elapsed() >= TTY_PROGRESS_INTERVAL =>
{
let line = self.line(update);
let mut stderr = io::stderr().lock();
let _ = write!(stderr, "\r\x1b[2K{line}");
let _ = stderr.flush();
self.last_rendered_at = Instant::now();
self.wrote_tty_line = true;
}
ProgressOutput::Plain
if update.processed_paths == update.total_paths
|| update
.processed_paths
.saturating_sub(self.last_plain_processed)
>= NON_TTY_PROGRESS_INTERVAL =>
{
eprintln!("{}", self.line(update));
self.last_plain_processed = update.processed_paths;
}
ProgressOutput::Tty | ProgressOutput::Plain => {}
}
}
fn finish(&mut self) {
if self.output != ProgressOutput::Tty || !self.wrote_tty_line {
return;
}
let mut stderr = io::stderr().lock();
let _ = write!(stderr, "\r\x1b[2K");
let _ = stderr.flush();
self.wrote_tty_line = false;
}
fn elapsed(&self) -> Duration {
self.started_at.elapsed()
}
fn line(&self, update: RolloutMigrationProgress) -> String {
let percent = update
.processed_paths
.saturating_mul(100)
.checked_div(update.total_paths)
.unwrap_or(100);
let action = match self.mode {
RolloutMigrationMode::DryRun => "Checking",
RolloutMigrationMode::Apply => "Migrating",
};
let status_counts = match self.mode {
RolloutMigrationMode::DryRun => format!(
"{} eligible • {} already paginated",
self.counts.eligible, self.counts.already_paginated
),
RolloutMigrationMode::Apply => format!(
"{} migrated • {} already paginated",
self.counts.migrated, self.counts.already_paginated
),
};
format!(
"{action} rollouts {}/{} ({percent}%) • {status_counts} • {} skipped • {} failed • {}",
update.processed_paths,
update.total_paths,
self.counts.skipped(),
self.counts.failed,
format_elapsed(self.elapsed()),
)
}
}
#[derive(Default)]
struct MigrationCounts {
eligible: usize,
migrated: usize,
already_paginated: usize,
skipped_empty: usize,
skipped_busy: usize,
failed: usize,
}
impl MigrationCounts {
fn observe(&mut self, status: RolloutMigrationStatus) {
match status {
RolloutMigrationStatus::Eligible => self.eligible += 1,
RolloutMigrationStatus::Migrated => self.migrated += 1,
RolloutMigrationStatus::AlreadyPaginated => self.already_paginated += 1,
RolloutMigrationStatus::SkippedEmpty => self.skipped_empty += 1,
RolloutMigrationStatus::SkippedBusy => self.skipped_busy += 1,
RolloutMigrationStatus::Failed => self.failed += 1,
}
}
fn skipped(&self) -> usize {
self.skipped_empty + self.skipped_busy
}
}
fn print_human_report(
report: &RolloutMigrationReport,
mode: RolloutMigrationMode,
verbose: bool,
elapsed: Duration,
thread_storage: Option<(u64, u64)>,
) {
let mut counts = MigrationCounts::default();
for outcome in &report.outcomes {
counts.observe(outcome.status);
}
let completion = match mode {
RolloutMigrationMode::DryRun => "Scan complete",
RolloutMigrationMode::Apply => "Migration complete",
};
println!("{completion} in {}.", format_elapsed(elapsed));
match mode {
RolloutMigrationMode::DryRun => println!(
"Scanned {} rollout(s): {} eligible, {} already paginated, {} skipped ({} empty, {} busy), {} failed.",
report.outcomes.len(),
counts.eligible,
counts.already_paginated,
counts.skipped(),
counts.skipped_empty,
counts.skipped_busy,
counts.failed,
),
RolloutMigrationMode::Apply => println!(
"Scanned {} rollout(s): {} migrated, {} already paginated, {} skipped ({} empty, {} busy), {} failed.",
report.outcomes.len(),
counts.migrated,
counts.already_paginated,
counts.skipped(),
counts.skipped_empty,
counts.skipped_busy,
counts.failed,
),
}
if let Some((before, after)) = thread_storage {
println!(
"Disk used for thread storage: {} -> {}",
format_bytes(before),
format_bytes(after)
);
}
if mode == RolloutMigrationMode::DryRun && counts.eligible > 0 {
println!("Run `akode migrate-rollouts --apply` to migrate eligible sessions.");
}
if verbose {
for outcome in &report.outcomes {
print_outcome(outcome);
}
return;
}
let exceptions = report.outcomes.iter().filter(|outcome| {
matches!(
outcome.status,
RolloutMigrationStatus::SkippedBusy | RolloutMigrationStatus::Failed
)
});
let exception_count = exceptions.clone().count();
if exception_count == 0 {
return;
}
println!();
for outcome in exceptions.take(MAX_EXCEPTION_DETAILS) {
print_outcome(outcome);
}
if exception_count > MAX_EXCEPTION_DETAILS {
println!(
"... and {} more; rerun with --json for the complete report.",
exception_count - MAX_EXCEPTION_DETAILS
);
}
}
fn print_outcome(outcome: &akode_thread_store::RolloutMigrationOutcome) {
let status = match outcome.status {
RolloutMigrationStatus::Eligible => "eligible",
RolloutMigrationStatus::Migrated => "migrated",
RolloutMigrationStatus::AlreadyPaginated => "already paginated",
RolloutMigrationStatus::SkippedEmpty => "skipped empty",
RolloutMigrationStatus::SkippedBusy => "skipped busy",
RolloutMigrationStatus::Failed => "failed",
};
let thread_id = outcome
.thread_id
.map_or_else(|| "unknown".to_string(), |thread_id| thread_id.to_string());
match &outcome.message {
Some(message) => println!("{status}\t{thread_id}\t{message}"),
None => println!("{status}\t{thread_id}"),
}
}
fn format_elapsed(elapsed: Duration) -> String {
let seconds = elapsed.as_secs();
let minutes = seconds / 60;
if minutes == 0 {
return format!("{seconds}s");
}
let hours = minutes / 60;
if hours == 0 {
return format!("{minutes}m{:02}s", seconds % 60);
}
format!("{hours}h{:02}m{:02}s", minutes % 60, seconds % 60)
}
async fn thread_storage_bytes(codex_home: &Path, thread_history_db_path: &Path) -> io::Result<u64> {
let mut bytes = 0_u64;
let mut directories = vec![
codex_home.join(akode_rollout::SESSIONS_SUBDIR),
codex_home.join(akode_rollout::ARCHIVED_SESSIONS_SUBDIR),
];
while let Some(directory) = directories.pop() {
let mut entries = match tokio::fs::read_dir(&directory).await {
Ok(entries) => entries,
Err(error) if error.kind() == io::ErrorKind::NotFound => continue,
Err(error) => return Err(error),
};
while let Some(entry) = entries.next_entry().await? {
let file_type = entry.file_type().await?;
if file_type.is_dir() {
directories.push(entry.path());
} else if file_type.is_file() {
bytes = bytes.saturating_add(entry.metadata().await?.len());
}
}
}
for suffix in ["", "-wal", "-shm"] {
let mut path = thread_history_db_path.as_os_str().to_owned();
path.push(suffix);
match tokio::fs::metadata(path).await {
Ok(metadata) => bytes = bytes.saturating_add(metadata.len()),
Err(error) if error.kind() == io::ErrorKind::NotFound => {}
Err(error) => return Err(error),
}
}
Ok(bytes)
}
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!("{:.1} GB", bytes / GIB)
} else if bytes >= MIB {
format!("{:.1} MB", bytes / MIB)
} else if bytes >= KIB {
format!("{:.1} KB", bytes / KIB)
} else {
format!("{} B", bytes as u64)
}
}

View File

@@ -0,0 +1,894 @@
use anyhow::Context;
use anyhow::Result;
use anyhow::bail;
use clap::Parser;
use akode_core::config::Config;
use akode_core::config::find_codex_home;
use akode_core::plugins_manager_for_config;
use akode_core_plugins::ConfiguredMarketplace;
use akode_core_plugins::OPENAI_BUNDLED_MARKETPLACE_NAME;
use akode_core_plugins::PluginInstallOutcome;
use akode_core_plugins::PluginInstallRequest;
use akode_core_plugins::PluginsConfigInput;
use akode_core_plugins::PluginsManager;
use akode_core_plugins::allowed_configured_marketplace_names;
use akode_core_plugins::installed_marketplaces::marketplace_install_root;
use akode_core_plugins::installed_marketplaces::resolve_configured_marketplace_root;
use akode_core_plugins::marketplace::MarketplaceListError;
use akode_core_plugins::marketplace::MarketplacePluginAuthPolicy;
use akode_core_plugins::marketplace::MarketplacePluginInstallPolicy;
use akode_core_plugins::marketplace::MarketplacePluginSource;
use akode_core_plugins::marketplace::find_marketplace_manifest_path;
use akode_login::AuthManager;
use akode_plugin::PluginId;
use akode_plugin::validate_plugin_segment;
use akode_utils_absolute_path::AbsolutePathBuf;
use akode_utils_cli::CliConfigOverrides;
use serde::Serialize;
use std::collections::HashMap;
use std::io;
use std::io::Write;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;
use crate::marketplace_cmd::MarketplaceCli;
const OPENAI_BUNDLED_ALPHA_MARKETPLACE_NAME: &str = "openai-bundled-alpha";
const OPENAI_PRIMARY_RUNTIME_MARKETPLACE_NAME: &str = "openai-primary-runtime";
#[derive(Debug, Parser)]
#[command(bin_name = "akode plugin")]
pub struct PluginCli {
#[clap(flatten)]
pub config_overrides: CliConfigOverrides,
#[command(subcommand)]
pub subcommand: PluginSubcommand,
}
#[derive(Debug, clap::Subcommand)]
pub enum PluginSubcommand {
/// Install a plugin from a configured marketplace.
///
/// Pass either `PLUGIN@MARKETPLACE` or pass `PLUGIN` with
/// `--marketplace MARKETPLACE`.
Add(AddPluginArgs),
/// List plugins available from configured marketplaces.
List(ListPluginsArgs),
/// Add, list, upgrade, or remove configured plugin marketplaces.
Marketplace(MarketplaceCli),
/// Uninstall a plugin and remove its local cache.
///
/// Pass either `PLUGIN@MARKETPLACE` or pass `PLUGIN` with
/// `--marketplace MARKETPLACE`.
Remove(RemovePluginArgs),
}
#[derive(Debug, Parser)]
#[command(
bin_name = "akode plugin add",
after_help = "Examples:\n akode plugin add sample@debug\n akode plugin add sample --marketplace debug"
)]
pub struct AddPluginArgs {
/// Plugin selector to install: either PLUGIN@MARKETPLACE or PLUGIN with --marketplace.
#[arg(value_name = "PLUGIN[@MARKETPLACE]")]
plugin: String,
/// Marketplace name to use when PLUGIN does not include @MARKETPLACE.
#[arg(long = "marketplace", short = 'm', value_name = "MARKETPLACE")]
marketplace_name: Option<String>,
/// Output install result as JSON.
#[arg(long = "json")]
json: bool,
}
#[derive(Debug, Parser)]
#[command(
bin_name = "akode plugin list",
after_help = "Examples:\n akode plugin list\n akode plugin list --marketplace debug\n akode plugin list --json\n akode plugin list --available --json"
)]
pub struct ListPluginsArgs {
/// Only list plugins from this marketplace name.
#[arg(long = "marketplace", short = 'm', value_name = "MARKETPLACE")]
marketplace_name: Option<String>,
/// Output plugin list as JSON.
#[arg(long = "json")]
json: bool,
/// Include uninstalled marketplace plugins in the JSON output.
#[arg(long = "available", requires = "json")]
available: bool,
}
#[derive(Debug, Parser)]
#[command(
bin_name = "akode plugin remove",
after_help = "Examples:\n akode plugin remove sample@debug\n akode plugin remove sample --marketplace debug"
)]
pub struct RemovePluginArgs {
/// Plugin selector to remove: either PLUGIN@MARKETPLACE or PLUGIN with --marketplace.
#[arg(value_name = "PLUGIN[@MARKETPLACE]")]
plugin: String,
/// Marketplace name to use when PLUGIN does not include @MARKETPLACE.
#[arg(long = "marketplace", short = 'm', value_name = "MARKETPLACE")]
marketplace_name: Option<String>,
/// Output remove result as JSON.
#[arg(long = "json")]
json: bool,
}
pub async fn run_plugin_add(
overrides: Vec<(String, toml::Value)>,
args: AddPluginArgs,
) -> Result<()> {
let AddPluginArgs {
plugin,
marketplace_name,
json,
} = args;
let selection = parse_plugin_selection(plugin, marketplace_name)?;
let context = load_plugin_command_context(overrides).await?;
let marketplace = find_marketplace_for_plugin(
&context.manager,
context.codex_home.as_path(),
&context.plugins_input,
&selection.marketplace_name,
&selection.plugin_name,
)?;
let outcome = context
.manager
.install_plugin(
&context.plugins_input.config_layer_stack,
PluginInstallRequest {
plugin_name: selection.plugin_name,
marketplace_path: marketplace.path,
},
)
.await?;
let output = JsonPluginAddOutput::from_outcome(outcome);
if json {
println!("{}", serde_json::to_string_pretty(&output)?);
return Ok(());
}
println!(
"Added plugin `{}` from marketplace `{}`.",
output.name, output.marketplace_name
);
println!("Installed plugin root: {}", output.installed_path);
Ok(())
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct JsonPluginAddOutput {
plugin_id: String,
name: String,
marketplace_name: String,
version: String,
installed_path: String,
auth_policy: &'static str,
}
impl JsonPluginAddOutput {
fn from_outcome(outcome: PluginInstallOutcome) -> Self {
Self {
plugin_id: outcome.plugin_id.as_key(),
name: outcome.plugin_id.plugin_name,
marketplace_name: outcome.plugin_id.marketplace_name,
version: outcome.plugin_version,
installed_path: outcome.installed_path.as_path().display().to_string(),
auth_policy: auth_policy_label(outcome.auth_policy),
}
}
}
pub async fn run_plugin_list(
overrides: Vec<(String, toml::Value)>,
args: ListPluginsArgs,
) -> Result<()> {
let context = load_plugin_command_context(overrides).await?;
let PluginCommandContext {
codex_home,
plugins_input,
manager,
..
} = context;
let outcome = manager
.list_marketplaces_for_config(&plugins_input, &[], /*include_openai_curated*/ true)
.context("failed to list marketplace plugins")?;
ensure_configured_marketplace_snapshots_loaded(
codex_home.as_path(),
&plugins_input,
&outcome.errors,
args.marketplace_name.as_deref(),
)?;
let marketplace_sources = configured_marketplace_sources(&plugins_input, codex_home.as_path());
let marketplaces = outcome
.marketplaces
.into_iter()
.map(|marketplace| {
let source = marketplace_sources.get(&marketplace.name).cloned();
PluginListMarketplace {
plugins: marketplace
.plugins
.into_iter()
.map(|plugin| {
PluginListEntry::from_configured_plugin(
&marketplace.name,
source.clone(),
plugin,
)
})
.collect(),
name: marketplace.name,
path: marketplace.path,
}
})
.filter(|marketplace| {
args.marketplace_name
.as_ref()
.is_none_or(|name| marketplace.name == *name)
})
.collect::<Vec<_>>();
write_plugin_list(&mut io::stdout().lock(), marketplaces, args)
}
fn write_plugin_list(
writer: &mut impl Write,
marketplaces: Vec<PluginListMarketplace>,
args: ListPluginsArgs,
) -> Result<()> {
let result = render_plugin_list(writer, marketplaces, args)
.and_then(|()| writer.flush().map_err(Into::into));
match result {
// A consumer such as `head` may finish before the full catalog is written.
Err(error)
if error
.downcast_ref::<io::Error>()
.is_some_and(|error| error.kind() == io::ErrorKind::BrokenPipe) =>
{
Ok(())
}
Ok(()) => Ok(()),
Err(error) => Err(error),
}
}
fn render_plugin_list(
writer: &mut impl Write,
marketplaces: Vec<PluginListMarketplace>,
args: ListPluginsArgs,
) -> Result<()> {
if args.json {
let output = JsonPluginListOutput::from_marketplaces(marketplaces, args.available);
writeln!(writer, "{}", serde_json::to_string_pretty(&output)?)?;
return Ok(());
}
if marketplaces.is_empty() {
if let Some(marketplace_name) = args.marketplace_name {
writeln!(
writer,
"No plugins found in marketplace `{marketplace_name}`."
)?;
} else {
writeln!(writer, "No marketplace plugins found.")?;
}
} else {
for (index, marketplace) in marketplaces.into_iter().enumerate() {
let mut rows = Vec::new();
let mut plugin_width = "PLUGIN".len();
let mut status_width = "STATUS".len();
let mut installed_version_width = "VERSION".len();
for plugin in &marketplace.plugins {
let state = if plugin.installed && plugin.enabled {
"installed, enabled"
} else if plugin.installed {
"installed, disabled"
} else {
"not installed"
};
let installed_version = plugin.display_version.clone().unwrap_or_default();
let path = match &plugin.source {
JsonPluginSource::Local { path } => path.clone(),
JsonPluginSource::Git { url, ref_name, sha }
| JsonPluginSource::GitSubdir {
url, ref_name, sha, ..
} => {
let mut parts = vec![url.clone()];
if let JsonPluginSource::GitSubdir { path, .. } = &plugin.source {
parts.push(format!("path `{path}`"));
}
if let Some(ref_name) = ref_name {
parts.push(format!("ref `{ref_name}`"));
}
if let Some(sha) = sha {
parts.push(format!("sha `{sha}`"));
}
parts.join(", ")
}
JsonPluginSource::Npm {
package,
version,
registry,
} => {
let mut parts = vec![package.clone()];
if let Some(version) = version {
parts.push(format!("version `{version}`"));
}
if let Some(registry) = registry {
parts.push(format!("registry `{registry}`"));
}
parts.join(", ")
}
};
plugin_width = plugin_width.max(plugin.plugin_id.len());
status_width = status_width.max(state.len());
installed_version_width = installed_version_width.max(installed_version.len());
rows.push((plugin.plugin_id.clone(), state, installed_version, path));
}
if index > 0 {
writeln!(writer)?;
}
writeln!(writer, "Marketplace `{}`", marketplace.name)?;
writeln!(writer, "{}", marketplace.path.display())?;
writeln!(writer)?;
writeln!(
writer,
"{:<plugin_width$} {:<status_width$} {:<installed_version_width$} SOURCE",
"PLUGIN", "STATUS", "VERSION"
)?;
for (plugin, status, installed_version, path) in rows {
writeln!(
writer,
"{plugin:<plugin_width$} {status:<status_width$} {installed_version:<installed_version_width$} {path}"
)?;
}
}
}
Ok(())
}
struct PluginListMarketplace {
name: String,
path: AbsolutePathBuf,
plugins: Vec<PluginListEntry>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct JsonPluginListOutput {
installed: Vec<PluginListEntry>,
available: Vec<PluginListEntry>,
}
impl JsonPluginListOutput {
fn from_marketplaces(
marketplaces: Vec<PluginListMarketplace>,
include_available: bool,
) -> Self {
let mut installed = Vec::new();
let mut available = Vec::new();
for marketplace in marketplaces {
for entry in marketplace.plugins {
if entry.installed {
installed.push(entry);
} else if include_available {
available.push(entry);
}
}
}
Self {
installed,
available,
}
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct PluginListEntry {
plugin_id: String,
name: String,
marketplace_name: String,
version: Option<String>,
#[serde(skip)]
display_version: Option<String>,
installed: bool,
enabled: bool,
source: JsonPluginSource,
#[serde(skip_serializing_if = "Option::is_none")]
marketplace_source: Option<JsonMarketplaceSource>,
install_policy: &'static str,
auth_policy: &'static str,
}
impl PluginListEntry {
fn from_configured_plugin(
marketplace_name: &str,
marketplace_source: Option<JsonMarketplaceSource>,
plugin: akode_core_plugins::ConfiguredMarketplacePlugin,
) -> Self {
let display_version = plugin.installed_version;
let version = display_version.clone().or(plugin.local_version);
Self {
plugin_id: plugin.id,
name: plugin.name,
marketplace_name: marketplace_name.to_string(),
version,
display_version,
installed: plugin.installed,
enabled: plugin.enabled,
source: JsonPluginSource::from_marketplace_source(plugin.source),
marketplace_source,
install_policy: install_policy_label(plugin.policy.installation),
auth_policy: auth_policy_label(plugin.policy.authentication),
}
}
}
#[derive(Debug, Serialize)]
#[serde(tag = "source", rename_all = "kebab-case")]
enum JsonPluginSource {
Local {
path: String,
},
Git {
url: String,
#[serde(rename = "ref", skip_serializing_if = "Option::is_none")]
ref_name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
sha: Option<String>,
},
GitSubdir {
url: String,
path: String,
#[serde(rename = "ref", skip_serializing_if = "Option::is_none")]
ref_name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
sha: Option<String>,
},
Npm {
package: String,
#[serde(skip_serializing_if = "Option::is_none")]
version: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
registry: Option<String>,
},
}
impl JsonPluginSource {
fn from_marketplace_source(source: MarketplacePluginSource) -> Self {
match source {
MarketplacePluginSource::Local { path } => Self::Local {
path: path.as_path().display().to_string(),
},
MarketplacePluginSource::Git {
url,
path: Some(path),
ref_name,
sha,
} => Self::GitSubdir {
url,
path,
ref_name,
sha,
},
MarketplacePluginSource::Git {
url,
path: None,
ref_name,
sha,
} => Self::Git { url, ref_name, sha },
MarketplacePluginSource::Npm {
package,
version,
registry,
} => Self::Npm {
package,
version,
registry,
},
}
}
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct JsonMarketplaceSource {
source_type: String,
source: String,
}
pub(crate) fn configured_marketplace_sources(
plugins_input: &PluginsConfigInput,
codex_home: &Path,
) -> HashMap<String, JsonMarketplaceSource> {
let effective_config = plugins_input.config_layer_stack.effective_config();
let Some(marketplaces) = effective_config
.get("marketplaces")
.and_then(toml::Value::as_table)
else {
return HashMap::new();
};
let allowed_marketplace_names =
allowed_configured_marketplace_names(&plugins_input.config_layer_stack, codex_home);
marketplaces
.iter()
.filter(|(marketplace_name, _)| allowed_marketplace_names.contains(*marketplace_name))
.filter_map(|(marketplace_name, marketplace)| {
let source_type = marketplace
.get("source_type")
.and_then(toml::Value::as_str)?;
let source = marketplace.get("source").and_then(toml::Value::as_str)?;
Some((
marketplace_name.clone(),
JsonMarketplaceSource {
source_type: source_type.to_string(),
source: source.to_string(),
},
))
})
.collect()
}
fn install_policy_label(policy: MarketplacePluginInstallPolicy) -> &'static str {
match policy {
MarketplacePluginInstallPolicy::NotAvailable => "NOT_AVAILABLE",
MarketplacePluginInstallPolicy::Available => "AVAILABLE",
MarketplacePluginInstallPolicy::InstalledByDefault => "INSTALLED_BY_DEFAULT",
}
}
fn auth_policy_label(policy: MarketplacePluginAuthPolicy) -> &'static str {
match policy {
MarketplacePluginAuthPolicy::OnInstall => "ON_INSTALL",
MarketplacePluginAuthPolicy::OnUse => "ON_USE",
}
}
pub async fn run_plugin_remove(
overrides: Vec<(String, toml::Value)>,
args: RemovePluginArgs,
) -> Result<()> {
let RemovePluginArgs {
plugin,
marketplace_name,
json,
} = args;
let selection = parse_plugin_selection(plugin, marketplace_name)?;
let context = load_plugin_command_context(overrides).await?;
context
.manager
.uninstall_plugin(selection.plugin_key.clone())
.await?;
if json {
let output = JsonPluginRemoveOutput::from_selection(selection);
println!("{}", serde_json::to_string_pretty(&output)?);
return Ok(());
}
println!(
"Removed plugin `{}` from marketplace `{}`.",
selection.plugin_name, selection.marketplace_name
);
Ok(())
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct JsonPluginRemoveOutput {
plugin_id: String,
name: String,
marketplace_name: String,
}
impl JsonPluginRemoveOutput {
fn from_selection(selection: PluginSelection) -> Self {
Self {
plugin_id: selection.plugin_key,
name: selection.plugin_name,
marketplace_name: selection.marketplace_name,
}
}
}
struct PluginCommandContext {
codex_home: PathBuf,
plugins_input: PluginsConfigInput,
manager: Arc<PluginsManager>,
}
async fn load_plugin_command_context(
overrides: Vec<(String, toml::Value)>,
) -> Result<PluginCommandContext> {
let codex_home = find_codex_home().context("failed to resolve AKODE_HOME")?;
let config = Config::load_with_cli_overrides(overrides)
.await
.context("failed to load configuration")?;
let plugins_input = config.plugins_config_input();
let auth_manager = load_cli_auth_manager(&config).await?;
let manager = Arc::new(plugins_manager_for_config(&config, auth_manager));
Ok(PluginCommandContext {
codex_home: codex_home.to_path_buf(),
plugins_input,
manager,
})
}
pub(crate) async fn load_cli_auth_manager(config: &Config) -> Result<Arc<AuthManager>> {
Ok(AuthManager::shared_from_config(config, /*enable_codex_api_key_env*/ true).await?)
}
struct PluginSelection {
plugin_name: String,
marketplace_name: String,
plugin_key: String,
}
impl PluginSelection {
fn from_plugin_id(plugin_id: PluginId) -> Self {
let plugin_key = plugin_id.as_key();
Self {
plugin_name: plugin_id.plugin_name,
marketplace_name: plugin_id.marketplace_name,
plugin_key,
}
}
}
fn parse_plugin_selection(
plugin: String,
marketplace_name: Option<String>,
) -> Result<PluginSelection> {
match (PluginId::parse(&plugin), marketplace_name) {
(Ok(plugin_id), None) => Ok(PluginSelection::from_plugin_id(plugin_id)),
(Ok(plugin_id), Some(marketplace_name)) => {
if plugin_id.marketplace_name != marketplace_name {
bail!(
"plugin id `{}` belongs to marketplace `{}`, but --marketplace specified `{}`",
plugin,
plugin_id.marketplace_name,
marketplace_name
);
}
Ok(PluginSelection::from_plugin_id(plugin_id))
}
(Err(_), Some(marketplace_name)) => Ok(PluginSelection::from_plugin_id(PluginId::new(
plugin,
marketplace_name,
)?)),
(Err(_), None) => {
bail!("plugin requires --marketplace unless passed as <plugin>@<marketplace>")
}
}
}
fn find_marketplace_for_plugin(
manager: &PluginsManager,
codex_home: &std::path::Path,
plugins_input: &PluginsConfigInput,
marketplace_name: &str,
plugin_name: &str,
) -> Result<ConfiguredMarketplace> {
let outcome = manager
.list_marketplaces_for_config(plugins_input, &[], /*include_openai_curated*/ true)
.context("failed to list marketplace plugins")?;
ensure_configured_marketplace_snapshots_loaded(
codex_home,
plugins_input,
&outcome.errors,
Some(marketplace_name),
)?;
let matches = outcome
.marketplaces
.into_iter()
.filter(|marketplace| marketplace.name == marketplace_name)
.filter(|marketplace| {
marketplace
.plugins
.iter()
.any(|plugin| plugin.name == plugin_name)
})
.collect::<Vec<_>>();
match matches.as_slice() {
[] => bail!("plugin `{plugin_name}` was not found in marketplace `{marketplace_name}`"),
[marketplace] => Ok(marketplace.clone()),
_ => bail!(
"plugin `{plugin_name}` in marketplace `{marketplace_name}` matched multiple marketplace roots"
),
}
}
pub(crate) struct ConfiguredMarketplaceSnapshotIssue {
pub(crate) marketplace_name: String,
pub(crate) path: PathBuf,
pub(crate) message: String,
}
fn ensure_configured_marketplace_snapshots_loaded(
codex_home: &std::path::Path,
plugins_input: &PluginsConfigInput,
load_errors: &[MarketplaceListError],
marketplace_name: Option<&str>,
) -> Result<()> {
let issues = configured_marketplace_snapshot_issues(
codex_home,
plugins_input,
load_errors,
marketplace_name,
);
if issues.is_empty() {
return Ok(());
}
let issue_lines = issues
.iter()
.map(|issue| {
format!(
"- `{}` at {}: {}",
issue.marketplace_name,
issue.path.display(),
issue.message
)
})
.collect::<Vec<_>>()
.join("\n");
bail!("failed to load configured marketplace snapshot(s):\n{issue_lines}");
}
pub(crate) fn configured_marketplace_snapshot_issues(
codex_home: &std::path::Path,
plugins_input: &PluginsConfigInput,
load_errors: &[MarketplaceListError],
marketplace_name: Option<&str>,
) -> Vec<ConfiguredMarketplaceSnapshotIssue> {
let effective_config = plugins_input.config_layer_stack.effective_config();
let Some(configured_marketplaces) = effective_config
.get("marketplaces")
.and_then(toml::Value::as_table)
else {
return Vec::new();
};
let allowed_marketplace_names =
allowed_configured_marketplace_names(&plugins_input.config_layer_stack, codex_home);
let default_install_root = marketplace_install_root(codex_home);
let mut manifest_paths = Vec::new();
let mut issues = Vec::new();
for (configured_name, marketplace) in configured_marketplaces {
if !allowed_marketplace_names.contains(configured_name) {
continue;
}
if marketplace_name.is_some_and(|name| configured_name != name) {
continue;
}
if !marketplace.is_table() {
issues.push(ConfiguredMarketplaceSnapshotIssue {
marketplace_name: configured_name.clone(),
path: PathBuf::from("<invalid config>"),
message: "configured marketplace entry must be a table".to_string(),
});
continue;
}
if let Err(err) = validate_plugin_segment(configured_name, "marketplace name") {
issues.push(ConfiguredMarketplaceSnapshotIssue {
marketplace_name: configured_name.clone(),
path: PathBuf::from("<invalid config>"),
message: err.to_string(),
});
continue;
}
if marketplace.get("source_type").and_then(toml::Value::as_str) == Some("local")
&& marketplace
.get("source")
.and_then(toml::Value::as_str)
.is_none_or(str::is_empty)
{
issues.push(ConfiguredMarketplaceSnapshotIssue {
marketplace_name: configured_name.clone(),
path: PathBuf::from("<invalid source>"),
message: "configured local marketplace source is missing or empty".to_string(),
});
continue;
}
let Some(root) = resolve_configured_marketplace_root(
configured_name,
marketplace,
&default_install_root,
) else {
continue;
};
match find_marketplace_manifest_path(&root) {
Some(path) => manifest_paths.push((configured_name.clone(), path)),
None => {
if is_implicit_system_marketplace_root(configured_name, codex_home, &root) {
continue;
}
issues.push(ConfiguredMarketplaceSnapshotIssue {
marketplace_name: configured_name.clone(),
path: root,
message: "marketplace root does not contain a supported manifest".to_string(),
});
}
}
}
for error in load_errors {
if let Some((configured_name, _)) = manifest_paths
.iter()
.find(|(_, path)| path.as_path() == error.path.as_path())
{
issues.push(ConfiguredMarketplaceSnapshotIssue {
marketplace_name: configured_name.clone(),
path: error.path.to_path_buf(),
message: error.message.clone(),
});
}
}
issues
}
fn is_implicit_system_marketplace_root(
marketplace_name: &str,
_codex_home: &Path,
root: &Path,
) -> bool {
if matches!(
marketplace_name,
OPENAI_BUNDLED_MARKETPLACE_NAME | OPENAI_BUNDLED_ALPHA_MARKETPLACE_NAME
) && path_ends_with(root, &[".tmp", "bundled-marketplaces", marketplace_name])
{
return true;
}
marketplace_name == OPENAI_PRIMARY_RUNTIME_MARKETPLACE_NAME
&& path_ends_with(
root,
&[
"codex-runtimes",
"codex-primary-runtime",
"plugins",
marketplace_name,
],
)
}
fn path_ends_with(path: &Path, suffix: &[&str]) -> bool {
let path_components = path
.components()
.map(|component| component.as_os_str().to_string_lossy().into_owned())
.collect::<Vec<_>>();
path_components.as_slice().ends_with(
&suffix
.iter()
.map(std::string::ToString::to_string)
.collect::<Vec<_>>(),
)
}
#[cfg(test)]
#[path = "plugin_cmd_tests.rs"]
mod tests;

View File

@@ -0,0 +1,76 @@
//! Verify plugin-list output error handling at the writer boundary.
use super::ListPluginsArgs;
use super::write_plugin_list;
use pretty_assertions::assert_eq;
use std::io;
use std::io::Write;
#[derive(Clone, Copy)]
enum Failure {
Write,
Flush,
}
struct FailingWriter {
failure: Failure,
kind: io::ErrorKind,
}
impl Write for FailingWriter {
fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
match self.failure {
Failure::Write => Err(io::Error::new(self.kind, "output failed")),
Failure::Flush => Ok(bytes.len()),
}
}
fn flush(&mut self) -> io::Result<()> {
match self.failure {
Failure::Write => Ok(()),
Failure::Flush => Err(io::Error::new(self.kind, "output failed")),
}
}
}
#[test]
fn plugin_list_treats_broken_pipe_as_success() {
for json in [false, true] {
for failure in [Failure::Write, Failure::Flush] {
let mut writer = FailingWriter {
failure,
kind: io::ErrorKind::BrokenPipe,
};
let args = ListPluginsArgs {
marketplace_name: None,
json,
available: true,
};
write_plugin_list(&mut writer, Vec::new(), args).unwrap();
}
}
}
#[test]
fn plugin_list_preserves_other_output_errors() {
for json in [false, true] {
for failure in [Failure::Write, Failure::Flush] {
for kind in [io::ErrorKind::PermissionDenied, io::ErrorKind::WriteZero] {
let mut writer = FailingWriter { failure, kind };
let args = ListPluginsArgs {
marketplace_name: None,
json,
available: true,
};
let error = write_plugin_list(&mut writer, Vec::new(), args)
.unwrap_err()
.downcast::<io::Error>()
.unwrap();
assert_eq!(error.kind(), kind);
assert_eq!(error.to_string(), "output failed");
}
}
}
}

View File

@@ -0,0 +1,153 @@
use clap::Arg;
use clap::ArgMatches;
use clap::Command;
use clap::CommandFactory;
use clap::Parser;
use clap::builder::NonEmptyStringValueParser;
use clap::error::ErrorKind;
use clap::parser::ValueSource;
use akode_arg0::Arg0DispatchPaths;
use akode_tui::Cli as TuiCli;
use akode_utils_cli::CliConfigOverrides;
use crate::InteractiveRemoteOptions;
use crate::SessionArchiveConfigOverrides;
use crate::finalize_session_archive_interactive;
use crate::resolve_remote_endpoint;
#[derive(Debug, Parser)]
#[command(defer(configure_help))]
pub(crate) struct QueueCommand {
/// Session UUID or exact session name.
#[arg(long, value_name = "THREAD")]
thread: String,
/// Message text to queue.
#[arg(long, value_name = "TEXT", value_parser = NonEmptyStringValueParser::new())]
message: String,
/// After queueing, try to resume the thread on the local daemon or selected --remote server.
/// A failed resume produces a warning and the command still succeeds.
#[arg(long)]
resume: bool,
#[clap(flatten)]
remote: InteractiveRemoteOptions,
#[clap(flatten)]
pub(crate) config_overrides: SessionArchiveConfigOverrides,
}
/// Only inherited options need restrictions; queue owns its other arguments.
fn restricted_options(command: &Command) -> impl Iterator<Item = &Arg> {
command.get_arguments().filter(|arg| {
!matches!(
arg.get_long(),
Some(
"remote"
| "remote-auth-token-env"
| "config"
| "enable"
| "disable"
| "profile"
| "strict-config"
)
)
})
}
fn configure_help(command: Command) -> Command {
let interactive = TuiCli::command();
command.mut_args(|arg| {
if arg.get_long() == Some("config") {
arg.long_help(None).help("Override a startup configuration value (key=value). Queued messages use the thread's model.")
} else if !restricted_options(&interactive).any(|shared| shared.get_id() == arg.get_id()) {
arg
} else if arg.get_long() == Some("cd") {
arg.help_heading("Local server options (without --remote)")
} else {
arg.hide(true)
}
})
}
/// Check both scopes before root flags such as `--approve-for-me` become config overrides.
pub(super) fn validate_options(command: &Command, root: &ArgMatches) -> Result<(), clap::Error> {
let Some(queue) = root.subcommand_matches("queue") else {
return Ok(());
};
let remote = root
.get_one::<String>("remote")
.or_else(|| queue.get_one::<String>("remote"));
let supplied = [root, queue].into_iter().flat_map(|scope| {
scope
.ids()
.filter(|id| scope.value_source(id.as_str()) == Some(ValueSource::CommandLine))
});
for id in supplied {
let Some(arg) = restricted_options(command).find(|arg| arg.get_id() == id) else {
continue;
};
let message = match arg.get_long() {
Some("cd") if remote.is_none() => continue,
Some("cd") => "`akode queue` does not support `--cd` with `--remote`".to_string(),
// These flags already have dedicated diagnostics in the CLI and session startup.
Some("worktree" | "no-daemon") => continue,
Some("model") => {
"`akode queue` does not support `--model`; queued messages use the thread's model"
.to_string()
}
Some("image") => "`akode queue` does not support image attachments".to_string(),
Some(name) => format!("`akode queue` does not support `--{name}`"),
None => {
"`akode queue` does not accept a positional prompt; use `--message`".to_string()
}
};
return Err(clap::Error::raw(ErrorKind::ArgumentConflict, message));
}
Ok(())
}
pub(crate) async fn run_queue_command(
command: QueueCommand,
interactive: TuiCli,
root_config_overrides: CliConfigOverrides,
root_remote: Option<String>,
root_remote_auth_token_env: Option<String>,
arg0_paths: Arg0DispatchPaths,
) -> anyhow::Result<String> {
let QueueCommand {
thread,
message,
resume,
remote,
config_overrides,
} = command;
let cli =
finalize_session_archive_interactive(interactive, root_config_overrides, config_overrides);
if cli.config_overrides.raw_overrides.iter().any(|entry| {
entry
.split_once('=')
.is_some_and(|(key, _)| key.trim() == "model")
}) {
anyhow::bail!(
"`akode queue` does not support a `model` config override; queued messages use the thread's model"
);
}
let explicit_remote_endpoint = resolve_remote_endpoint(
remote.remote.or(root_remote),
remote.remote_auth_token_env.or(root_remote_auth_token_env),
)?;
akode_tui::run_session_queue_command(
thread,
message,
resume,
akode_tui::SessionArchiveCommandOptions {
cli,
arg0_paths,
explicit_remote_endpoint,
},
)
.await
.map_err(|error| anyhow::anyhow!("{error:#}"))
}

View File

@@ -0,0 +1,230 @@
use std::path::PathBuf;
use anyhow::Context;
use clap::ArgAction;
use clap::ArgGroup;
use clap::Parser;
use akode_core::config::ConfigBuilder;
use akode_core::config::edit::ConfigEditsBuilder;
use akode_core::config::find_codex_home;
use akode_utils_cli::ProfileV2Name;
use toml::Value as TomlValue;
#[derive(Debug, Parser)]
#[command(group(
ArgGroup::new("sandbox_user")
.required(true)
.args(["user", "current_user"])
))]
pub(crate) struct SandboxSetupCommand {
/// Set up the elevated Windows sandbox.
#[arg(long = "elevated", action = ArgAction::SetTrue)]
elevated_sandbox_level: bool,
/// Windows user that will run aKode after managed deployment.
#[arg(
long = "user",
value_name = "USER",
conflicts_with = "current_user",
requires = "codex_home"
)]
user: Option<String>,
/// Use the current Windows user as the aKode user.
#[arg(
long = "current-user",
default_value_t = false,
conflicts_with = "user"
)]
current_user: bool,
/// AKODE_HOME for the aKode user. Required with --user.
#[arg(long = "akode-home", value_name = "DIR")]
codex_home: Option<PathBuf>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SandboxSetupLevel {
Elevated,
}
impl SandboxSetupCommand {
fn setup_level(&self) -> anyhow::Result<SandboxSetupLevel> {
if self.elevated_sandbox_level {
Ok(SandboxSetupLevel::Elevated)
} else {
anyhow::bail!("`akode sandbox setup` currently requires --elevated");
}
}
}
pub(crate) async fn run(
cmd: SandboxSetupCommand,
config_profile: Option<ProfileV2Name>,
cli_overrides: Vec<(String, TomlValue)>,
) -> anyhow::Result<()> {
match cmd.setup_level()? {
SandboxSetupLevel::Elevated => run_elevated(cmd, config_profile, cli_overrides).await,
}
}
pub(crate) fn parse_setup_command(
sandbox_command: &[String],
) -> anyhow::Result<Option<SandboxSetupCommand>> {
if sandbox_command
.first()
.is_none_or(|command| command != "setup")
{
return Ok(None);
}
SandboxSetupCommand::try_parse_from(sandbox_command.iter().map(String::as_str))
.map(Some)
.map_err(anyhow::Error::from)
}
async fn run_elevated(
cmd: SandboxSetupCommand,
config_profile: Option<ProfileV2Name>,
cli_overrides: Vec<(String, TomlValue)>,
) -> anyhow::Result<()> {
let identity = resolve_sandbox_setup_identity(&cmd)?;
let config = ConfigBuilder::default()
.codex_home(identity.codex_home.clone())
.fallback_cwd(Some(identity.codex_home.clone()))
.loader_overrides(super::loader_overrides_for_profile_at_codex_home(
config_profile.as_ref(),
&identity.codex_home,
))
.cli_overrides(cli_overrides)
.build()
.await
.context("failed to load target user's aKode config for sandbox provisioning")?;
akode_core::windows_sandbox::run_elevated_provisioning_setup(
identity.codex_home.as_path(),
identity.real_user.as_str(),
config.permissions.network.as_ref(),
)?;
ConfigEditsBuilder::new(identity.codex_home.as_path())
.set_windows_sandbox_mode("elevated")
.apply()
.await
.map_err(|err| {
anyhow::anyhow!(
"sandbox provisioning succeeded, but failed to persist elevated sandbox config: {err}"
)
})?;
println!(
"Windows elevated sandbox setup completed for {} at {}.",
identity.real_user,
identity.codex_home.display()
);
Ok(())
}
struct SandboxSetupIdentity {
real_user: String,
codex_home: PathBuf,
}
fn resolve_sandbox_setup_identity(
cmd: &SandboxSetupCommand,
) -> anyhow::Result<SandboxSetupIdentity> {
if cmd.current_user {
let real_user = std::env::var("USERNAME")
.or_else(|_| std::env::var("USER"))
.map_err(|err| {
anyhow::anyhow!("failed to determine current user from environment: {err}")
})?;
let codex_home = match cmd.codex_home.clone() {
Some(codex_home) => codex_home,
None => find_codex_home()?.to_path_buf(),
};
return Ok(SandboxSetupIdentity {
real_user,
codex_home,
});
}
let real_user = cmd
.user
.clone()
.ok_or_else(|| anyhow::anyhow!("--user or --current-user is required"))?;
let codex_home = cmd
.codex_home
.clone()
.ok_or_else(|| anyhow::anyhow!("--codex-home is required with --user"))?;
Ok(SandboxSetupIdentity {
real_user,
codex_home,
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_managed_user_identity() {
let command = SandboxSetupCommand::try_parse_from([
"setup",
"--elevated",
"--user",
"DOMAIN\\alice",
"--codex-home",
r"C:\Users\alice\.akode",
])
.expect("parse");
assert!(command.elevated_sandbox_level);
assert_eq!(command.user.as_deref(), Some(r"DOMAIN\alice"));
assert!(!command.current_user);
assert_eq!(
command.codex_home.as_deref(),
Some(std::path::Path::new(r"C:\Users\alice\.akode"))
);
}
#[test]
fn requires_explicit_user_identity() {
let err = SandboxSetupCommand::try_parse_from(["setup", "--elevated"])
.expect_err("parse should fail");
assert_eq!(err.kind(), clap::error::ErrorKind::MissingRequiredArgument);
}
#[test]
fn requires_codex_home_for_managed_user() {
let err =
SandboxSetupCommand::try_parse_from(["setup", "--elevated", "--user", "DOMAIN\\alice"])
.expect_err("parse should fail");
assert_eq!(err.kind(), clap::error::ErrorKind::MissingRequiredArgument);
}
#[test]
fn parses_setup_from_sandbox_command_args() {
let command = parse_setup_command(&[
"setup".to_string(),
"--elevated".to_string(),
"--user".to_string(),
r"DOMAIN\alice".to_string(),
"--codex-home".to_string(),
r"C:\Users\alice\.akode".to_string(),
])
.expect("parse")
.expect("setup command");
assert_eq!(command.user.as_deref(), Some(r"DOMAIN\alice"));
}
#[test]
fn ignores_non_setup_sandbox_command_args() {
let command =
parse_setup_command(&["echo".to_string(), "hello".to_string()]).expect("parse");
assert!(command.is_none());
}
}

View File

@@ -0,0 +1,21 @@
//! Uninstalls the legacy Windows sandbox without loading config or removing user data.
use clap::Args;
#[derive(Debug, Args)]
#[command(
about = "Remove the legacy Windows sandbox's machine-wide accounts and network rules",
after_help = "Run as administrator after stopping apps using the legacy sandbox and its provisioning service, if installed.\nPreserves aKode home, including sandbox directories and filesystem permissions."
)]
pub(crate) struct SandboxUninstallCommand {}
impl SandboxUninstallCommand {
pub(crate) fn run(self) -> anyhow::Result<()> {
#[cfg(target_os = "windows")]
{
akode_windows_sandbox::clean_up_legacy_windows_sandbox()
}
#[cfg(not(target_os = "windows"))]
anyhow::bail!("`akode sandbox uninstall` is only supported on Windows")
}
}

View File

@@ -0,0 +1,25 @@
---
source: cli/src/doctor.rs
expression: "render_human_report(&report, HumanOutputOptions\n{ show_details: true, show_all: true, ascii: true, color_enabled: false, })"
---
aKode Doctor v0.0.0
Notes
[!!] terminal TERM=dumb - colors and cursor control are disabled in this non-interactive run
-------------------------------------------------------------
Environment
[!!] terminal TERM=dumb - colors and cursor control are disabled in this non-interactive run
terminal dumb
TERM dumb
stdin is terminal false
stdout is terminal false
stderr is terminal false
terminal size 120x40
color output disabled (TERM=dumb)
-------------------------------------------------------------
0 ok | 1 notes | 1 warn | 0 fail degraded
--summary compact output --all expand truncated lists
--json redacted report

View File

@@ -0,0 +1,18 @@
---
source: cli/src/doctor.rs
expression: "render_human_report(&DoctorReport\n{\n schema_version: 1, generated_at: \"0s since unix epoch\".to_string(),\n overall_status: check.status, codex_version: \"0.0.0\".to_string(), checks:\n vec![check],\n}, HumanOutputOptions\n{ show_details: false, show_all: false, ascii: true, color_enabled: false, })"
---
aKode Doctor v0.0.0
Notes
[XX] terminal 3 issues - TERMINFO unreadable - terminal capabilities are unknown; TERM=dumb - colors and cursor control are disabled in this non-interactive run
-------------------------------------------------------------
Environment
[XX] terminal 3 issues - TERMINFO unreadable - terminal capabilities are unknown; TERM=dumb - colors and cursor control are disabled in this non-interactive run
-------------------------------------------------------------
0 ok | 1 notes | 0 warn | 1 fail failed
Run akode doctor without --summary for detailed diagnostics.
--all expand truncated lists --json redacted report

View File

@@ -0,0 +1,67 @@
---
source: cli/src/doctor.rs
expression: rendered
---
successful handshake
aKode Doctor v0.0.0
Connectivity
[ok] network network environment is readable
HTTPS proxy not set
[ok] websocket Responses WebSocket handshake succeeded
handshake result HTTP 101
reasoning header true
server model present true
[ok] reachability active provider endpoints are reachable over HTTP
OpenAI endpoint HTTP 200
-------------------------------------------------------------
3 ok | 0 warn | 0 fail ok
--summary compact output --all expand truncated lists
--json redacted report
immediate close
aKode Doctor v0.0.0
Notes
[!!] websocket Responses WebSocket closed immediately after handshake - Check proxy, VPN, firewall, DNS, custom CA, and WebSocket policy support.
-------------------------------------------------------------
Connectivity
[ok] network network environment is readable
HTTPS proxy not set
[!!] websocket Responses WebSocket closed immediately after handshake - Check proxy, VPN, firewall, DNS, custom CA, and WebSocket policy support.
handshake result HTTP 101
immediate close code 1008
immediate close reason present (redacted)
[ok] reachability active provider endpoints are reachable over HTTP
OpenAI endpoint HTTP 200
-------------------------------------------------------------
2 ok | 1 notes | 1 warn | 0 fail degraded
--summary compact output --all expand truncated lists
--json redacted report
stream failure
aKode Doctor v0.0.0
Notes
[!!] websocket Responses WebSocket failed; HTTPS fallback may still work - Check proxy, VPN, firewall, DNS, custom CA, and WebSocket policy support.
-------------------------------------------------------------
Connectivity
[ok] network network environment is readable
HTTPS proxy not set
[!!] websocket Responses WebSocket failed; HTTPS fallback may still work - Check proxy, VPN, firewall, DNS, custom CA, and WebSocket policy support.
endpoint wss://example.com/responses
handshake stream error [redacted]
[ok] reachability active provider endpoints are reachable over HTTP
OpenAI endpoint HTTP 200
-------------------------------------------------------------
2 ok | 1 notes | 1 warn | 0 fail degraded
--summary compact output --all expand truncated lists
--json redacted report

View File

@@ -0,0 +1,126 @@
---
source: cli/src/exec_server_args_tests.rs
expression: help_text
---
[EXPERIMENTAL] Run the standalone exec-server service
Usage: akode exec-server [OPTIONS] [COMMAND]
Commands:
forward Register an existing WebSocket exec-server as a remote environment
help Print this message or the help of the given subcommand(s)
Options:
-c, --config <key=value>
Override a configuration value that would otherwise be loaded from
`~/.akode/config.toml`. Use a dotted path (`foo.bar.baz`) to override
nested values. The `value` portion is parsed as TOML. If it fails to
parse as TOML, the raw string is used as a literal.
Examples: - `-c model="o3"` - `-c
'sandbox_permissions=["disk-full-read-access"]'` - `-c
shell_environment_policy.inherit=all`
--enable <FEATURE>
Enable a feature (repeatable). Equivalent to `-c features.<name>=true`
--strict-config
Error out when config.toml contains fields that are not recognized by
this version of Codex
--disable <FEATURE>
Disable a feature (repeatable). Equivalent to `-c
features.<name>=false`
--linux-sandbox-pid-namespace <MODE>
Linux PID namespace: isolate (default) or inherit. Inherit allows
signals to other same-UID processes; enable only when provisioning a
dedicated environment
[default: isolate]
--proxy-private-ips-via-upstream
Allow permitted private IP destinations to use the configured upstream
proxy. If no valid upstream proxy applies to the request protocol,
connect directly. Loopback stays local. This flag does not require
upstream routing
[env: AKODE_EXEC_SERVER_PROXY_PRIVATE_IPS_VIA_UPSTREAM]
--concurrent-requests <COUNT>
Maximum number of requests to process concurrently on each connection
[default: 1]
--listen <URL>
Transport endpoint URL. Supported values: `ws://IP:PORT` (default),
`stdio`, `stdio://`
--ws-auth <MODE>
Authentication mode for incoming WebSocket connections
[possible values: capability-token, signed-bearer-token]
--ws-token-file <PATH>
Absolute path to the capability-token file
--ws-token-sha256 <HEX>
Hex-encoded SHA-256 digest of the capability token
--ws-shared-secret-file <PATH>
Absolute path to the shared secret file for signed JWT bearer tokens
--ws-issuer <ISSUER>
Expected issuer for signed JWT bearer tokens
--ws-audience <AUDIENCE>
Expected audience for signed JWT bearer tokens
--ws-max-clock-skew-seconds <SECONDS>
Maximum clock skew when validating signed JWT bearer tokens
--remote <URL>
Register this exec-server as a remote environment using the given base
URL
--remote-transport <REMOTE_TRANSPORT>
Transport used for the remote executor connection
[default: noise]
[possible values: noise, direct]
--environment-id <ID>
Environment id to attach to when registering remotely
--name <NAME>
Human-readable environment name
--registration-bearer-stdin
Read one registration bearer from stdin
--executor-credential-stdin
Read rotating executor credentials from stdin; exit when the pipe
closes
--aws-sigv4
Sign Direct registration and WebSocket handshake requests with AWS
SigV4
--aws-profile <PROFILE>
AWS profile used for SigV4 authentication
--aws-region <REGION>
AWS signing region. Uses the SDK region chain when omitted
--aws-service <SERVICE>
AWS signing service
[default: execute-api]
--exit-on-stdin-close
Exit when the parent-owned standard-input pipe closes
[env: AKODE_EXEC_SERVER_EXIT_ON_STDIN_CLOSE]
-h, --help
Print help (see a summary with '-h')

View File

@@ -0,0 +1,13 @@
---
source: cli/src/main.rs
assertion_line: 3324
expression: "errors.join(\"\\n\")"
---
akode --worktree login: `--worktree` supports new interactive sessions, `akode fork`, `akode exec`, and `akode exec fork`
akode fork --worktree: `akode fork --worktree` requires an explicit session ID
akode fork --worktree --last: `akode fork --worktree` requires an explicit session ID
akode exec resume --worktree session: `--worktree` cannot resume an existing session; use `akode exec fork --worktree`
akode exec review --worktree: `--worktree` is not supported for code review
akode resume --worktree session: `--worktree` supports new interactive sessions, `akode fork`, `akode exec`, and `akode exec fork`
codex archive session --worktree: `--worktree` supports new interactive sessions, `akode fork`, `akode exec`, and `akode exec fork`
codex queue --thread session --message hi --worktree: `--worktree` supports new interactive sessions, `akode fork`, `akode exec`, and `akode exec fork`

View File

@@ -0,0 +1,7 @@
---
source: cli/src/login_storage_tests.rs
assertion_line: 52
expression: "logs.replace(home.path().join(\"secrets\").to_str().unwrap(),\n\"[SECRETS_PATH]\").replace(&cause, \"[OS_ERROR]\")"
---
WARN akode_login::auth::storage: failed to save auth to keyring, falling back to file storage: failed to write CLI auth to encrypted auth storage: failed to create secrets dir [SECRETS_PATH]: [OS_ERROR]
WARN akode_otel::auth_storage: credential storage file fallback completed credential_kind="codex" store_mode="auto" selected_store="secrets" actual_store="file" operation="save" secure_outcome="error" outcome="success" fallback_reason="secure_error" secure_error="other" storage_phase="policy" originator="none"

View File

@@ -0,0 +1,6 @@
---
source: cli/src/login_storage_tests.rs
assertion_line: 81
expression: "message.replace(secrets_path.to_str().unwrap(),\n\"[SECRETS_PATH]\").replace(&cause, \"[OS_ERROR]\")"
---
failed to write CLI auth to encrypted auth storage: failed to create secrets dir [SECRETS_PATH]: [OS_ERROR]

View File

@@ -0,0 +1,156 @@
//! CLI handling for local state database startup failures.
//!
//! This keeps user-facing backup and lock-contention handling out of the main
//! CLI dispatch path while preserving the TUI startup error as the boundary type.
use akode_state::RuntimeDbBackup;
use akode_tui::LocalStateDbStartupError;
use std::io::IsTerminal;
use std::path::Path;
pub(crate) fn startup_error(err: &std::io::Error) -> Option<&LocalStateDbStartupError> {
err.get_ref()
.and_then(|err| err.downcast_ref::<LocalStateDbStartupError>())
}
pub(crate) fn is_locked(detail: &str) -> bool {
akode_state::sqlite_error_detail_is_lock(detail)
}
pub(crate) fn is_auto_backup_recoverable(startup_error: &LocalStateDbStartupError) -> bool {
startup_error.is_corruption() || sqlite_home_is_blocking_file(startup_error)
}
fn sqlite_home_is_blocking_file(startup_error: &LocalStateDbStartupError) -> bool {
startup_error
.database_path()
.parent()
.and_then(|path| std::fs::metadata(path).ok())
.is_some_and(|metadata| metadata.is_file())
}
pub(crate) fn print_auto_backup_start(startup_error: &LocalStateDbStartupError) {
eprintln!("aKode couldn't start because its local database appears to be damaged.");
eprintln!("Moving the damaged local database aside so aKode can rebuild it from saved data.");
print_technical_details(startup_error);
}
pub(crate) async fn backup_files_for_fresh_start(
startup_error: &LocalStateDbStartupError,
) -> std::io::Result<Vec<RuntimeDbBackup>> {
akode_state::backup_runtime_db_for_fresh_start(startup_error.database_path()).await
}
pub(crate) fn confirm_fresh_start_rebuild(
startup_error: &LocalStateDbStartupError,
backups: &[RuntimeDbBackup],
) -> std::io::Result<()> {
eprintln!("aKode rebuilt its local database.");
eprintln!(
"aKode detected a damaged local database, moved it into a backup folder, and will continue startup with a fresh database."
);
eprintln!("Database path: {}", startup_error.database_path().display());
if let Some(backup_folder) = backup_folder(backups) {
eprintln!("Backup folder: {}", backup_folder.display());
} else {
eprintln!("Backup folder: unavailable");
}
if std::io::stdin().is_terminal() && std::io::stderr().is_terminal() {
eprintln!("Press Enter to continue.");
let mut input = String::new();
std::io::stdin().read_line(&mut input)?;
} else {
eprintln!("Continuing startup with a fresh local database...");
}
Ok(())
}
pub(crate) fn print_diagnostic_guidance(startup_error: &LocalStateDbStartupError) {
eprintln!("aKode couldn't start because its local database appears to be damaged.");
eprintln!("Run `akode doctor` to check your setup and get next-step guidance.");
eprintln!("If this keeps happening, share the technical details below when asking for help.");
print_technical_details(startup_error);
}
pub(crate) fn print_locked_guidance(startup_error: &LocalStateDbStartupError) {
eprintln!("aKode couldn't start because another aKode process is using its local data.");
eprintln!("Quit any other copies of aKode that may still be running, then try again.");
print_technical_details(startup_error);
}
fn print_technical_details(startup_error: &LocalStateDbStartupError) {
eprintln!("Technical details:");
eprintln!(" Location: {}", startup_error.database_path().display());
eprintln!(" Cause: {}", startup_error.detail());
}
fn backup_folder(backups: &[RuntimeDbBackup]) -> Option<&Path> {
backups.first()?.backup_path.parent()
}
#[cfg(test)]
mod tests {
use super::*;
use akode_utils_absolute_path::test_support::PathExt;
use pretty_assertions::assert_eq;
use std::path::PathBuf;
use tempfile::TempDir;
#[tokio::test]
async fn backup_backs_up_only_failed_database_file() -> std::io::Result<()> {
let temp_dir = TempDir::new()?;
let sqlite = akode_state::SqliteConfig::new_for_testing(temp_dir.path().abs());
let state_path = sqlite.state_db_path();
let failed_db_path = sqlite.logs_db_path();
tokio::fs::write(state_path.as_path(), b"state").await?;
tokio::fs::write(failed_db_path.as_path(), b"logs").await?;
let startup_error =
LocalStateDbStartupError::new(failed_db_path.clone(), anyhow::anyhow!("corrupt"));
let backups = backup_files_for_fresh_start(&startup_error).await?;
assert_eq!(
backups
.iter()
.map(|backup| &backup.original_path)
.collect::<Vec<_>>(),
vec![&failed_db_path]
);
assert!(!tokio::fs::try_exists(failed_db_path.as_path()).await?);
assert!(tokio::fs::try_exists(state_path.as_path()).await?);
assert!(tokio::fs::try_exists(backups[0].backup_path.as_path()).await?);
Ok(())
}
#[tokio::test]
async fn backup_replaces_blocking_sqlite_home_file() -> std::io::Result<()> {
let temp_dir = TempDir::new()?;
let sqlite_home = temp_dir.path().join("sqlite-home");
tokio::fs::write(sqlite_home.as_path(), b"not-a-directory").await?;
let sqlite = akode_state::SqliteConfig::new_for_testing(sqlite_home.as_path().abs());
let startup_error =
LocalStateDbStartupError::new(sqlite.state_db_path(), anyhow::anyhow!("File exists"));
assert!(is_auto_backup_recoverable(&startup_error));
let backups = backup_files_for_fresh_start(&startup_error).await?;
assert_eq!(backups.len(), 1);
assert!(tokio::fs::metadata(sqlite_home.as_path()).await?.is_dir());
assert!(tokio::fs::try_exists(backups[0].backup_path.as_path()).await?);
Ok(())
}
#[test]
fn backup_folder_uses_parent_of_first_backup_path() {
let backups = vec![RuntimeDbBackup {
original_path: PathBuf::from("/tmp/state_5.sqlite"),
backup_path: PathBuf::from("/tmp/db-backups/sqlite-1-0/state_5.sqlite"),
}];
assert_eq!(
backup_folder(&backups),
Some(Path::new("/tmp/db-backups/sqlite-1-0"))
);
}
}

View File

@@ -0,0 +1,59 @@
use std::ffi::OsStr;
/// Returns true if the current process is running under WSL.
pub use akode_utils_path::is_wsl;
/// Convert a Windows absolute path (`C:\foo\bar` or `C:/foo/bar`) to a WSL mount path (`/mnt/c/foo/bar`).
/// Returns `None` if the input does not look like a Windows drive path.
pub fn win_path_to_wsl(path: &str) -> Option<String> {
let bytes = path.as_bytes();
if bytes.len() < 3
|| bytes[1] != b':'
|| !(bytes[2] == b'\\' || bytes[2] == b'/')
|| !bytes[0].is_ascii_alphabetic()
{
return None;
}
let drive = (bytes[0] as char).to_ascii_lowercase();
let tail = path[3..].replace('\\', "/");
if tail.is_empty() {
return Some(format!("/mnt/{drive}"));
}
Some(format!("/mnt/{drive}/{tail}"))
}
/// If under WSL and given a Windows-style path, return the equivalent `/mnt/<drive>/…` path.
/// Otherwise returns the input unchanged.
pub fn normalize_for_wsl<P: AsRef<OsStr>>(path: P) -> String {
let value = path.as_ref().to_string_lossy().to_string();
if !is_wsl() {
return value;
}
if let Some(mapped) = win_path_to_wsl(&value) {
return mapped;
}
value
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn win_to_wsl_basic() {
assert_eq!(
win_path_to_wsl(r"C:\Temp\codex.zip").as_deref(),
Some("/mnt/c/Temp/codex.zip")
);
assert_eq!(
win_path_to_wsl("D:/Work/codex.tgz").as_deref(),
Some("/mnt/d/Work/codex.tgz")
);
assert!(win_path_to_wsl("/home/user/codex").is_none());
}
#[test]
fn normalize_is_noop_on_unix_paths() {
assert_eq!(normalize_for_wsl("/home/u/x"), "/home/u/x");
}
}

View File

@@ -0,0 +1,339 @@
use std::path::Path;
use anyhow::Result;
use app_test_support::app_server_json_shutdown_event;
use predicates::str::contains;
use pretty_assertions::assert_eq;
use serde_json::json;
use tempfile::TempDir;
fn codex_command(codex_home: &Path) -> Result<assert_cmd::Command> {
let mut cmd = assert_cmd::Command::new(akode_utils_cargo_bin::cargo_bin("akode")?);
cmd.env("AKODE_HOME", codex_home)
.env_remove("AKODE_ACCESS_TOKEN")
.env_remove("AKODE_API_KEY")
.env_remove("OPENAI_API_KEY")
.env_remove("OPENAI_FEDERATION_RULE_ID")
.env_remove("OPENAI_IDENTITY_TOKEN_FILE")
.env_remove("OPENAI_WORKLOAD_IDENTITY_CONTEXT");
Ok(cmd)
}
#[test]
fn strict_config_rejects_unknown_config_fields_for_app_server() -> Result<()> {
let codex_home = TempDir::new()?;
std::fs::write(
codex_home.path().join("config.toml"),
r#"
foo = "bar"
"#,
)?;
let mut cmd = codex_command(codex_home.path())?;
cmd.args(["app-server", "--strict-config", "--listen", "off"])
.assert()
.failure()
.stderr(contains("unknown configuration field"));
Ok(())
}
#[test]
fn app_server_preserves_config_overrides_across_subcommand() -> Result<()> {
let home = TempDir::new()?;
codex_command(home.path())?
.args([
"-c",
"missing-equals",
"app-server",
"--print-startup-config",
"-c",
"model=example",
])
.assert()
.failure()
.stdout(contains("Invalid override (missing '='): missing-equals"));
Ok(())
}
#[test]
fn agents_accept_interactive_configuration_overrides() -> Result<()> {
let codex_home = TempDir::new()?;
for args in [
["-c", "features.multi_agent_mode=true", "agents"].as_slice(),
["--enable", "multi_agent_mode", "agents"].as_slice(),
["--yolo", "agents"].as_slice(),
["--no-daemon", "agents"].as_slice(),
["agents", "--no-daemon"].as_slice(),
["--search", "agents"].as_slice(),
["--model", "gpt-5", "agents"].as_slice(),
["--approve-for-me", "agents"].as_slice(),
["--cd", ".", "agents"].as_slice(),
] {
let mut cmd = codex_command(codex_home.path())?;
cmd.env("TERM", "xterm-256color").args(args);
cmd.assert()
.failure()
.stderr(contains("stdin is not a terminal"));
}
Ok(())
}
#[test]
fn agents_reject_inputs_that_cannot_be_applied() -> Result<()> {
let codex_home = TempDir::new()?;
for (args, expected_error) in [
(
["--image=image.png", "agents"].as_slice(),
"does not accept an initial prompt or images",
),
(
["--oss", "agents", "--remote", "ws://127.0.0.1:4512"].as_slice(),
"cannot apply local provider or additional-directory overrides",
),
(
[
"--add-dir",
".",
"agents",
"--remote",
"ws://127.0.0.1:4512",
]
.as_slice(),
"cannot apply local provider or additional-directory overrides",
),
(
[
"-c",
"sandbox_workspace_write.writable_roots=[\"../shared\"]",
"agents",
"--remote",
"ws://127.0.0.1:4512",
]
.as_slice(),
"cannot apply local provider or additional-directory overrides",
),
] {
let mut cmd = codex_command(codex_home.path())?;
cmd.args(args)
.assert()
.failure()
.stderr(contains(expected_error));
}
Ok(())
}
#[test]
fn app_server_emits_json_info_events() -> Result<()> {
let codex_home = TempDir::new()?;
let event = app_server_json_shutdown_event("codex", &["app-server"], codex_home.path())?;
assert_eq!(
event,
json!({
"level": "INFO",
"fields": {
"message": "processor task exited",
"exit_reason": "stdio_connection_closed",
"remaining_connection_count": 0,
"shutdown_forced": false,
},
"target": "akode_app_server",
})
);
Ok(())
}
#[test]
fn app_server_keeps_sqlite_logs_in_overridden_sqlite_home() -> Result<()> {
let home = TempDir::new()?;
let sqlite_home = TempDir::new()?;
std::fs::write(
home.path().join("config.toml"),
"[features]\nplugins = false\n",
)?;
codex_command(home.path())?
.env("AKODE_SQLITE_HOME", sqlite_home.path())
.env(
"AKODE_APP_SERVER_MANAGED_CONFIG_PATH",
home.path().join("managed_config.toml"),
)
.arg("app-server")
.write_stdin("")
.assert()
.success();
assert!(sqlite_home.path().join("state_5.sqlite").is_file());
assert!(std::fs::metadata(sqlite_home.path().join("logs_2.sqlite"))?.len() > 0);
assert!(!home.path().join("logs_2.sqlite").exists());
assert!(!home.path().join("log/logs_2.sqlite").exists());
Ok(())
}
#[cfg(unix)]
#[test]
fn app_server_preserves_the_existing_sqlite_logs_symlink() -> Result<()> {
let home = TempDir::new()?;
let external_logs = TempDir::new()?;
let target = external_logs.path().join("logs_2.sqlite");
let link = home.path().join("logs_2.sqlite");
std::os::unix::fs::symlink(&target, &link)?;
std::fs::write(
home.path().join("config.toml"),
"[features]\nplugins = false\n",
)?;
codex_command(home.path())?
.env_remove("AKODE_SQLITE_HOME")
.env(
"AKODE_APP_SERVER_MANAGED_CONFIG_PATH",
home.path().join("managed_config.toml"),
)
.arg("app-server")
.write_stdin("")
.assert()
.success();
assert_eq!(std::fs::read_link(&link)?, target);
assert!(std::fs::metadata(&target)?.len() > 0);
assert!(home.path().join("state_5.sqlite").is_file());
assert!(!home.path().join("log/logs_2.sqlite").exists());
Ok(())
}
#[test]
fn print_startup_config_preserves_project_login_restrictions() -> Result<()> {
let home = TempDir::new()?;
let project = TempDir::new()?;
let project_key =
serde_json::to_string(&akode_config::loader::project_trust_key(project.path()))?;
std::fs::write(
home.path().join("config.toml"),
format!("[projects.{project_key}]\ntrust_level = \"trusted\"\n"),
)?;
std::fs::create_dir(project.path().join(".git"))?;
std::fs::create_dir(project.path().join(".akode"))?;
for method in ["chatgpt", "api"] {
std::fs::write(
project.path().join(".akode/config.toml"),
format!("forced_login_method = '{method}'\n"),
)?;
for sign_out in [None, Some("--startup-sign-out")] {
let mut command = codex_command(home.path())?;
command
.current_dir(project.path())
.args(["app-server", "--print-startup-config"])
.args(sign_out);
let output = command.assert().success();
let value: serde_json::Value = serde_json::from_slice(&output.get_output().stdout)?;
assert_eq!(
value["configRequirements"]["requirements"]["allowedLoginMethods"],
json!([method])
);
}
}
Ok(())
}
#[test]
fn print_startup_config_validates_configuration() -> Result<()> {
let home = TempDir::new()?;
let config_path = home.path().join("config.toml");
for (config, strict_arg, error) in [
("[broken\n", None, Some("failed to load configuration")),
(
"unknown_future_setting = true\n",
Some("--strict-config"),
Some("unknown configuration field"),
),
("unknown_future_setting = true\n", None, None),
] {
std::fs::write(&config_path, config)?;
let output = codex_command(home.path())?
.args(["app-server", "--print-startup-config"])
.args(strict_arg)
.assert();
let value: serde_json::Value = serde_json::from_slice(&output.get_output().stdout)?;
if let Some(error) = error {
output.failure().stdout(contains(error));
assert_eq!(value["error"]["data"]["reason"], "configLoad");
assert_eq!(
Path::new(value["error"]["data"]["filePath"].as_str().unwrap()).canonicalize()?,
config_path.canonicalize()?
);
assert!(value["error"]["data"]["line"].as_u64().is_some());
assert!(value.get("configRequirements").is_none());
} else {
output.success();
assert_eq!(value["appServerVersion"], env!("CARGO_PKG_VERSION"));
assert!(value["configRequirements"].get("requirements").is_some());
assert!(value.get("config").is_none());
}
}
Ok(())
}
#[tokio::test]
async fn print_startup_config_is_independent_of_a_locked_history_database() -> Result<()> {
use sqlx::Executor;
use std::time::Duration;
use tokio::process::Command;
use tokio::time::timeout;
let home = TempDir::new()?;
let sqlite = TempDir::new()?;
let binary = akode_utils_cargo_bin::cargo_bin("akode")?;
let mut command = Command::new(&binary);
command
.env("AKODE_HOME", home.path())
.env("AKODE_SQLITE_HOME", sqlite.path())
.env_remove("AKODE_ACCESS_TOKEN")
.env_remove("AKODE_API_KEY")
.env_remove("OPENAI_API_KEY")
.env_remove("OPENAI_FEDERATION_RULE_ID")
.env_remove("OPENAI_IDENTITY_TOKEN_FILE")
.env_remove("OPENAI_WORKLOAD_IDENTITY_CONTEXT")
.args(["app-server", "--print-startup-config"])
.kill_on_drop(true);
let baseline = timeout(Duration::from_secs(10), command.output()).await??;
assert!(baseline.status.success());
let path = sqlite.path().join("state_5.sqlite");
let sqlite_config = akode_state::SqliteConfig::new_for_testing(
akode_utils_absolute_path::AbsolutePathBuf::from_absolute_path(sqlite.path())?,
);
let pool = sqlite_config.open_read_write_pool(&path).await?;
let mut database = pool.acquire().await?;
database
.execute("CREATE TABLE synthetic_history (id INTEGER)")
.await?;
database.execute("PRAGMA journal_mode=DELETE").await?;
let readers = sqlite_config
.open_read_only_pool(&path, Some(Duration::ZERO))
.await?;
let mut reader = readers.acquire().await?;
database.execute("BEGIN EXCLUSIVE").await?;
assert!(
reader
.execute("SELECT * FROM synthetic_history")
.await
.is_err()
);
let before = std::fs::read(&path)?;
let output = timeout(Duration::from_secs(10), command.output()).await??;
assert!(output.status.success());
assert_eq!(
serde_json::from_slice::<serde_json::Value>(&output.stdout)?,
serde_json::from_slice::<serde_json::Value>(&baseline.stdout)?
);
assert_eq!(std::fs::read(&path)?, before);
database.execute("ROLLBACK").await?;
Ok(())
}

View File

@@ -0,0 +1,552 @@
//! Managed daemon lifecycle through the public CLI, using isolated standalone fixtures.
#![cfg(unix)]
#[path = "app_server_daemon/support.rs"]
mod support;
use support::TestDaemon;
use support::signal;
use support::wait_for_exit;
use std::process::Command;
use std::process::Stdio;
use std::time::Duration;
use std::time::Instant;
use anyhow::Context;
use anyhow::Result;
use anyhow::ensure;
use pretty_assertions::assert_eq;
use serde_json::Value;
#[test]
fn managed_daemon_restarts_from_deleted_working_directory() -> Result<()> {
let daemon = TestDaemon::new()?;
let project = daemon.home.path().join("project");
std::fs::create_dir(&project)?;
let started = daemon
.command()
.current_dir(&project)
.args(["app-server", "daemon", "start"])
.output()?;
ensure!(
started.status.success(),
"{}",
String::from_utf8_lossy(&started.stderr)
);
let old_pid = daemon.pid("app-server.pid")?;
let old_updater_pid = daemon.pid("app-server-updater.pid")?;
signal(old_updater_pid, libc::SIGTERM)?;
wait_for_exit(old_updater_pid)?;
// Delete the restart caller's cwd without changing the test process's cwd.
let restarted = Command::new("/bin/sh")
.args([
"-c",
"rmdir \"$1\" && exec \"$2\" app-server daemon restart",
"restart",
])
.arg(&project)
.arg(&daemon.codex)
.current_dir(&project)
.env("AKODE_HOME", daemon.home.path())
.output()?;
ensure!(
restarted.status.success(),
"{}",
String::from_utf8_lossy(&restarted.stderr)
);
let restarted: Value = serde_json::from_slice(&restarted.stdout)?;
assert_eq!(restarted["status"], "restarted");
assert_ne!(daemon.pid("app-server.pid")?, old_pid);
assert_ne!(daemon.pid("app-server-updater.pid")?, old_updater_pid);
assert_eq!(daemon.lifecycle("version")?["status"], "running");
let updater_socket = daemon
.home
.path()
.join("app-server-daemon/app-server-updater.sock");
let deadline = Instant::now() + Duration::from_secs(30);
while std::os::unix::net::UnixStream::connect(&updater_socket).is_err() {
ensure!(
Instant::now() < deadline,
"replacement updater did not become ready"
);
std::thread::sleep(Duration::from_millis(50));
}
Ok(())
}
#[test]
fn bootstrap_updater_is_ready_in_deep_codex_home() -> Result<()> {
let mut daemon = TestDaemon::new()?;
let deep_home = tempfile::Builder::new()
.prefix(&"deep-codex-home-".repeat(8))
.tempdir_in("/tmp")?;
for name in ["packages", "app-server-daemon"] {
std::fs::rename(daemon.home.path().join(name), deep_home.path().join(name))?;
}
daemon.home = deep_home;
let state = daemon.home.path().join("app-server-daemon");
std::fs::write(
state.join("settings.json"),
br#"{"shutdownGraceSeconds":0}"#,
)?;
let socket = state.join("app-server-updater.sock");
let result = daemon.lifecycle("bootstrap")?;
assert_eq!(result["autoUpdateEnabled"], true);
assert_eq!(result["status"], "bootstrapped");
signal(daemon.pid("app-server-updater.pid")?, /*signal*/ 0)?;
let target = socket.canonicalize()?;
let _connection = std::os::unix::net::UnixStream::connect(target)?;
assert_eq!(daemon.lifecycle("version")?["status"], "running");
Ok(())
}
#[test]
fn bootstrap_reports_updater_bind_failure() -> Result<()> {
let daemon = TestDaemon::new()?;
let state = daemon.home.path().join("app-server-daemon");
std::fs::write(
state.join("settings.json"),
br#"{"shutdownGraceSeconds":0}"#,
)?;
let socket = state.join("app-server-updater.sock");
std::fs::write(&socket, b"not a socket")?;
let result = daemon
.command()
.args(["app-server", "daemon", "bootstrap"])
.output()?;
assert!(!result.status.success());
assert_eq!(std::fs::read(socket)?, b"not a socket");
assert_eq!(daemon.lifecycle("version")?["status"], "running");
Ok(())
}
#[test]
fn explicit_restart_applies_feature_overrides_and_preserves_saved_settings() -> Result<()> {
let daemon = TestDaemon::new()?;
let settings_path = daemon.home.path().join("app-server-daemon/settings.json");
std::fs::write(
&settings_path,
serde_json::to_vec(&serde_json::json!({
"shutdownGraceSeconds": 0,
"updater": { "autoUpdateEnabled": false },
"featureOverrides": {
"api_key_model_discovery": false,
"auth_elicitation": true,
"connectors": true,
"apps": true
}
}))?,
)?;
let mut previous_pid = None;
// Start from a stopped daemon, change running settings, and restart again
// with omitted flags. Every explicit restart replaces the process.
for (args, discovery) in [
(
vec![
"--enable",
"api_key_model_discovery",
"--disable",
"connectors",
"-c",
"features.network_proxy.enabled=false",
],
true,
),
(vec!["--disable", "api_key_model_discovery"], false),
(vec!["-c", "features.api_key_model_discovery=true"], true),
(vec![], true),
] {
let output = daemon
.command()
.args(["app-server", "daemon", "restart"])
.args(args)
.output()?;
ensure!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
let output: Value = serde_json::from_slice(&output.stdout)?;
assert_eq!(output["status"], "restarted");
let pid = output["pid"].as_u64().context("restarted daemon PID")?;
assert_ne!(Some(pid), previous_pid);
previous_pid = Some(pid);
let settings: Value = serde_json::from_slice(&std::fs::read(&settings_path)?)?;
assert_eq!(
settings["featureOverrides"],
serde_json::json!({
"api_key_model_discovery": discovery,
"auth_elicitation": true,
"apps": false,
"network_proxy": false
})
);
assert_eq!(settings["updater"]["autoUpdateEnabled"], false);
}
// Non-toggle config keys must fail before stopping the daemon or saving settings.
let saved_settings = std::fs::read(&settings_path)?;
let output = daemon
.command()
.args([
"app-server",
"daemon",
"restart",
"--enable",
"tool_registry",
])
.output()?;
assert!(!output.status.success());
insta::assert_snapshot!(
String::from_utf8(output.stderr)?,
@"Error: daemon restart requires a boolean feature toggle: tool_registry"
);
assert_eq!(std::fs::read(&settings_path)?, saved_settings);
assert_eq!(Some(u64::from(daemon.pid("app-server.pid")?)), previous_pid);
assert_eq!(daemon.lifecycle("version")?["status"], "running");
Ok(())
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
#[test]
fn managed_identity_survives_locale_and_timezone_changes() -> Result<()> {
let daemon = TestDaemon::new()?;
let mut original = Vec::new();
let mut updater_pid = 0;
let pid_file = daemon.home.path().join("app-server-daemon/app-server.pid");
for (action, locale, timezone, expected_status) in [
("start", "C", "UTC0", "started"),
("version", "en_AU.UTF-8", "PST8PDT", "running"),
("restart", "en_AU.UTF-8", "PST8PDT", "restarted"),
("stop", "C", "UTC0", "stopped"),
] {
let output = daemon
.command()
.args(["app-server", "daemon", action])
.env("LC_ALL", locale)
.env("TZ", timezone)
.output()?;
ensure!(
output.status.success(),
"daemon {action} failed: {}",
String::from_utf8_lossy(&output.stderr)
);
let output: Value = serde_json::from_slice(&output.stdout)?;
assert_eq!(output["status"], expected_status);
if action == "start" {
updater_pid = daemon.pid("app-server-updater.pid")?;
original = std::fs::read(&pid_file)?;
let record: Value = serde_json::from_slice(&original)?;
assert!(record["processIdentity"].is_object());
// Older clients still receive the original, unnormalized ps value.
let legacy = Command::new("ps")
.args([
"-p",
&daemon.pid("app-server.pid")?.to_string(),
"-o",
"lstart=",
])
.env("LC_ALL", locale)
.env("TZ", timezone)
.output()?;
ensure!(legacy.status.success(), "failed to read legacy start time");
assert_eq!(
record["processStartTime"],
String::from_utf8(legacy.stdout)?.trim()
);
} else if action == "version" {
assert_eq!(output["backend"], "pid");
assert_eq!(daemon.pid("app-server-updater.pid")?, updater_pid);
assert_eq!(std::fs::read(&pid_file)?, original);
// Finish startup promotion before deliberately restoring a legacy record.
let updater_socket = daemon
.home
.path()
.join("app-server-daemon/app-server-updater.sock");
let deadline = Instant::now() + Duration::from_secs(30);
while !updater_socket.exists() {
ensure!(Instant::now() < deadline, "updater did not become ready");
std::thread::sleep(Duration::from_millis(50));
}
let mut legacy: Value = serde_json::from_slice(&original)?;
legacy
.as_object_mut()
.context("PID record object")?
.remove("processIdentity");
let legacy_bytes = serde_json::to_vec(&legacy)?;
std::fs::write(&pid_file, &legacy_bytes)?;
let result = daemon
.command()
.args(["app-server", "daemon", "version"])
.env("LC_ALL", locale)
.env("TZ", timezone)
.output();
let preserved = std::fs::read(&pid_file);
// Restore the native identity before assertions so Drop can stop the daemon.
std::fs::write(&pid_file, &original)?;
let result = result?;
assert!(!result.status.success());
assert_eq!(preserved?, legacy_bytes);
let stderr =
String::from_utf8(result.stderr)?.replace(&legacy["pid"].to_string(), "[PID]");
insta::assert_snapshot!(stderr, @"Error: cannot verify pid-managed process [PID]: legacy start time changed; PID record retained. Retry with the locale and timezone used to start the daemon. If the system clock changed, stop the original process before restarting the daemon");
}
if action == "restart" {
assert_eq!(daemon.pid("app-server-updater.pid")?, updater_pid);
}
}
assert!(!pid_file.exists());
Ok(())
}
#[test]
fn package_ownership_check_does_not_start_an_updater() -> Result<()> {
let daemon = TestDaemon::new()?;
let output = daemon
.command()
.args([
"app-server",
"daemon",
"pid-update-loop",
"--check-package-ownership",
])
.output()?;
ensure!(
output.status.success(),
"ownership check failed: {}",
String::from_utf8_lossy(&output.stderr)
);
let state = daemon.home.path().join("app-server-daemon");
assert!(!state.join("app-server-updater.pid").exists());
assert!(!state.join("daemon-updater.pid").exists());
Ok(())
}
#[test]
fn managed_starts_ensure_one_updater_and_recover_a_missing_one() -> Result<()> {
let daemon = TestDaemon::new()?;
assert_eq!(daemon.lifecycle("start")?["status"], "started");
let backend_pid = daemon.pid("app-server.pid")?;
let updater_pid = daemon.pid("app-server-updater.pid")?;
assert_ne!(backend_pid, updater_pid);
assert_eq!(daemon.lifecycle("start")?["status"], "alreadyRunning");
assert_eq!(daemon.pid("app-server.pid")?, backend_pid);
assert_eq!(daemon.pid("app-server-updater.pid")?, updater_pid);
signal(updater_pid, libc::SIGTERM)?;
wait_for_exit(updater_pid)?;
// A replacement updater also upgrades still-verifiable records left by an old CLI.
let server_record_path = daemon.home.path().join("app-server-daemon/app-server.pid");
let mut legacy: Value = serde_json::from_slice(&std::fs::read(&server_record_path)?)?;
let native = legacy.as_object_mut().unwrap().remove("processIdentity");
std::fs::write(&server_record_path, serde_json::to_vec(&legacy)?)?;
assert_eq!(daemon.lifecycle("start")?["status"], "alreadyRunning");
assert_eq!(daemon.pid("app-server.pid")?, backend_pid);
let replacement_pid = daemon.pid("app-server-updater.pid")?;
assert_ne!(replacement_pid, updater_pid);
if let Some(native) = native {
legacy["processIdentity"] = native;
let deadline = Instant::now() + Duration::from_secs(30);
loop {
let record: Value = serde_json::from_slice(&std::fs::read(&server_record_path)?)?;
if record == legacy {
break;
}
ensure!(
Instant::now() < deadline,
"legacy record was not upgraded: {record}"
);
std::thread::sleep(Duration::from_millis(50));
}
}
assert_eq!(daemon.lifecycle("restart")?["status"], "restarted");
assert_ne!(daemon.pid("app-server.pid")?, backend_pid);
assert_eq!(daemon.pid("app-server-updater.pid")?, replacement_pid);
daemon.lifecycle("stop")?;
assert!(
!daemon
.home
.path()
.join("app-server-daemon/app-server.pid")
.exists()
);
assert_eq!(daemon.lifecycle("start")?["status"], "started");
assert!(
!daemon
.home
.path()
.join("packages/app-server-daemon")
.exists()
);
Ok(())
}
#[test]
fn managed_start_succeeds_when_updater_record_is_invalid() -> Result<()> {
let daemon = TestDaemon::new()?;
let state_dir = daemon.home.path().join("app-server-daemon");
std::fs::create_dir_all(&state_dir)?;
std::fs::write(state_dir.join("app-server-updater.pid"), "not a PID record")?;
assert_eq!(daemon.lifecycle("start")?["status"], "started");
let server_pid = daemon.pid("app-server.pid")?;
assert_eq!(daemon.lifecycle("start")?["status"], "alreadyRunning");
assert_eq!(daemon.pid("app-server.pid")?, server_pid);
Ok(())
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
#[test]
fn wall_clock_shift_keeps_server_and_updater_managed() -> Result<()> {
let daemon = TestDaemon::new()?;
assert_eq!(daemon.lifecycle("start")?["status"], "started");
let server_pid = daemon.pid("app-server.pid")?;
let updater_pid = daemon.pid("app-server-updater.pid")?;
for name in ["app-server.pid", "app-server-updater.pid"] {
let path = daemon.home.path().join("app-server-daemon").join(name);
let mut record: Value = serde_json::from_slice(&std::fs::read(&path)?)?;
record["processStartTime"] = "historical wall-clock start time".into();
let replacement = path.with_extension("replacement");
std::fs::write(&replacement, serde_json::to_vec(&record)?)?;
std::fs::rename(replacement, path)?;
}
let version = daemon.lifecycle("version")?;
assert_eq!(version["status"], "running");
assert_eq!(version["backend"], "pid");
assert_eq!(daemon.lifecycle("start")?["status"], "alreadyRunning");
assert_eq!(daemon.pid("app-server.pid")?, server_pid);
assert_eq!(daemon.pid("app-server-updater.pid")?, updater_pid);
assert_eq!(daemon.lifecycle("restart")?["status"], "restarted");
wait_for_exit(server_pid)?;
assert_ne!(daemon.pid("app-server.pid")?, server_pid);
assert_eq!(daemon.pid("app-server-updater.pid")?, updater_pid);
Ok(())
}
#[test]
fn managed_start_keeps_updater_on_marker_mismatch_but_stops_it_for_pin() -> Result<()> {
let daemon = TestDaemon::new()?;
assert_eq!(daemon.lifecycle("start")?["status"], "started");
let updater_pid = daemon.pid("app-server-updater.pid")?;
let marker = daemon
.home
.path()
.join("packages/standalone/auto-update-version");
std::fs::write(&marker, "0.1.0-other-target")?;
assert_eq!(daemon.lifecycle("start")?["status"], "alreadyRunning");
assert_eq!(daemon.pid("app-server-updater.pid")?, updater_pid);
std::thread::sleep(Duration::from_millis(250));
let updater_state = Command::new("/bin/ps")
.args(["-p", &updater_pid.to_string(), "-o", "stat="])
.output()?;
ensure!(
updater_state.status.success()
&& !String::from_utf8_lossy(&updater_state.stdout)
.trim()
.starts_with('Z'),
"updater exited during the latest marker transition"
);
std::fs::remove_file(marker)?;
assert_eq!(daemon.lifecycle("start")?["status"], "alreadyRunning");
wait_for_exit(updater_pid)?;
assert!(
!daemon
.home
.path()
.join("app-server-daemon/app-server-updater.pid")
.exists()
);
Ok(())
}
#[test]
fn restart_applies_saved_updater_preference() -> Result<()> {
let daemon = TestDaemon::new()?;
assert_eq!(daemon.lifecycle("start")?["status"], "started");
let updater_pid = daemon.pid("app-server-updater.pid")?;
let settings = daemon.home.path().join("app-server-daemon/settings.json");
std::fs::write(
&settings,
serde_json::to_vec(&serde_json::json!({
"updater": {"autoUpdateEnabled": false, "updateIntervalMinutes": 2},
}))?,
)?;
assert_eq!(daemon.lifecycle("restart")?["status"], "restarted");
wait_for_exit(updater_pid)?;
assert!(daemon.pid("app-server-updater.pid").is_err());
assert_eq!(daemon.lifecycle("bootstrap")?["autoUpdateEnabled"], false);
assert!(daemon.pid("app-server-updater.pid").is_err());
std::fs::write(
&settings,
serde_json::to_vec(&serde_json::json!({
"updater": {"autoUpdateEnabled": true, "updateIntervalMinutes": 2},
}))?,
)?;
assert_eq!(daemon.lifecycle("restart")?["status"], "restarted");
assert_ne!(daemon.pid("app-server-updater.pid")?, updater_pid);
std::fs::write(&settings, "{malformed")?;
assert_eq!(daemon.lifecycle("stop")?["status"], "stopped");
Ok(())
}
#[test]
fn unmanaged_app_server_does_not_launch_updater() -> Result<()> {
let mut daemon = TestDaemon::new()?;
daemon.unmanaged = Some(
daemon
.command()
.args(["app-server", "--listen", "unix://"])
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()?,
);
let deadline = Instant::now() + Duration::from_secs(30);
while !daemon
.command()
.args(["app-server", "daemon", "version"])
.output()?
.status
.success()
{
ensure!(Instant::now() < deadline, "app server did not become ready");
std::thread::sleep(Duration::from_millis(50));
}
let output = daemon.lifecycle("start")?;
assert_eq!(output["status"], "alreadyRunning");
assert_eq!(output["backend"], Value::Null);
assert_eq!(daemon.lifecycle("update")?["status"], "unsupported");
assert!(
!daemon
.home
.path()
.join("app-server-daemon/app-server-updater.pid")
.exists()
);
Ok(())
}
#[test]
fn manual_update_rejects_an_unowned_installation() -> Result<()> {
let daemon = TestDaemon::new()?;
std::fs::remove_file(
daemon
.home
.path()
.join("packages/standalone/current/bin/akode"),
)?;
assert_eq!(daemon.lifecycle("update")?["status"], "unsupported");
assert!(daemon.pid("app-server.pid").is_err());
assert!(daemon.pid("app-server-updater.pid").is_err());
Ok(())
}

View File

@@ -0,0 +1,223 @@
//! Real package installation and replacement through the daemon CLI.
//! Keep these I/O-heavy cases separate from ordinary lifecycle coverage.
#![cfg(unix)]
mod support;
use anyhow::Context;
use anyhow::Result;
use anyhow::ensure;
use pretty_assertions::assert_eq;
use serde_json::Value;
use support::TestDaemon;
use support::wait_for_exit;
#[derive(Clone, Copy, PartialEq, Eq)]
enum InitialDaemon {
Missing,
Legacy,
}
fn packaged_daemon_launch(action: &str, initial: InitialDaemon) -> Result<()> {
let mut daemon = TestDaemon::new()?;
let standalone = daemon.home.path().join("packages/standalone");
let package = if action == "start" && initial == InitialDaemon::Missing {
standalone.join("releases/caller")
} else {
daemon.home.path().join("cli-package")
};
for directory in ["bin", "akode-path", "akode-resources"] {
std::fs::create_dir_all(package.join(directory))?;
}
// Both paths are in this test's temp home and therefore on the same filesystem.
// Reuse its prepared (and on Intel macOS, translated) executable. The installer
// still makes a real independent package copy; only fixture setup shares this inode.
std::fs::hard_link(
standalone.join("current/bin/akode"),
package.join("bin/akode"),
)?;
daemon.codex = package.join("bin/akode");
for helper in [
"bin/akode-code-mode-host",
"akode-path/rg",
"akode-resources/bwrap",
] {
akode_utils_cargo_bin::write_executable(&package.join(helper), "runtime fixture")?;
}
let target = format!(
"{}-{}",
std::env::consts::ARCH,
if cfg!(target_os = "macos") {
"apple-darwin"
} else if cfg!(target_env = "gnu") {
"unknown-linux-gnu"
} else {
"unknown-linux-musl"
}
);
std::fs::write(
package.join("akode-package.json"),
serde_json::to_vec(&serde_json::json!({
"version": env!("CARGO_PKG_VERSION"), "target": target, "entrypoint": "bin/akode"
}))?,
)?;
if action == "start" && initial == InitialDaemon::Missing {
std::fs::remove_file(standalone.join("current"))?;
std::os::unix::fs::symlink(&package, standalone.join("current"))?;
}
let cli_selection = standalone.join("current").canonicalize()?;
let state = daemon.home.path().join("app-server-daemon");
if initial == InitialDaemon::Missing {
std::fs::remove_file(state.join("app-server.stderr.log"))?;
}
std::fs::write(
state.join("settings.json"),
br#"{"shutdownGraceSeconds":0}"#,
)?;
let cli_before = daemon.codex.canonicalize()?;
let result = daemon
.command()
.args(["app-server", "daemon", action])
.output()
.context("failed to launch packaged daemon fixture")?;
ensure!(
result.status.success(),
"{}",
String::from_utf8_lossy(&result.stderr)
);
assert_eq!(
String::from_utf8_lossy(&result.stderr).contains("Installing daemon from CLI version"),
initial == InitialDaemon::Missing
);
let output: Value = serde_json::from_slice(&result.stdout)?;
let dedicated = daemon
.home
.path()
.canonicalize()?
.join("packages/app-server-daemon");
let (initial_root, initial_pid_file) = match initial {
InitialDaemon::Missing => (&dedicated, "daemon.pid"),
InitialDaemon::Legacy => (&standalone, "app-server.pid"),
};
assert_eq!(
output["managedCodexPath"],
initial_root
.canonicalize()?
.join("current/bin/akode")
.to_str()
.context("managed path is not UTF-8")?
);
assert_eq!(daemon.codex.canonicalize()?, cli_before);
assert_eq!(standalone.join("current").canonicalize()?, cli_selection);
assert!(state.join(initial_pid_file).exists());
let legacy_updater = match initial {
InitialDaemon::Missing => {
assert!(!state.join("app-server-updater.pid").exists());
None
}
InitialDaemon::Legacy => Some(daemon.pid("app-server-updater.pid")?),
};
if action == "start" {
let initial_current = initial_root.join("current");
let current = dedicated.join("current");
let original = initial_current.canonicalize()?;
let original_pid = daemon.pid(initial_pid_file)?;
let settings_before = std::fs::read(state.join("settings.json"))?;
let refused = daemon
.command()
.args(["app-server", "daemon", "update", "--from-cli"])
.output()?;
assert!(!refused.status.success());
assert!(String::from_utf8_lossy(&refused.stderr).contains("rerun with --yes"));
assert_eq!(daemon.pid(initial_pid_file)?, original_pid);
assert_eq!(initial_current.canonicalize()?, original);
if initial == InitialDaemon::Legacy {
assert!(!current.exists());
}
std::fs::remove_file(package.join("bin/akode-code-mode-host"))?;
let invalid = daemon
.command()
.args(["app-server", "daemon", "update", "--from-cli", "--yes"])
.output()?;
assert!(!invalid.status.success());
assert_eq!(daemon.pid(initial_pid_file)?, original_pid);
assert_eq!(initial_current.canonicalize()?, original);
if initial == InitialDaemon::Legacy {
assert!(!current.exists());
}
akode_utils_cargo_bin::write_executable(
&package.join("bin/akode-code-mode-host"),
"replacement helper",
)?;
let replaced = daemon
.command()
.args(["app-server", "daemon", "update", "--from-cli", "--yes"])
.output()?;
ensure!(
replaced.status.success(),
"{}",
String::from_utf8_lossy(&replaced.stderr)
);
let output: Value = serde_json::from_slice(&replaced.stdout)?;
assert_eq!(output["status"], "updated");
assert_ne!(daemon.pid("daemon.pid")?, original_pid);
wait_for_exit(original_pid)?;
if let Some(pid) = legacy_updater {
wait_for_exit(pid)?;
}
assert!(!state.join("app-server.pid").exists());
assert!(!state.join("app-server-updater.pid").exists());
assert_eq!(
output["managedCodexPath"],
current
.join("bin/akode")
.to_str()
.context("managed path is not UTF-8")?
);
assert_ne!(current.canonicalize()?, original);
assert!(!dedicated.join("auto-update-version").exists());
assert_eq!(std::fs::read(state.join("settings.json"))?, settings_before);
assert_eq!(
std::fs::read(current.join("bin/akode-code-mode-host"))?,
b"replacement helper"
);
if initial == InitialDaemon::Missing {
assert_eq!(
std::fs::read(original.join("bin/akode-code-mode-host"))?,
b"runtime fixture"
);
}
assert_eq!(daemon.lifecycle("start")?["status"], "alreadyRunning");
assert_eq!(daemon.lifecycle("stop")?["status"], "stopped");
assert_eq!(standalone.join("current").canonicalize()?, cli_selection);
}
if action == "bootstrap" {
// Only stable release versions follow automatic updates; local builds versioned
// 0.0.0 do not. aKode builds carry a release version (0.1.0).
let stable_build =
env!("CARGO_PKG_VERSION") != "0.0.0" && !env!("CARGO_PKG_VERSION").contains(['-', '+']);
assert_eq!(output["autoUpdateEnabled"], stable_build);
}
Ok(())
}
#[test]
fn packaged_daemon_start_and_explicit_replacement() -> Result<()> {
packaged_daemon_launch("start", InitialDaemon::Missing)
}
#[test]
fn packaged_daemon_restart_seeds_local_package() -> Result<()> {
packaged_daemon_launch("restart", InitialDaemon::Missing)
}
#[test]
fn packaged_daemon_bootstrap_seeds_local_package() -> Result<()> {
packaged_daemon_launch("bootstrap", InitialDaemon::Missing)
}
#[test]
fn packaged_daemon_explicit_replacement_migrates_running_legacy() -> Result<()> {
packaged_daemon_launch("start", InitialDaemon::Legacy)
}

View File

@@ -0,0 +1,140 @@
//! Isolated installed-CLI fixtures and PID cleanup for Unix daemon integration tests.
//! Every test owns its home and CLI selection; only immutable executable contents are shared.
use std::path::PathBuf;
use std::process::Child;
use std::process::Command;
use std::time::Duration;
use std::time::Instant;
use anyhow::Context;
use anyhow::Result;
use anyhow::ensure;
use akode_utils_cargo_bin::copy_executable;
use serde_json::Value;
use tempfile::TempDir;
pub(super) struct TestDaemon {
pub(super) home: TempDir,
pub(super) codex: PathBuf,
pub(super) unmanaged: Option<Child>,
}
impl TestDaemon {
pub(super) fn new() -> Result<Self> {
let home = tempfile::Builder::new().tempdir_in("/tmp")?;
let codex = akode_utils_cargo_bin::cargo_bin("akode")?;
let codex_source = std::fs::canonicalize(&codex)?;
let target = if cfg!(target_os = "macos") {
format!("{}-apple-darwin", std::env::consts::ARCH)
} else {
format!("{}-unknown-linux-musl", std::env::consts::ARCH)
};
let standalone = home.path().join("packages/standalone");
let release_name = format!("0.0.0-{target}");
let managed = standalone
.join("releases")
.join(&release_name)
.join("bin/akode");
std::fs::create_dir_all(managed.parent().context("managed bin parent")?)?;
// Preserve the installed path without invalidating the shared CLI's Rosetta cache.
#[cfg(all(target_os = "macos", target_arch = "x86_64"))]
{
copy_executable(&codex_source, &managed)?;
// Translate the fixture before timed daemon capability and readiness checks.
ensure!(
Command::new(&managed)
.env("AKODE_HOME", home.path())
.arg("--version")
.output()?
.status
.success(),
"failed to prepare managed test executable"
);
}
#[cfg(not(all(target_os = "macos", target_arch = "x86_64")))]
if std::fs::hard_link(&codex_source, &managed).is_err() {
copy_executable(&codex_source, &managed)?;
}
std::fs::write(standalone.join("auto-update-version"), &release_name)?;
std::os::unix::fs::symlink(
PathBuf::from("releases").join(release_name),
standalone.join("current"),
)?;
// Model a daemon that was previously launched and is currently stopped.
let state = home.path().join("app-server-daemon");
std::fs::create_dir(&state)?;
std::fs::write(state.join("app-server.stderr.log"), b"")?;
Ok(Self {
home,
codex,
unmanaged: None,
})
}
pub(super) fn command(&self) -> Command {
let mut command = Command::new(&self.codex);
command.env("AKODE_HOME", self.home.path());
command
}
pub(super) fn lifecycle(&self, action: &str) -> Result<Value> {
let output = self
.command()
.args(["app-server", "daemon", action])
.output()?;
ensure!(
output.status.success(),
"daemon {action} failed: {}",
String::from_utf8_lossy(&output.stderr)
);
Ok(serde_json::from_slice(&output.stdout)?)
}
pub(super) fn pid(&self, name: &str) -> Result<u32> {
let record = std::fs::read(self.home.path().join("app-server-daemon").join(name))
.with_context(|| format!("failed to read {name}"))?;
Ok(serde_json::from_slice::<Value>(&record)?["pid"]
.as_u64()
.context("pid missing")? as u32)
}
}
impl Drop for TestDaemon {
fn drop(&mut self) {
if let Some(mut child) = self.unmanaged.take() {
let _ = child.kill();
let _ = child.wait();
}
let _ = self.lifecycle("stop");
if let Ok(pid) = self.pid("app-server-updater.pid") {
let _ = signal(pid, libc::SIGTERM);
}
}
}
pub(super) fn signal(pid: u32, signal: libc::c_int) -> Result<()> {
let raw_pid = libc::pid_t::try_from(pid).context("pid out of range")?;
ensure!(
unsafe { libc::kill(raw_pid, signal) } == 0,
"failed to signal pid {pid}: {}",
std::io::Error::last_os_error()
);
Ok(())
}
pub(super) fn wait_for_exit(pid: u32) -> Result<()> {
let deadline = Instant::now() + Duration::from_secs(30);
loop {
let output = Command::new("/bin/ps")
.args(["-p", &pid.to_string(), "-o", "stat="])
.output()
.context("failed to invoke ps")?;
let state = String::from_utf8_lossy(&output.stdout);
if !output.status.success() || state.trim().starts_with('Z') {
return Ok(());
}
ensure!(Instant::now() < deadline, "pid {pid} did not exit: {state}");
std::thread::sleep(Duration::from_millis(50));
}
}

View File

@@ -0,0 +1,126 @@
//! Exercises daemon installation from the Windows WinGet archive layout.
#![cfg(windows)]
use anyhow::Result;
use anyhow::ensure;
use akode_utils_cargo_bin::copy_executable;
use pretty_assertions::assert_eq;
use serde_json::Value;
use sha2::Digest;
use sha2::Sha256;
use std::process::Command;
#[test]
fn winget_package_starts_and_reselects_daemon() -> Result<()> {
if akode_app_server_daemon::is_elevated()? {
eprintln!("requires a non-elevated Windows runner");
return Ok(());
}
let temp = tempfile::tempdir()?;
let home = temp.path().join("home");
let package = temp.path().join("WinGet/Packages/OpenAI.Codex");
let target = format!("{}-pc-windows-msvc", std::env::consts::ARCH);
let entrypoint = format!("akode-{target}.exe");
let codex = package.join(&entrypoint);
for directory in ["bin", "akode-path", "akode-resources/voice"] {
std::fs::create_dir_all(package.join(directory))?;
}
copy_executable(&akode_utils_cargo_bin::cargo_bin("akode")?, &codex)?;
for helper in [
"akode-code-mode-host.exe",
"akode-path/rg.exe",
"akode-resources/codex-command-runner.exe",
"akode-resources/codex-windows-sandbox-setup.exe",
] {
std::fs::write(package.join(helper), b"runtime fixture")?;
}
let mut metadata = serde_json::json!({
"layoutVersion": 1, "version": env!("CARGO_PKG_VERSION"),
"target": target, "entrypoint": entrypoint
});
let manifest_bytes = serde_json::to_vec(&metadata)?;
std::fs::write(package.join("akode-package.json"), &manifest_bytes)?;
let checksum = format!("{:x}", Sha256::digest(std::fs::read(&codex)?));
let voice_bytes = serde_json::to_vec(&serde_json::json!({
"sha256": { &entrypoint: checksum, "akode-resources/voice/runtime": "untouched" }
}))?;
std::fs::write(
package.join("akode-resources/voice/manifest.json"),
&voice_bytes,
)?;
let current = home.join("packages/app-server-daemon/current");
// Drop before temp so assertion failures also release the managed executable.
struct StopDaemon(Command);
impl Drop for StopDaemon {
fn drop(&mut self) {
let _ = self.0.output();
}
}
let mut stop = Command::new(&codex);
stop.env("AKODE_HOME", &home)
.args(["app-server", "daemon", "stop"]);
let mut daemon = StopDaemon(stop);
for args in [
vec!["start"],
vec!["update", "--from-cli", "--yes"],
vec!["update", "--from-cli", "--yes"],
] {
let output = Command::new(&codex)
.env("AKODE_HOME", &home)
.args(["app-server", "daemon"])
.args(&args)
.output()?;
ensure!(
output.status.success(),
"daemon {args:?} failed: {}",
String::from_utf8_lossy(&output.stderr)
);
}
let selected_metadata: Value =
serde_json::from_slice(&std::fs::read(current.join("akode-package.json"))?)?;
metadata["entrypoint"] = "bin/akode.exe".into();
assert_eq!(selected_metadata, metadata);
let selected_voice: Value = serde_json::from_slice(&std::fs::read(
current.join("akode-resources/voice/manifest.json"),
)?)?;
assert_eq!(
selected_voice,
serde_json::json!({
"sha256": {
"bin/akode.exe": checksum,
"akode-resources/voice/runtime": "untouched"
}
})
);
assert_eq!(
std::fs::read(current.join("bin/akode-code-mode-host.exe"))?,
b"runtime fixture"
);
let selected = current.canonicalize()?;
std::fs::remove_file(package.join("akode-code-mode-host.exe"))?;
let invalid = Command::new(&codex)
.env("AKODE_HOME", &home)
.args(["app-server", "daemon", "update", "--from-cli", "--yes"])
.output()?;
ensure!(
!invalid.status.success(),
"an incomplete WinGet package was accepted"
);
assert_eq!(current.canonicalize()?, selected);
assert_eq!(
std::fs::read(package.join("akode-package.json"))?,
manifest_bytes
);
assert_eq!(
std::fs::read(package.join("akode-resources/voice/manifest.json"))?,
voice_bytes
);
let stopped = daemon.0.output()?;
ensure!(
stopped.status.success(),
"failed to stop daemon: {}",
String::from_utf8_lossy(&stopped.stderr)
);
Ok(())
}

View File

@@ -0,0 +1,629 @@
//! Exercises daemon startup and excluded resume/fork pickers with Cargo's CLI executable.
use anyhow::Context as _;
use anyhow::Result;
use anyhow::ensure;
use std::collections::VecDeque;
use std::fs;
use std::process::Command;
use std::time::Duration;
#[tokio::test]
#[cfg(unix)]
async fn auto_daemon_start_attaches_to_shared_server() -> Result<()> {
daemon_startup("start").await
}
#[tokio::test]
#[cfg(unix)]
async fn agents_can_offer_restart_for_managed_daemon() -> Result<()> {
daemon_startup("agents").await
}
#[tokio::test]
#[cfg(unix)]
async fn agents_no_daemon_uses_embedded_even_with_a_running_daemon() -> Result<()> {
daemon_startup("agents-no-daemon").await
}
#[tokio::test]
#[cfg(unix)]
async fn agents_defers_launch_directory_trust_until_starting_a_task() -> Result<()> {
daemon_startup("agents-untrusted").await
}
#[tokio::test]
#[cfg(unix)]
async fn discovered_managed_daemon_can_restart_with_auto_start_disabled() -> Result<()> {
daemon_startup("discovered").await
}
#[tokio::test]
#[cfg(unix)]
async fn incompatible_daemon_can_cancel() -> Result<()> {
daemon_startup("mismatch-cancel").await
}
#[tokio::test]
#[cfg(unix)]
async fn incompatible_daemon_can_run_embedded() -> Result<()> {
daemon_startup("mismatch-embedded").await
}
#[tokio::test]
#[cfg(unix)]
async fn incompatible_daemon_can_restart_with_confirmed_settings() -> Result<()> {
daemon_startup("mismatch-restart").await
}
#[tokio::test]
#[cfg(unix)]
async fn fresh_daemon_requires_confirmation_to_disable_shared_features() -> Result<()> {
daemon_startup("mismatch-disable").await
}
#[tokio::test]
#[cfg(unix)]
async fn stopped_daemon_requires_confirmation_to_disable_persisted_features() -> Result<()> {
daemon_startup("mismatch-disable-persisted").await
}
#[tokio::test]
async fn daemon_exclusion_survives_resume_picker() -> Result<()> {
daemon_startup("resume").await
}
#[tokio::test]
async fn daemon_exclusion_survives_fork_picker() -> Result<()> {
daemon_startup("fork").await
}
#[tokio::test]
#[cfg(windows)]
async fn elevated_local_tui_uses_embedded_without_starting_daemon() -> Result<()> {
if !akode_app_server_daemon::is_elevated()? {
eprintln!("requires an elevated Windows runner");
return Ok(());
}
for command in ["elevated", "elevated-resume", "elevated-fork"] {
daemon_startup(command).await?;
}
let codex = akode_utils_cargo_bin::cargo_bin("akode")?;
let home = tempfile::tempdir()?;
for operation in ["start", "restart"] {
let output = Command::new(&codex)
.env("AKODE_HOME", home.path())
.args(["app-server", "daemon", operation])
.output()?;
ensure!(
!output.status.success(),
"{operation} must reject elevation"
);
ensure!(
String::from_utf8_lossy(&output.stderr).contains("non-elevated terminal"),
"{}",
String::from_utf8_lossy(&output.stderr)
);
}
ensure!(!home.path().join("app-server-daemon").exists());
Ok(())
}
#[tokio::test]
#[cfg(windows)]
async fn restrictive_launcher_uses_embedded_if_daemon_cannot_start() -> Result<()> {
const CHILD: &str = "AKODE_TEST_RESTRICTIVE_DAEMON_START";
if std::env::var_os(CHILD).is_some() {
// The PTY creates its own breakaway-permitted job. Add Cargo's
// restriction *inside* the PTY so it is the CLI's innermost job.
let job = akode_utils_pty::JobObject::create_without_breakaway()?;
let codex = akode_utils_cargo_bin::cargo_bin("akode")?;
let mut command = tokio::process::Command::new(codex);
command
.arg("--no-alt-screen")
.stdin(std::process::Stdio::inherit())
.stdout(std::process::Stdio::inherit())
.stderr(std::process::Stdio::inherit())
// This interactive CLI must inherit the PTY console rather than use
// the background helper's CREATE_NO_WINDOW launch policy.
.creation_flags(windows_sys::Win32::System::Threading::CREATE_SUSPENDED)
.kill_on_drop(true);
let mut child = command.spawn()?;
ensure!(
job.assign_and_resume_process(child.id().context("missing CLI pid")?)?
.is_some(),
"CLI job assignment failed"
);
let status = child.wait().await?;
ensure!(status.success(), "CLI exited: {status}");
return Ok(());
}
daemon_startup("restrictive-job").await
}
async fn daemon_startup(command: &str) -> Result<()> {
#[cfg(windows)]
let elevated = akode_app_server_daemon::is_elevated()?;
#[cfg(not(windows))]
let elevated = false;
let elevated_launch = command.starts_with("elevated");
let codex = akode_utils_cargo_bin::cargo_bin("akode")?.canonicalize()?;
let workspace = tempfile::tempdir()?;
let workspace_path = workspace.path().canonicalize()?;
#[cfg(unix)]
let home = tempfile::Builder::new().tempdir_in("/tmp")?;
#[cfg(not(unix))]
let home = tempfile::tempdir()?;
// Keep cold Rosetta translation outside the timed startup assertions.
#[cfg(all(target_os = "macos", target_arch = "x86_64"))]
anyhow::ensure!(
Command::new(&codex)
.env("AKODE_HOME", home.path())
.arg("--version")
.output()?
.status
.success(),
"failed to prepare CLI test executable"
);
let bedrock_onboarding = matches!(command, "bedrock" | "bedrock-running");
// aKode has no built-in catalog for providers without a catalog URL; keep the bundled one.
let catalog = home.path().join("test-models.json");
fs::write(&catalog, include_str!("../../models-manager/models.json"))?;
fs::write(
home.path().join("config.toml"),
format!(
"model = \"gpt-5.6-terra\"\n\
model_provider = \"mock\"\n\
model_catalog_json = {}\n\
cli_auth_credentials_store = \"file\"\n\
suppress_unstable_features_warning = true\n\
windows.sandbox = \"unelevated\"\n\
tui.disable_paste_burst = true\n\
{}\n\
notice.model_migrations.\"gpt-5.6-terra\" = \"gpt-6-sol\"\n\
[model_providers.mock]\nname = \"mock\"\nbase_url = \"http://127.0.0.1:9/v1\"\nrequires_openai_auth = true\n\
[projects.{}]\ntrust_level = \"{}\"\n",
serde_json::to_string(&catalog.display().to_string())?,
if command == "discovered" {
"tui.status_line=[\"model\",\"thread-id\",\"thread-name\"]\nfeatures.daemon_auto_start=false"
} else if bedrock_onboarding {
"features.gcp_setup_wizard=false"
} else {
""
},
serde_json::to_string(&workspace_path)?,
if command == "agents-untrusted" {
"untrusted"
} else {
"trusted"
},
),
)?;
let mismatch = command.starts_with("mismatch-");
let persisted = command == "mismatch-disable-persisted";
let disabling = matches!(command, "mismatch-disable" | "mismatch-disable-persisted");
let restart = command == "mismatch-restart" || disabling;
if !bedrock_onboarding {
fs::write(
home.path().join("auth.json"),
r#"{"OPENAI_API_KEY":"daemon-startup-test","tokens":null,"last_refresh":null}"#,
)?;
}
let mut env = std::env::vars().collect::<std::collections::HashMap<_, _>>();
for key in [
"AKODE_EXEC_SERVER_URL",
"AKODE_ACCESS_TOKEN",
"AKODE_API_KEY",
"AKODE_CLOUD_TASKS_MODE",
"OPENAI_API_KEY",
"OPENAI_FEDERATION_RULE_ID",
"OPENAI_IDENTITY_TOKEN_FILE",
"OPENAI_WORKLOAD_IDENTITY_CONTEXT",
] {
env.remove(key);
}
env.insert("AKODE_HOME".into(), home.path().display().to_string());
env.insert(
"AKODE_SQLITE_HOME".into(),
home.path().display().to_string(),
);
env.insert("TERM".into(), "xterm-256color".into());
let mut args = vec!["--no-alt-screen".to_string()];
let mut steps: VecDeque<(&str, &[u8])> = VecDeque::new();
if matches!(
command,
"start"
| "agents"
| "agents-no-daemon"
| "agents-untrusted"
| "discovered"
| "bedrock"
| "bedrock-running"
| "restrictive-job"
) || mismatch
{
// A selected package with a stopped daemon avoids installing a release.
let managed = home
.path()
.join("packages/app-server-daemon/current/bin")
.join(if cfg!(windows) { "akode.exe" } else { "codex" });
fs::create_dir_all(home.path().join("packages/app-server-daemon/current/bin"))?;
// Hard links change the executable's ctime and invalidate Rosetta's translation cache.
#[cfg(unix)]
std::os::unix::fs::symlink(&codex, &managed)?;
#[cfg(not(unix))]
fs::hard_link(&codex, &managed)
.or_else(|_| akode_utils_cargo_bin::copy_executable(&codex, &managed))?;
if command != "restrictive-job" {
fs::create_dir(home.path().join("app-server-daemon"))?;
fs::write(
home.path().join("app-server-daemon/settings.json"),
if persisted {
r#"{"shutdownGraceSeconds":0,"updater":{"autoUpdateEnabled":false},"featureOverrides":{"api_key_model_discovery":true}}"#
} else {
r#"{"shutdownGraceSeconds":0,"updater":{"autoUpdateEnabled":false}}"#
},
)?;
}
}
let pid_file = home.path().join("app-server-daemon/daemon.pid");
let result = async {
let mut existing_daemon = if matches!(command, "bedrock-running" | "discovered" | "agents-no-daemon")
|| (mismatch && !disabling)
{
if command == "bedrock-running" {
// This Unix-only case uses a daemon-only token and no ambient profiles.
env.insert("AWS_CONFIG_FILE".into(), "/dev/null".into());
env.insert("AWS_SHARED_CREDENTIALS_FILE".into(), "/dev/null".into());
env.remove("AWS_ACCESS_KEY_ID");
env.remove("AWS_SECRET_ACCESS_KEY");
env.insert("AWS_BEARER_TOKEN_BEDROCK".into(), "daemon-only-test-token".into());
}
let started = Command::new(&codex)
.env_clear()
.envs(&env)
.current_dir(&workspace_path)
.args(["app-server", "daemon", "start"])
.output()?;
ensure!(
started.status.success(),
"{}",
String::from_utf8_lossy(&started.stderr)
);
Some(fs::read(&pid_file)?)
} else {
None
};
let expected = if command == "start" {
// The draft header is visible before the session's command composer is ready.
steps.push_back(("GPT-5.6-Terra", b"/status\r"));
"Server:Localbackgroundserver"
} else if command == "agents-no-daemon" {
args.extend(["agents".into(), "--no-daemon".into()]);
steps.push_back(("Notasksyet", b"n"));
steps.push_back(("GPT-5.6-Terra", b"/daemon\r"));
"Notconnectedtothelocalbackgroundserver"
} else if command == "agents" {
args.push("agents".into());
steps.push_back(("Notasksyet", b"n"));
steps.push_back(("GPT-5.6-Terra", b"/daemon\r"));
steps.push_back(("Restartbackgroundserver", b"\x1b[F\r"));
"Restartbackgroundserver?"
} else if command == "agents-untrusted" {
args.push("agents".into());
steps.push_back(("Notasksyet", b"n"));
"entercontinue·escback"
} else if command == "discovered" {
args.extend(["--disable".into(), "daemon_auto_start".into()]);
// Empty drafts need not survive a daemon restart. Renaming materializes the
// thread; wait for the confirmed footer name, not the echoed command.
steps.push_back(("GPT-5.6-Terra", b"/rename daemon-restart-test\r"));
steps.push_back(("·daemon-restart-test", b"/daemon\r"));
steps.push_back(("Restartbackgroundserver", b"2"));
steps.push_back(("Restartbackgroundserver?", b"2\r"));
// Offline editing preserves text but suppresses Enter. Observe the command
// popup in a complete connected frame before submitting the retained draft.
steps.push_back(("GPT-5.6-Terra", b"/status"));
steps.push_back(("/statusshowcurrentsessionconfigurationandtokenusage", b"\r"));
"Server:Localbackgroundserver"
} else if elevated_launch || command == "restrictive-job" && elevated {
if let Some(action) = command.strip_prefix("elevated-") {
args.push(action.into());
steps.push_back(("Nosessionsyet", b"\x1b"));
}
steps.push_back(("GPT-5.6-Terra", b"\x14"));
"Runningasadministrator:sharedbackgroundserverdisabled."
} else if command == "restrictive-job" {
steps.push_back(("GPT-5.6-Terra", b"\x14"));
"Runningwithoutthesharedbackgroundserver:thisWindowslauncher"
} else if mismatch {
args.extend(if disabling && !persisted {
["--disable".into(), "auth_elicitation".into()]
} else {
["--disable".into(), "api_key_model_discovery".into()]
});
let input: &[u8] = match command {
"mismatch-cancel" => b"\x03",
"mismatch-embedded" => b"1",
"mismatch-restart" | "mismatch-disable" | "mismatch-disable-persisted" => b"2\r",
_ => unreachable!(),
};
steps.push_back(("Backgroundserverhasincompatiblefeaturesettings", input));
if command == "mismatch-cancel" {
"--no-daemon"
} else {
steps.push_back(("GPT-5.6-Terra", b"/status\r"));
if restart { "Server:Localbackgroundserver" } else { "Model:" }
}
} else if command == "bedrock-running" {
env.remove("AWS_BEARER_TOKEN_BEDROCK");
steps.push_back(("UseanAPIkeyoranotherprovider", b"3"));
steps.push_back(("UseAmazonBedrock", b"2"));
"Continuewithdetectedcredentials"
} else if bedrock_onboarding {
// With GCP disabled, only Bedrock makes the sign-in menu advertise another provider.
"UseanAPIkeyoranotherprovider"
} else {
args.extend([command.into(), "--strict-config".into()]);
if command == "resume" {
let thread_id = "00000000-0000-0000-0000-000000000001";
let sessions = home.path().join("sessions/2025/01/05");
fs::create_dir_all(&sessions)?;
let metadata = serde_json::json!({
"timestamp": "2025-01-05T12:00:00Z",
"type": "session_meta",
"payload": {
"session_id": thread_id, "id": thread_id,
"timestamp": "2025-01-05T12:00:00Z", "cwd": workspace_path,
"originator": "codex", "cli_version": "0.0.0",
"source": "cli", "model_provider": "mock"
}
});
let message = serde_json::json!({
"timestamp": "2025-01-05T12:00:00Z",
"type": "event_msg",
"payload": {"type": "user_message", "message": "Saved resume session", "kind": "plain"}
});
fs::write(
sessions.join(format!("rollout-2025-01-05T12-00-00-{thread_id}.jsonl")),
format!("{metadata}\n{message}\n"),
)?;
steps.push_back(("Savedresumesession", b"\r"));
} else {
steps.push_back(("Nosessionsyet", b"\x1b"));
}
steps.push_back(("GPT-5.6-Terra", b"\x14"));
if elevated {
"Runningasadministrator:sharedbackgroundserverdisabled."
} else {
"Runningwithoutthesharedbackgroundserver:--strict-config"
}
};
let program = if cfg!(windows) && command == "restrictive-job" {
env.insert("AKODE_TEST_RESTRICTIVE_DAEMON_START".into(), "1".into());
args = vec![
"--exact".into(),
"restrictive_launcher_uses_embedded_if_daemon_cannot_start".into(),
"--nocapture".into(),
];
std::env::current_exe()?
} else {
codex.clone()
};
let spawned = akode_utils_pty::spawn_pty_process(
&program.to_string_lossy(),
&args,
&workspace_path,
&env,
/*arg0*/ &None,
akode_utils_pty::TerminalSize {
rows: 40,
cols: 120,
},
akode_utils_pty::ChildFds::Inherited(&[]),
)
.await?;
let exit = spawned.exit_rx;
let session = spawned.session;
let writer = session.writer_sender();
let mut stdout = spawned.stdout_rx;
let mut output = String::new();
let mut initial_agents_screen = String::new();
let mut screen = vt100::Parser::new(
/*rows*/ 40, /*cols*/ 120, /*scrollback_len*/ 0,
);
let mut queries: Vec<(&str, &[u8])> = vec![
("\x1b[6n", b"\x1b[1;1R"),
("\x1b[?u", b"\x1b[?0u\x1b[?1;2c"),
("\x1b[c", b"\x1b[?1;2c"),
("\x1b]10;?", b"\x1b]10;rgb:ffff/ffff/ffff\x1b\\"),
("\x1b]11;?", b"\x1b]11;rgb:0000/0000/0000\x1b\\"),
];
// A fresh disable request includes both cold daemon startup and its confirmed restart.
let timeout = Duration::from_secs(if disabling { 90 } else { 45 });
let result = tokio::time::timeout(timeout, async {
loop {
let bytes = tokio::select! {
bytes = stdout.recv() => bytes,
// The first onboarding draw precedes its typeahead drain. Retry the
// main menu shortcut until the submenu appears (it has no option 3).
() = tokio::time::sleep(Duration::from_millis(/*millis*/ 250)),
if steps.front().is_some_and(|(ready, _)| *ready == "UseAmazonBedrock") => {
writer.send(b"3".to_vec()).await?;
continue;
}
};
let Some(bytes) = bytes else { break };
output.push_str(&String::from_utf8_lossy(&bytes));
screen.process(&bytes);
for (query, reply) in &mut queries {
if !query.is_empty() && output.contains(*query) {
writer.send(reply.to_vec()).await?;
*query = "";
}
}
// PTY reads can split a redraw after the reconnect notice is erased but
// before it is repainted. Only inspect completed synchronized updates.
if command == "discovered"
&& output
.rfind("\x1b[?2026l")
.is_none_or(|end| output[end..].contains("\x1b[?2026h"))
{
continue;
}
let text: String = screen
.screen()
.contents()
.chars()
.filter(|c| !c.is_whitespace())
.collect();
if let Some((ready, input)) = steps.front()
&& text.contains(ready)
{
if command == "agents-untrusted" && *ready == "Notasksyet" {
if !text.contains("enteropennnew") {
continue;
}
initial_agents_screen = screen.screen().contents();
}
if command == "discovered" {
if *ready == "Restartbackgroundserver?" {
existing_daemon = Some(fs::read(&pid_file)?);
} else if *ready == "GPT-5.6-Terra" {
// The header renders before thread/start completes. Wait for the
// live status line to confirm there is a session to reconnect.
if !screen.screen().contents().split_whitespace().any(|part| {
akode_protocol::ThreadId::from_string(part).is_ok()
}) {
continue;
}
}
// A replacement PID can appear before the TUI observes the disconnect.
// Wait for reconnect to clear/rebuild the transcript, so the old
// composer's command popup cannot make the status probe look ready.
if *input == b"/status" && !output.contains("\x1b[3J") {
continue;
}
// The old header can linger while the daemon stops. Check both
// the draft and its Enter against the replacement process and UI.
if (*input == b"/status" || *input == b"\r")
&& (!fs::read(&pid_file).is_ok_and(|pid| Some(pid) != existing_daemon)
|| text.contains("Reconnecting"))
{
continue;
}
}
if disabling && *ready == "Backgroundserverhasincompatiblefeaturesettings" {
existing_daemon = Some(fs::read(&pid_file)?);
let settings: serde_json::Value = serde_json::from_slice(&fs::read(home.path().join("app-server-daemon/settings.json"))?)?;
if persisted {
ensure!(settings["featureOverrides"]["api_key_model_discovery"] == true);
} else {
ensure!(settings["featureOverrides"]["auth_elicitation"].is_null());
}
}
writer.send(input.to_vec()).await?;
steps.pop_front();
output.clear();
} else if steps.is_empty() && text.contains(expected) {
if command == "agents-untrusted" {
let transition = format!(
"{initial_agents_screen}\n\n--- Start a task ---\n\n{}",
screen.screen().contents()
)
.replace(&*workspace_path.to_string_lossy(), "[WORKSPACE]")
.replace(&*home.path().to_string_lossy(), "[AKODE_HOME]")
.replace(" tab/⇧tab filter", "tab/shift+tab filter");
let transition = transition.lines().map(str::trim_end).collect::<Vec<_>>().join("\n");
let snapshot = akode_utils_cargo_bin::find_resource!(
"tests/snapshots/daemon_startup__agents_overview_before_folder_consent.snap"
)?;
insta::with_settings!({snapshot_path => snapshot.parent().context("snapshot has no parent")?}, {
insta::assert_snapshot!("agents_overview_before_folder_consent", transition);
});
}
if mismatch {
let previous_pid = existing_daemon.as_ref().context("missing original daemon PID")?;
ensure!((fs::read(&pid_file)? != *previous_pid) == restart);
if command == "mismatch-cancel" {
ensure!(text.contains("Cannotusethesharedbackgroundserver:Thissessionrequiresapi_key_model_discoverytobedisabled."));
} else {
ensure!(text.contains("Server:Localbackgroundserver") == restart);
if restart {
let settings: serde_json::Value = serde_json::from_slice(
&fs::read(home.path().join("app-server-daemon/settings.json"))?
)?;
let flag = if disabling && !persisted {
"auth_elicitation"
} else {
"api_key_model_discovery"
};
assert_eq!(settings["featureOverrides"], serde_json::json!({(flag): false}));
}
}
} else if command == "start" {
ensure!(text.contains("Server:Localbackgroundserver"));
ensure!(home.path().join("app-server-daemon/daemon.pid").exists());
} else if command == "discovered" {
let previous_pid = existing_daemon.as_ref().context("missing original daemon PID")?;
ensure!(fs::read(&pid_file)? != *previous_pid, "daemon PID did not change");
} else if let Some(existing_daemon) = &existing_daemon {
ensure!(fs::read(&pid_file)? == *existing_daemon);
} else if elevated_launch {
ensure!(!home.path().join("app-server-daemon").exists());
ensure!(!home.path().join("packages/app-server-daemon").exists());
} else if bedrock_onboarding {
ensure!(pid_file.exists() != elevated);
} else if command == "restrictive-job" {
ensure!(!pid_file.exists());
if !elevated {
let contents = screen.screen().contents();
let warning = contents.lines()
.find(|line| line.contains("Running without the shared background server:"))
.context("missing rendered fallback warning")?;
insta::assert_snapshot!("restrictive_launcher_warning", warning.trim());
}
}
return Ok::<_, anyhow::Error>(());
}
}
anyhow::bail!(
"TUI exited before {expected}: {}",
screen.screen().contents()
)
})
.await;
if command == "mismatch-cancel" && matches!(result, Ok(Ok(()))) {
let status = tokio::time::timeout(Duration::from_secs(/*secs*/ 5), exit).await??;
ensure!(status != 0, "incompatible daemon launch must fail");
}
Ok::<_, anyhow::Error>((
session,
result.with_context(|| format!("{command} timed out waiting for {}: {}", steps.front().map_or(expected, |(ready, _)| *ready), screen.screen().contents())),
))
}
.await;
// Elevated fresh Bedrock onboarding already verified that no daemon started.
if elevated
&& command == "bedrock"
&& let Ok((session, Ok(Ok(())))) = &result
{
session.terminate();
return Ok(());
}
// Stop the detached daemon, including on timeout or failed assertions.
let stopped = Command::new(&codex)
.env_clear()
.envs(&env)
.args(["app-server", "daemon", "stop"])
.output()?;
let (session, result) = result?;
session.terminate();
result??;
ensure!(
stopped.status.success(),
"{}",
String::from_utf8_lossy(&stopped.stderr)
);
Ok(())
}

View File

@@ -0,0 +1,185 @@
use std::path::Path;
use anyhow::Result;
use akode_state::StateRuntime;
use akode_utils_absolute_path::test_support::PathExt;
use predicates::str::contains;
use tempfile::TempDir;
fn codex_command(codex_home: &Path) -> Result<assert_cmd::Command> {
let mut cmd = assert_cmd::Command::new(akode_utils_cargo_bin::cargo_bin("akode")?);
cmd.env("AKODE_HOME", codex_home);
Ok(cmd)
}
#[tokio::test]
async fn debug_clear_memories_resets_state_and_removes_memory_dir() -> Result<()> {
let codex_home = TempDir::new()?;
let sqlite = akode_state::SqliteConfig::new_for_testing(codex_home.path().abs());
let runtime = StateRuntime::init(sqlite.clone(), "test-provider".to_string()).await?;
runtime.close().await;
let thread_id = "00000000-0000-0000-0000-000000000123";
let db_path = sqlite.state_db_path();
let pool = sqlite.open_read_write_pool(&db_path).await?;
let memories_db_path = sqlite.memories_db_path();
let memories_pool = sqlite.open_read_write_pool(&memories_db_path).await?;
sqlx::query(
r#"
INSERT INTO threads (
id,
rollout_path,
created_at,
updated_at,
source,
agent_nickname,
agent_role,
model_provider,
cwd,
cli_version,
title,
sandbox_policy,
approval_mode,
tokens_used,
first_user_message,
archived,
archived_at,
git_sha,
git_branch,
git_origin_url,
memory_mode
) VALUES (?, ?, 1, 1, 'cli', NULL, NULL, 'test-provider', ?, '', '', 'read-only', 'on-request', 0, '', 0, NULL, NULL, NULL, NULL, 'enabled')
"#,
)
.bind(thread_id)
.bind(codex_home.path().join("session.jsonl").display().to_string())
.bind(codex_home.path().display().to_string())
.execute(&pool)
.await?;
sqlx::query(
r#"
INSERT INTO stage1_outputs (
thread_id,
source_updated_at,
raw_memory,
rollout_summary,
generated_at,
rollout_slug,
usage_count,
last_usage,
selected_for_phase2,
selected_for_phase2_source_updated_at
) VALUES (?, 1, 'raw', 'summary', 1, NULL, 0, NULL, 0, NULL)
"#,
)
.bind(thread_id)
.execute(&memories_pool)
.await?;
sqlx::query(
r#"
INSERT INTO jobs (
kind,
job_key,
status,
worker_id,
ownership_token,
started_at,
finished_at,
lease_until,
retry_at,
retry_remaining,
last_error,
input_watermark,
last_success_watermark
) VALUES
('memory_stage1', ?, 'completed', NULL, NULL, NULL, NULL, NULL, NULL, 3, NULL, NULL, 1),
('memory_consolidate_global', 'global', 'completed', NULL, NULL, NULL, NULL, NULL, NULL, 3, NULL, NULL, 1)
"#,
)
.bind(thread_id)
.execute(&memories_pool)
.await?;
let memory_root = codex_home.path().join("memories");
std::fs::create_dir_all(&memory_root)?;
std::fs::write(memory_root.join("memory_summary.md"), "stale memory")?;
pool.close().await;
memories_pool.close().await;
let mut cmd = codex_command(codex_home.path())?;
cmd.args(["debug", "clear-memories"])
.assert()
.success()
.stdout(contains("Cleared memory state"));
let pool = sqlite.open_read_write_pool(&memories_db_path).await?;
let stage1_outputs_count: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM stage1_outputs")
.fetch_one(&pool)
.await?;
assert_eq!(stage1_outputs_count, 0);
let memory_jobs_count: i64 = sqlx::query_scalar(
"SELECT COUNT(*) FROM jobs WHERE kind = 'memory_stage1' OR kind = 'memory_consolidate_global'",
)
.fetch_one(&pool)
.await?;
assert_eq!(memory_jobs_count, 0);
assert!(memory_root.exists());
assert_eq!(std::fs::read_dir(memory_root)?.count(), 0);
pool.close().await;
Ok(())
}
#[tokio::test]
async fn debug_clear_memories_resets_memories_db_without_state_db() -> Result<()> {
let codex_home = TempDir::new()?;
let sqlite = akode_state::SqliteConfig::new_for_testing(codex_home.path().abs());
let runtime = StateRuntime::init(sqlite.clone(), "test-provider".to_string()).await?;
runtime.close().await;
let db_path = sqlite.state_db_path();
let memories_db_path = sqlite.memories_db_path();
let memories_pool = sqlite.open_read_write_pool(&memories_db_path).await?;
sqlx::query(
r#"
INSERT INTO stage1_outputs (
thread_id,
source_updated_at,
raw_memory,
rollout_summary,
generated_at,
rollout_slug,
usage_count,
last_usage,
selected_for_phase2,
selected_for_phase2_source_updated_at
) VALUES ('00000000-0000-0000-0000-000000000123', 1, 'raw', 'summary', 1, NULL, 0, NULL, 0, NULL)
"#,
)
.execute(&memories_pool)
.await?;
memories_pool.close().await;
std::fs::remove_file(&db_path)?;
let mut cmd = codex_command(codex_home.path())?;
cmd.args(["debug", "clear-memories"])
.assert()
.success()
.stdout(contains("Cleared memory state"));
let pool = sqlite.open_read_write_pool(&memories_db_path).await?;
let stage1_outputs_count: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM stage1_outputs")
.fetch_one(&pool)
.await?;
assert_eq!(stage1_outputs_count, 0);
pool.close().await;
assert!(!db_path.exists());
Ok(())
}

View File

@@ -0,0 +1,41 @@
use std::path::Path;
use anyhow::Result;
use tempfile::TempDir;
fn codex_command(codex_home: &Path) -> Result<assert_cmd::Command> {
let mut cmd = assert_cmd::Command::new(akode_utils_cargo_bin::cargo_bin("akode")?);
cmd.env("AKODE_HOME", codex_home);
Ok(cmd)
}
#[test]
fn debug_models_bundled_prints_json() -> Result<()> {
let codex_home = TempDir::new()?;
let mut cmd = codex_command(codex_home.path())?;
let output = cmd.args(["debug", "models", "--bundled"]).output()?;
assert!(output.status.success());
let stdout = String::from_utf8(output.stdout)?;
let value: serde_json::Value = serde_json::from_str(&stdout)?;
assert!(value["models"].is_array());
assert!(!value["models"].as_array().unwrap_or(&Vec::new()).is_empty());
Ok(())
}
#[test]
fn debug_models_default_prints_empty_json_without_provider() -> Result<()> {
let codex_home = TempDir::new()?;
let mut cmd = codex_command(codex_home.path())?;
let output = cmd.args(["debug", "models"]).output()?;
assert!(output.status.success());
let stdout = String::from_utf8(output.stdout)?;
let value: serde_json::Value = serde_json::from_str(&stdout)?;
assert!(value["models"].is_array());
// aKode has no default provider and no built-in catalog: nothing to list, no network.
assert!(value["models"].as_array().unwrap_or(&Vec::new()).is_empty());
Ok(())
}

View File

@@ -0,0 +1,17 @@
use predicates::prelude::*;
#[test]
fn missing_session_fails_before_delete_confirmation() -> anyhow::Result<()> {
let codex_home = tempfile::tempdir()?;
let mut cmd = assert_cmd::Command::new(akode_utils_cargo_bin::cargo_bin("akode")?);
cmd.env("AKODE_HOME", codex_home.path())
.args(["delete", "123e4567-e89b-12d3-a456-426614174000"]);
cmd.assert()
.failure()
.stderr(predicate::str::contains(
"No active or archived session found matching",
))
.stderr(predicate::str::contains("cannot confirm").not());
Ok(())
}

View File

@@ -0,0 +1,344 @@
#[cfg(target_os = "macos")]
use std::path::Path;
use std::process::Command;
use std::process::Stdio;
use anyhow::Context as _;
use anyhow::Result;
use akode_state::SqliteConfig;
use akode_utils_absolute_path::AbsolutePathBuf;
use pretty_assertions::assert_eq;
use regex_lite::Regex;
use serde_json::Value;
use serde_json::json;
use tempfile::TempDir;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::method;
use wiremock::matchers::path;
async fn local_provider() -> Result<(MockServer, TempDir)> {
let server = MockServer::start().await;
for (request_method, request_path, status) in
[("HEAD", "/v1/responses", 200), ("GET", "/v1/models", 401)]
{
Mock::given(method(request_method))
.and(path(request_path))
.respond_with(ResponseTemplate::new(status).insert_header("x-request-id", "fixture-id"))
.mount(&server)
.await;
}
let home = TempDir::new()?;
std::fs::write(
home.path().join("config.toml"),
format!(
"cli_auth_credentials_store = \"ephemeral\"\ncheck_for_update_on_startup = false\nmodel_provider = \"local\"\n[model_providers.local]\nname = \"local\"\nbase_url = \"{}/v1\"\nwire_api = \"responses\"\n",
server.uri()
),
)?;
Ok((server, home))
}
fn local_command(home: &TempDir) -> Result<Command> {
let mut command = Command::new(akode_utils_cargo_bin::cargo_bin("akode")?);
command
.current_dir(home.path())
.env("AKODE_HOME", home.path())
.env("NO_PROXY", "127.0.0.1,localhost")
.env("no_proxy", "127.0.0.1,localhost")
.stdin(Stdio::null());
for name in [
"HTTP_PROXY",
"HTTPS_PROXY",
"ALL_PROXY",
"http_proxy",
"https_proxy",
"all_proxy",
"AKODE_ACCESS_TOKEN",
"AKODE_API_KEY",
"OPENAI_API_KEY",
"AKODE_CA_CERTIFICATE",
"SSL_CERT_FILE",
"OPENAI_WORKLOAD_IDENTITY_CONTEXT",
"OPENAI_IDENTITY_TOKEN_FILE",
"OPENAI_FEDERATION_RULE_ID",
] {
command.env_remove(name);
}
Ok(command)
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn network_only_selects_checks_without_database_or_mcp_scans() -> Result<()> {
let (server, home) = local_provider().await?;
Mock::given(path("/unrelated-mcp"))
.respond_with(ResponseTemplate::new(200))
.expect(0)
.mount(&server)
.await;
let sqlite =
SqliteConfig::new_for_testing(AbsolutePathBuf::try_from(home.path().to_path_buf())?);
let database = sqlite.logs_db_path();
std::fs::write(&database, "not a SQLite database")?;
let mcp_url = format!("{}/unrelated-mcp", server.uri());
let output = local_command(&home)?
.args(["doctor", "--network-only", "--json", "--all", "--feedback"])
.arg("-c")
.arg(format!("mcp_servers.unrelated.url={mcp_url:?}"))
.output()?;
let report: Value = serde_json::from_slice(&output.stdout)?;
assert!(output.status.success(), "{report:#}");
let checks = report["checks"].as_object().unwrap();
assert_eq!(
checks.keys().map(String::as_str).collect::<Vec<_>>(),
vec![
"config.load",
"network.env",
"network.provider_reachability",
"network.websocket_reachability",
]
);
assert_eq!(std::fs::read_to_string(database)?, "not a SQLite database");
server.verify().await;
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn network_only_reports_recoverable_config_warnings_and_effective_config() -> Result<()> {
let (_server, home) = local_provider().await?;
let baseline_output = local_command(&home)?
.args(["doctor", "--network-only", "--json"])
.output()?;
let baseline_report: Value = serde_json::from_slice(&baseline_output.stdout)?;
assert!(baseline_output.status.success(), "{baseline_report:#}");
let baseline_warning_count =
baseline_report["checks"]["config.load"]["details"]["startup warnings"]
.as_str()
.unwrap_or("0")
.parse::<usize>()?;
let config_path = home.path().join("config.toml");
let config = std::fs::read_to_string(&config_path)?;
std::fs::write(
config_path,
// OTEL exporters were removed (otel settings are ignored without warnings); use another
// recoverable, warning-only setting.
format!("{config}\n[features.guardianv2]\nasync_classifier_mode = \"conversation\"\n"),
)?;
let output = local_command(&home)?
.args(["doctor", "--network-only", "--json"])
.output()?;
let report: Value = serde_json::from_slice(&output.stdout)?;
assert!(output.status.success(), "{report:#}");
let config_check = &report["checks"]["config.load"];
let warning_count = config_check["details"]["startup warnings"]
.as_str()
.context("missing startup-warning count")?
.parse::<usize>()?;
let warnings = &config_check["details"]["startup warning"];
let startup_warning = std::iter::once(warnings)
.chain(warnings.as_array().into_iter().flatten())
.filter_map(Value::as_str)
.find(|warning| warning.starts_with("`[features.guardianv2].async_classifier_mode`"))
.context("missing recoverable config warning")?;
let check_statuses = report["checks"]
.as_object()
.unwrap()
.iter()
.map(|(id, check)| (id.clone(), check["status"].clone()))
.collect::<serde_json::Map<_, _>>();
assert_eq!(
json!({
"overallStatus": report["overallStatus"],
"checkStatuses": check_statuses,
"config": {
"summary": config_check["summary"],
"scope": config_check["details"]["configuration scope"],
"provider": config_check["details"]["model provider"],
"startupWarnings": warning_count,
"startupWarning": startup_warning,
},
}),
json!({
"overallStatus": "warning",
"checkStatuses": {
"config.load": "warning",
"network.env": "ok",
"network.provider_reachability": "ok",
"network.websocket_reachability": "ok",
},
"config": {
"summary": "config loaded",
"scope": "invocation config, including managed policy",
"provider": "local",
"startupWarnings": baseline_warning_count + 1,
"startupWarning": "`[features.guardianv2].async_classifier_mode` is deprecated and ignored. Async classification always uses conversations; remove this setting from config.toml or profile configuration files.",
},
})
);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn network_only_config_failure_does_not_guess_probe_targets() -> Result<()> {
let proxy = MockServer::start().await;
let home = TempDir::new()?;
std::fs::write(
home.path().join("config.toml"),
"model_provider = sk-config-credential-fixture\n",
)?;
let output = local_command(&home)?
.args(["doctor", "--network-only", "--json"])
.env("HTTP_PROXY", proxy.uri())
.env("HTTPS_PROXY", proxy.uri())
.output()?;
assert_eq!(output.status.code(), Some(1));
assert!(!String::from_utf8_lossy(&output.stdout).contains("sk-config-credential-fixture"));
let report: Value = serde_json::from_slice(&output.stdout)?;
assert_eq!(report["checks"].as_object().unwrap().len(), 1);
assert_eq!(report["checks"]["config.load"]["status"], "fail");
assert_eq!(
report["checks"]["config.load"]["details"]["network diagnostics"],
"effective network configuration is unavailable"
);
assert!(proxy.received_requests().await.unwrap().is_empty());
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn network_only_human_output() -> Result<()> {
let (_server, home) = local_provider().await?;
let output = local_command(&home)?
.args([
"doctor",
"--network-only",
"--summary",
"--ascii",
"--no-color",
])
.output()?;
let stdout = String::from_utf8(output.stdout)?;
assert!(output.status.success(), "{stdout}");
insta::assert_snapshot!("network_only_human_output", stdout);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn network_only_config_failure_human_output() -> Result<()> {
let home = TempDir::new()?;
std::fs::write(
home.path().join("config.toml"),
"model_provider = sk-config-credential-fixture\n",
)?;
let output = local_command(&home)?
.args(["doctor", "--network-only", "--all", "--ascii", "--no-color"])
.output()?;
let stdout = String::from_utf8(output.stdout)?;
assert_eq!(output.status.code(), Some(1));
assert!(!stdout.contains("sk-config-credential-fixture"));
// Config loading may canonicalize the directory, rendering may shorten it,
// and Windows uses backslashes.
// Normalize the rendered config-file row while retaining its label and filename.
let file_row = Regex::new(r"(?m)^( file +).+[\\/]config\.toml$")?;
assert!(file_row.is_match(&stdout), "{stdout}");
let stdout = file_row.replace_all(&stdout, "${1}<AKODE_HOME>/config.toml");
insta::assert_snapshot!("network_only_config_failure_human_output", stdout);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn invalid_custom_ca_falls_back_to_system_roots() -> Result<()> {
let server = MockServer::start().await;
for (request_method, request_path) in [("HEAD", "/v1/responses"), ("GET", "/v1/models")] {
Mock::given(method(request_method))
.and(path(request_path))
.respond_with(ResponseTemplate::new(200))
.expect(2)
.mount(&server)
.await;
}
let codex_home = TempDir::new()?;
let certificate = codex_home.path().join("invalid-ca.pem");
std::fs::write(&certificate, "not a certificate")?;
std::fs::write(
codex_home.path().join("config.toml"),
format!(
"model_provider = \"local\"\n[model_providers.local]\nname = \"local\"\nbase_url = \"{}/v1\"\nwire_api = \"responses\"\n",
server.uri()
),
)?;
for sandbox in [None, Some("seatbelt")] {
let mut command = Command::new(akode_utils_cargo_bin::cargo_bin("akode")?);
command
.args(["doctor", "--json"])
.env("AKODE_HOME", codex_home.path())
.env("AKODE_CA_CERTIFICATE", &certificate)
.stdin(Stdio::null());
if let Some(sandbox) = sandbox {
command
.env("AKODE_SANDBOX", sandbox)
.env("HTTP_PROXY", "http://127.0.0.1:1")
.env("http_proxy", "http://127.0.0.1:1")
.env("HTTPS_PROXY", "http://127.0.0.1:1")
.env("https_proxy", "http://127.0.0.1:1")
.env("NO_PROXY", "")
.env("no_proxy", "");
} else {
command
.env("NO_PROXY", "127.0.0.1,localhost")
.env("no_proxy", "127.0.0.1,localhost");
}
let output = command
.output()
.context("failed to run the doctor with an invalid custom CA")?;
let report: Value = serde_json::from_slice(&output.stdout)?;
assert!(
report["checks"]["network.provider_reachability"]["details"]["local API inference URL"]
.as_str()
.is_some_and(|detail| detail.ends_with("reachable (HTTP 200)"))
);
}
server.verify().await;
Ok(())
}
#[cfg(target_os = "macos")]
#[test]
fn doctor_reports_macos_system_proxy_configuration_and_policy() -> Result<()> {
let codex_home = TempDir::new()?;
let report = doctor_report(codex_home.path())?;
let details = &report["checks"]["network.env"]["details"];
assert_eq!(details["respect system proxy"], json!("disabled"));
assert!(matches!(
details["system proxy"].as_str(),
Some("automatic (PAC)" | "manual" | "direct" | "unavailable")
));
std::fs::write(
codex_home.path().join("config.toml"),
"[features]\nrespect_system_proxy = true\n",
)?;
let report = doctor_report(codex_home.path())?;
assert_eq!(
report["checks"]["network.env"]["details"]["respect system proxy"],
json!("enabled")
);
Ok(())
}
#[cfg(target_os = "macos")]
fn doctor_report(codex_home: &Path) -> Result<Value> {
let output = Command::new(akode_utils_cargo_bin::cargo_bin("akode")?)
.args(["doctor", "--json"])
.env("AKODE_HOME", codex_home)
.stdin(Stdio::null())
.output()
.context("failed to run the doctor")?;
serde_json::from_slice(&output.stdout).context("doctor did not emit a valid json report")
}

View File

@@ -0,0 +1,693 @@
//! Black-box coverage for safe diagnostic execution and config error reporting.
use std::ffi::OsString;
use std::path::PathBuf;
use std::time::Duration;
#[cfg(unix)]
use anyhow::Context;
use anyhow::Result;
use app_test_support::TestAppServer;
use akode_app_server_protocol::RequestId;
use akode_config::loader::project_trust_key;
use akode_state::SqliteConfig;
use akode_utils_absolute_path::AbsolutePathBuf;
use akode_utils_cargo_bin::copy_executable;
use pretty_assertions::assert_eq;
use serde_json::Value;
use serde_json::json;
use tempfile::TempDir;
use tokio::io::AsyncBufReadExt;
use tokio::io::AsyncWriteExt;
use tokio::io::BufReader;
use tokio::net::TcpListener;
use tokio::time::timeout;
struct Fixture {
root: TempDir,
program: PathBuf,
workspace: PathBuf,
home: PathBuf,
marker: PathBuf,
path: OsString,
}
impl Fixture {
fn new() -> Result<Self> {
let root = TempDir::new()?;
let home = root.path().join("home");
std::fs::create_dir(&home)?;
// Cargo-built paths deliberately ignore npm provenance. Launch outside
// target/ so this fixture also exercises the packaged-install checks.
let program = root
.path()
.join(format!("codex{}", std::env::consts::EXE_SUFFIX));
let source = akode_utils_cargo_bin::cargo_bin("akode")?;
// Hard-link setup and teardown invalidate other tests' Rosetta translations.
#[cfg(all(target_os = "macos", target_arch = "x86_64"))]
{
copy_executable(&source, &program)?;
// Translate the fixture before the timed diagnostic command.
anyhow::ensure!(
std::process::Command::new(&program)
.env("AKODE_HOME", &home)
.arg("--version")
.output()?
.status
.success(),
"failed to prepare diagnostic test executable"
);
}
#[cfg(not(all(target_os = "macos", target_arch = "x86_64")))]
if std::fs::hard_link(&source, &program).is_err() {
copy_executable(&source, &program)?;
}
let workspace = root.path().join("workspace");
let bin = workspace.join("node_modules/.bin");
let marker = root.path().join("helper-ran");
std::fs::create_dir_all(&bin)?;
std::fs::create_dir_all(workspace.join(".git"))?;
std::fs::write(
home.join("config.toml"),
r#"
cli_auth_credentials_store = "file"
check_for_update_on_startup = false
model_provider = "local"
[model_providers.local]
name = "local test"
base_url = "http://127.0.0.1:9/v1"
wire_api = "responses"
"#,
)?;
for name in [
"zellij", "tmux", "which", "where", "npm", "rg", "git", "curl", "cmd.exe",
] {
#[cfg(unix)]
{
let executable = bin.join(name);
akode_utils_cargo_bin::write_executable(
&executable,
"#!/bin/sh\nprintf 'helper ran\\n' >> \"$AKODE_TEST_HELPER_MARKER\"\nexit 0\n",
)?;
}
#[cfg(windows)]
std::fs::write(
bin.join(format!("{name}.cmd")),
"@echo helper ran>>\"%AKODE_TEST_HELPER_MARKER%\"\r\n@exit /b 0\r\n",
)?;
}
// Windows selects rg.exe explicitly, so rg.cmd cannot satisfy discovery.
// An invalid image still counts as found: doctor must not execute it.
#[cfg(windows)]
std::fs::write(bin.join("rg.exe"), "not an executable image")?;
let path = std::env::join_paths(std::iter::once(bin).chain(std::env::split_paths(
&std::env::var_os("PATH").unwrap_or_default(),
)))?;
Ok(Self {
root,
program,
workspace,
home,
marker,
path,
})
}
fn command(&self) -> Result<assert_cmd::Command> {
let mut command = assert_cmd::Command::new(&self.program);
command
.current_dir(&self.workspace)
.env("AKODE_HOME", &self.home)
.env("HOME", self.root.path())
.env("PATH", &self.path)
.env("AKODE_TEST_HELPER_MARKER", &self.marker)
.env("AKODE_MANAGED_BY_NPM", "1")
.env(
"AKODE_MANAGED_PACKAGE_ROOT",
self.workspace.join("node_modules/@openai/codex"),
)
.env(
"AKODE_APP_SERVER_MANAGED_CONFIG_PATH",
self.home.join("managed_config.toml"),
)
.env("HTTPS_PROXY", "http://127.0.0.1:9")
.env("HTTP_PROXY", "http://127.0.0.1:9")
.env("ALL_PROXY", "http://127.0.0.1:9")
.env("https_proxy", "http://127.0.0.1:9")
.env("http_proxy", "http://127.0.0.1:9")
.env("all_proxy", "http://127.0.0.1:9")
.env("NO_PROXY", "127.0.0.1,localhost")
.env("no_proxy", "127.0.0.1,localhost")
.env_remove("TMUX")
.env_remove("TMUX_PANE")
.env_remove("ZELLIJ_VERSION")
.env_remove("ZELLIJ_SESSION_NAME")
.env_remove("TERM_PROGRAM")
.env("TERM", "dumb")
.env("ZELLIJ", "0")
.timeout(Duration::from_secs(/*secs*/ 45));
Ok(command)
}
}
#[test]
#[cfg_attr(
windows,
ignore = "Windows doctor fixture does not discover the synthetic Git executable"
)]
fn startup_and_doctor_do_not_execute_path_helpers() -> Result<()> {
let fixture = Fixture::new()?;
// Non-TTY dumb-terminal startup exits immediately after terminal detection.
fixture.command()?.assert().failure();
assert!(!fixture.marker.exists(), "startup executed a PATH helper");
for args in [
vec!["doctor", "--json"],
vec!["doctor", "--json", "--feedback"],
] {
let mut command = fixture.command()?;
command
.args(args)
.env("TMUX", "test-tmux")
.env("TERM_PROGRAM", "tmux");
let output = command.output()?;
let report: Value = serde_json::from_slice(&output.stdout)?;
assert_eq!(
report["checks"]["installation"]["details"]["managed by npm"],
"true"
);
assert_eq!(report["checks"]["runtime.search"]["status"], "ok");
assert_eq!(
report["checks"]["runtime.search"]["details"]["search command path"],
fixture
.workspace
.join("node_modules/.bin")
.join(format!("rg{}", std::env::consts::EXE_SUFFIX))
.display()
.to_string()
);
assert_eq!(
report["checks"]["git.environment"]["summary"],
"git executable found; execution not verified"
);
assert!(!fixture.marker.exists(), "doctor executed a PATH helper");
}
Ok(())
}
#[test]
fn non_interactive_dumb_terminal_preserves_other_doctor_failures() -> Result<()> {
let fixture = Fixture::new()?;
let output = fixture
.command()?
.args(["doctor", "--json"])
// Explicit identity takes precedence over inherited terminal-specific variables.
.env("TERM_PROGRAM", "dumb")
.env_remove("TERMINFO")
.env_remove("TERMINFO_DIRS")
.output()?;
// The fixture's provider is unreachable, regardless of terminal capabilities.
assert_eq!(output.status.code(), Some(1));
let report: Value = serde_json::from_slice(&output.stdout)?;
assert_eq!(report["checks"]["terminal.env"]["status"], "warning");
assert_eq!(report["overallStatus"], "fail");
Ok(())
}
#[test]
fn doctor_reports_failed_database_paths() -> Result<()> {
let fixture = Fixture::new()?;
let sqlite_home = fixture.root.path().join("sqlite");
std::fs::create_dir(&sqlite_home)?;
let sqlite = SqliteConfig::new_for_testing(AbsolutePathBuf::try_from(sqlite_home.clone())?);
let config_file = fixture.home.join("config.toml");
let config = std::fs::read_to_string(&config_file)?;
let sqlite_home = toml::Value::String(sqlite_home.display().to_string());
std::fs::write(
&config_file,
format!("sqlite_home = {sqlite_home}\nlog_dir = {sqlite_home}\n{config}"),
)?;
for (snapshot_name, failed_paths) in [
("doctor_failed_log_database", vec![sqlite.logs_db_path()]),
(
"doctor_failed_multiple_databases",
vec![sqlite.logs_db_path(), sqlite.goals_db_path()],
),
] {
for path in &failed_paths {
std::fs::write(path, "not a SQLite database")?;
}
let paths = failed_paths
.iter()
.map(|path| path.display().to_string())
.collect::<Vec<_>>()
.join(", ");
let noun = if failed_paths.len() == 1 {
"database"
} else {
"databases"
};
let expected_cause = format!("{paths} {noun} failed integrity check");
for args in [
vec!["doctor", "--json"],
vec!["doctor", "--json", "--feedback"],
] {
let output = fixture.command()?.args(args).output()?;
assert_eq!(output.status.code(), Some(1));
let report: Value = serde_json::from_slice(&output.stdout)?;
assert_eq!(report["checks"]["state.paths"]["status"], "fail");
assert_eq!(
report["checks"]["state.paths"]["summary"],
"state database integrity check failed"
);
assert_eq!(
report["checks"]["state.paths"]["issues"][0]["cause"],
expected_cause
);
}
for summary_only in [false, true] {
let mut command = fixture.command()?;
command.args(["doctor", "--ascii", "--no-color"]);
if summary_only {
command.arg("--summary");
}
let output = command.output()?;
assert_eq!(output.status.code(), Some(1));
let stdout = String::from_utf8(output.stdout)?;
let state_row = stdout
.lines()
.filter(|line| {
line.starts_with(" [XX] state ")
|| (!summary_only
&& line.starts_with(" -> Move the damaged SQLite database aside"))
})
.collect::<Vec<_>>()
.join("\n")
.replace(&fixture.root.path().display().to_string(), "FIXTURE")
.replace('\\', "/");
if summary_only {
assert_eq!(
state_row,
format!(
" [XX] state {}",
expected_cause
.replace(&fixture.root.path().display().to_string(), "FIXTURE")
)
.replace('\\', "/")
);
} else {
insta::assert_snapshot!(snapshot_name, state_row);
}
}
for path in &failed_paths {
assert_eq!(std::fs::read_to_string(path)?, "not a SQLite database");
}
}
Ok(())
}
#[test]
fn doctor_redacts_failed_database_paths_in_json() -> Result<()> {
let fixture = Fixture::new()?;
let sqlite_home = fixture.root.path().join("doctor-secret-sqlite");
std::fs::create_dir(&sqlite_home)?;
let sqlite = SqliteConfig::new_for_testing(AbsolutePathBuf::try_from(sqlite_home.clone())?);
let config_file = fixture.home.join("config.toml");
let config = std::fs::read_to_string(&config_file)?;
let sqlite_home = toml::Value::String(sqlite_home.display().to_string());
std::fs::write(
&config_file,
format!("sqlite_home = {sqlite_home}\nlog_dir = {sqlite_home}\n{config}"),
)?;
std::fs::write(sqlite.logs_db_path(), "not a SQLite database")?;
let output = fixture
.command()?
.args(["doctor", "--json", "--feedback"])
.output()?;
assert_eq!(output.status.code(), Some(1));
let stdout = String::from_utf8(output.stdout)?;
assert!(!stdout.contains("doctor-secret-sqlite"));
let report: Value = serde_json::from_str(&stdout)?;
assert_eq!(
report["checks"]["state.paths"]["summary"],
"state database integrity check failed"
);
assert_eq!(
report["checks"]["state.paths"]["issues"][0]["cause"],
"<redacted>"
);
Ok(())
}
#[test]
fn doctor_reports_only_safe_config_error_metadata() -> Result<()> {
let fixture = Fixture::new()?;
let user_config_file = fixture.home.join("config.toml");
let original = std::fs::read_to_string(&user_config_file)?;
// macOS temp directories can use a symlinked path; trust the canonical workspace.
let project_key = toml::Value::String(project_trust_key(&fixture.workspace));
let original = format!("{original}\n[projects.{project_key}]\ntrust_level = \"trusted\"\n");
let project_config_dir = fixture.workspace.join(".akode");
std::fs::create_dir(&project_config_dir)?;
for (snapshot_name, config_file, config) in [
(
"doctor_config_error_location",
user_config_file.clone(),
"custom_header = \"doctor-test-credential\" trailing\n".to_string(),
),
(
"doctor_config_invalid_data",
project_config_dir.join("config.toml"),
"custom_header = \"doctor-test-credential\" trailing\n".to_string(),
),
(
"doctor_config_not_found",
user_config_file.clone(),
original.replace(
"model_provider = \"local\"",
"model_provider = \"doctor-test-credential\"",
),
),
// A type error in a known key reports its location (file/line/column) but never
// the offending value.
(
"doctor_config_invalid_type",
user_config_file.clone(),
original.replace(
"wire_api = \"responses\"",
"wire_api = \"responses\"\nhttp_headers = \"sk-proj-ABC123example\"",
),
),
] {
std::fs::write(&user_config_file, &original)?;
std::fs::write(&config_file, config)?;
for args in [
vec!["doctor", "--json"],
vec!["doctor", "--json", "--feedback"],
] {
let output = fixture.command()?.args(args).output()?;
assert_eq!(output.status.code(), Some(1));
let report: Value = serde_json::from_slice(&output.stdout)?;
let mut check = report["checks"]["config.load"].clone();
check
.as_object_mut()
.expect("config check")
.remove("durationMs");
if let Some(file) = check["details"]["file"].as_str() {
check["details"]["file"] = Value::String(
file.replace(
&fixture.root.path().canonicalize()?.display().to_string(),
"FIXTURE",
)
.replace(&fixture.root.path().display().to_string(), "FIXTURE")
.replace('\\', "/"),
);
}
let stdout = String::from_utf8_lossy(&output.stdout);
assert!(!stdout.contains("doctor-test-credential"));
assert!(!stdout.contains("sk-proj-ABC123example"));
// Keep snapshots stable across serde_json feature sets in Cargo and Bazel.
check.sort_all_objects();
insta::assert_snapshot!(snapshot_name, serde_json::to_string_pretty(&check)?);
}
std::fs::remove_file(config_file)?;
}
Ok(())
}
#[test]
fn doctor_reports_configured_tui_mode() -> Result<()> {
let fixture = Fixture::new()?;
for (setting, expected) in [("true", "fullscreen"), ("false", "scrollback")] {
let output = fixture
.command()?
.args(["-c", &format!("tui.fullscreen_transcript={setting}")])
.args(["doctor", "--json"])
.output()?;
let report: Value = serde_json::from_slice(&output.stdout)?;
assert_eq!(
report["checks"]["config.load"]["details"]["configured TUI mode"],
expected
);
}
Ok(())
}
#[test]
fn doctor_reports_configured_filesystem_paths() -> Result<()> {
let fixture = Fixture::new()?;
let config_file = fixture.home.join("config.toml");
let original = std::fs::read_to_string(&config_file)?;
let existing = fixture.workspace.join("probe-existing");
let missing = fixture.workspace.join("probe-missing");
std::fs::create_dir(&existing)?;
let existing_key = toml::Value::String(existing.display().to_string());
let missing_key = toml::Value::String(missing.display().to_string());
std::fs::write(
&config_file,
format!(
r#"default_permissions = "diagnostic"
{original}
[permissions.diagnostic]
extends = ":read-only"
[permissions.diagnostic.filesystem]
{existing_key} = "read"
{missing_key} = "write"
"#
),
)?;
let output = fixture.command()?.args(["doctor", "--json"]).output()?;
let report: Value = serde_json::from_slice(&output.stdout)?;
#[cfg(windows)]
assert_eq!(report["checks"]["sandbox.filesystem_paths"]["status"], "ok");
let mut details = report["checks"]["sandbox.filesystem_paths"]["details"].clone();
// Snapshot outcomes and provenance independently of helper startup speed.
details
.as_object_mut()
.expect("path details")
.retain(|key, _| !key.ends_with(" latency"));
let canonical_root = fixture.root.path().canonicalize()?;
for value in details.as_object_mut().expect("path details").values_mut() {
let detail = value
.as_str()
.expect("scalar path detail")
.replace(&canonical_root.display().to_string(), "FIXTURE")
.replace(&fixture.root.path().display().to_string(), "FIXTURE")
.replace('\\', "/");
*value = Value::String(detail);
}
let snapshot_name = if cfg!(windows) {
"doctor_configured_filesystem_paths_windows"
} else {
"doctor_configured_filesystem_paths"
};
insta::assert_snapshot!(snapshot_name, serde_json::to_string_pretty(&details)?);
Ok(())
}
#[test]
fn filesystem_probe_does_not_load_configuration() -> Result<()> {
let fixture = Fixture::new()?;
std::fs::write(fixture.home.join("config.toml"), "invalid TOML = [")?;
for (path, expected) in [
(&fixture.workspace, 0),
(&fixture.workspace.join("missing"), 2),
] {
let output = fixture
.command()?
.args(["doctor", "--probe-filesystem-path"])
.arg(path)
.output()?;
assert_eq!(
output.status.code(),
Some(if cfg!(windows) { 5 } else { expected })
);
assert!(output.stdout.is_empty());
}
Ok(())
}
#[cfg(unix)]
#[tokio::test]
async fn interactive_tmux_startup_does_not_execute_workspace_helpers() -> Result<()> {
let fixture = Fixture::new()?;
std::fs::create_dir(fixture.workspace.join(".akode"))?;
let command = fixture.command()?;
let mut env: std::collections::HashMap<String, String> = std::env::vars().collect();
for (key, value) in command.get_envs() {
let key = key.to_string_lossy().into_owned();
if let Some(value) = value {
env.insert(key, value.to_string_lossy().into_owned());
} else {
env.remove(&key);
}
}
env.insert("TERM".to_string(), "xterm-256color".to_string());
env.insert("TERM_PROGRAM".to_string(), "tmux".to_string());
env.insert("TMUX".to_string(), "test-tmux".to_string());
env.insert(
"AKODE_TUI_DISABLE_KEYBOARD_ENHANCEMENT".to_string(),
"0".to_string(),
);
env.insert(
"GHOSTTY_RESOURCES_DIR".to_string(),
"/test/ghostty".to_string(),
);
let spawned = akode_utils_pty::spawn_pty_process(
fixture.program.to_str().unwrap(),
&["--no-daemon".to_string()],
&fixture.workspace,
&env,
/*arg0*/ &None,
akode_utils_pty::TerminalSize {
rows: 40,
cols: 120,
},
akode_utils_pty::ChildFds::Inherited(&[]),
)
.await?;
let session = spawned.session;
let mut output_rx = spawned.stdout_rx;
let writer = session.writer_sender();
let mut output = String::new();
let ansi = regex_lite::Regex::new(r"\x1b\[[0-?]*[ -/]*[@-~]")?;
let ready = timeout(Duration::from_secs(/*secs*/ 45), async {
while let Some(bytes) = output_rx.recv().await {
let chunk = String::from_utf8_lossy(&bytes);
output.push_str(&chunk);
if chunk.contains("\x1b[6n") {
writer.send(b"\x1b[1;1R".to_vec()).await?;
}
if chunk.contains("\x1b[c") {
writer.send(b"\x1b[?1;2c".to_vec()).await?;
}
// Ratatui can position over spaces instead of writing them.
let text: String = ansi
.replace_all(&output, "")
.chars()
.filter(|character| !character.is_whitespace())
.collect();
if text.contains("Trustthisfolder?") {
return Ok::<_, anyhow::Error>(());
}
}
anyhow::bail!("TUI exited before trust prompt")
})
.await;
ready.map_err(|_| {
anyhow::anyhow!(
"trust prompt timed out: {}",
output.chars().take(/*n*/ 4000).collect::<String>()
)
})??;
// The first Ctrl+C leaves the untrusted workspace for the command center.
// Keep sending Ctrl+C so the TUI exits even if the first draw discarded input.
let mut quit_retry = tokio::time::interval(Duration::from_millis(/*millis*/ 250));
let mut exit_rx = spawned.exit_rx;
timeout(Duration::from_secs(/*secs*/ 10), async {
loop {
tokio::select! {
result = &mut exit_rx => return result,
_ = quit_retry.tick() => {
let _ = writer.send(b"\x03".to_vec()).await;
}
Some(_) = output_rx.recv() => {}
}
}
})
.await
.with_context(|| {
format!(
"TUI did not exit after declining directory trust: {}",
output.chars().take(/*n*/ 4000).collect::<String>()
)
})??;
assert!(
output.contains("\x1b[>5u"),
"expected safe Ghostty/tmux keyboard flags: {output}"
);
assert!(
!fixture.marker.exists(),
"interactive startup executed a workspace helper"
);
Ok(())
}
#[tokio::test]
async fn feedback_with_logs_does_not_execute_path_helpers() -> Result<()> {
let fixture = Fixture::new()?;
let proxy = TcpListener::bind("127.0.0.1:0").await?;
let proxy_uri = format!("http://{}", proxy.local_addr()?);
// Reject all outbound traffic locally; feedback collection must not need the network.
let proxy_task = tokio::spawn(async move {
while let Ok((stream, _)) = proxy.accept().await {
let mut stream = BufReader::new(stream);
let mut request = String::new();
if stream.read_line(&mut request).await.is_ok() {
let _ = stream.get_mut().write_all(b"HTTP/1.1 503 Service Unavailable\r\nContent-Length: 0\r\nConnection: close\r\n\r\n").await;
}
}
});
let path = fixture.path.to_string_lossy();
let marker = fixture.marker.to_string_lossy();
let home = fixture.root.path().to_string_lossy();
let package_root = fixture.workspace.join("node_modules/@openai/codex");
let package_root = package_root.to_string_lossy();
let mut app_server = TestAppServer::builder()
.with_program(&fixture.program)
.with_codex_home(&fixture.home)
// The CLI does not accept the standalone app-server's test-only flag.
// Disable plugins through real config; their safety test joins a full sync.
.with_plugin_startup_tasks()
.with_args(&["-c", "features.plugins=false", "app-server"])
.with_env_overrides(&[
("PATH", Some(path.as_ref())),
("HOME", Some(home.as_ref())),
("AKODE_TEST_HELPER_MARKER", Some(marker.as_ref())),
("AKODE_MANAGED_BY_NPM", Some("1")),
("AKODE_MANAGED_PACKAGE_ROOT", Some(package_root.as_ref())),
("ZELLIJ", Some("0")),
("ZELLIJ_VERSION", None),
("TMUX", None),
("TMUX_PANE", None),
("HTTP_PROXY", Some(&proxy_uri)),
("HTTPS_PROXY", Some(&proxy_uri)),
("ALL_PROXY", Some(&proxy_uri)),
("http_proxy", Some(&proxy_uri)),
("https_proxy", Some(&proxy_uri)),
("all_proxy", Some(&proxy_uri)),
("NO_PROXY", Some("127.0.0.1,localhost")),
("no_proxy", Some("127.0.0.1,localhost")),
])
.build_initialized_with_timeout(Duration::from_secs(/*secs*/ 30))
.await?;
// Feedback is only ever saved locally; collecting its diagnostics must not run PATH helpers.
let save_path = fixture.root.path().join("feedback.zip");
let request_id = app_server
.send_raw_request(
"feedback/save",
Some(json!({
"classification": "bug",
"includeLogs": true,
"savePath": save_path.to_string_lossy(),
})),
)
.await?;
timeout(
Duration::from_secs(/*secs*/ 45),
app_server.read_stream_until_response_message(RequestId::Integer(request_id)),
)
.await??;
assert!(save_path.exists(), "feedback must be saved locally");
assert!(!fixture.marker.exists(), "feedback executed a PATH helper");
timeout(
Duration::from_secs(/*secs*/ 10),
app_server.shutdown_gracefully(),
)
.await??;
proxy_task.abort();
Ok(())
}

View File

@@ -0,0 +1,928 @@
#[cfg(target_os = "linux")]
#[path = "exec_server/pid_namespace_tests.rs"]
mod pid_namespace_tests;
use std::collections::HashMap;
#[cfg(unix)]
use std::io::BufRead as _;
#[cfg(unix)]
use std::io::BufReader as StdBufReader;
#[cfg(unix)]
use std::io::Read as _;
#[cfg(unix)]
use std::io::Write as _;
#[cfg(unix)]
use std::net::TcpStream;
use std::path::Path;
use std::process::Stdio;
#[cfg(unix)]
use std::thread;
use std::time::Duration;
#[cfg(unix)]
use std::time::Instant;
use anyhow::Context;
use anyhow::Result;
use akode_exec_server::EnvironmentInfo;
use akode_exec_server::ExecParams;
use akode_exec_server::ExecServerClient;
use akode_exec_server::NoiseChannelIdentity;
use akode_exec_server::NoiseChannelPublicKey;
use akode_exec_server::NoiseRendezvousConnectArgs;
use akode_exec_server::NoiseRendezvousConnectBundle;
use akode_exec_server::ProcessId;
use akode_http_client::HttpClientFactory;
use akode_http_client::OutboundProxyPolicy;
use akode_utils_cargo_bin::copy_executable;
use akode_utils_path_uri::PathUri;
use futures::SinkExt;
use futures::StreamExt;
use predicates::prelude::PredicateBooleanExt;
use predicates::str::contains;
use pretty_assertions::assert_eq;
use tempfile::TempDir;
use tokio::io::AsyncBufReadExt;
use tokio::io::AsyncWriteExt;
use tokio::io::BufReader;
use tokio::net::TcpListener;
use tokio_tungstenite::WebSocketStream;
use tokio_tungstenite::accept_async;
use tokio_tungstenite::accept_hdr_async;
use tokio_tungstenite::tungstenite::handshake::server::Request;
use tokio_tungstenite::tungstenite::handshake::server::Response;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::header;
use wiremock::matchers::method;
use wiremock::matchers::path;
fn codex_command(codex_home: &Path) -> Result<assert_cmd::Command> {
let mut cmd = assert_cmd::Command::new(akode_utils_cargo_bin::cargo_bin("akode")?);
cmd.env("AKODE_HOME", codex_home);
Ok(cmd)
}
#[test]
fn strict_config_rejects_unknown_config_fields_for_exec_server() -> Result<()> {
let codex_home = TempDir::new()?;
std::fs::write(
codex_home.path().join("config.toml"),
r#"
foo = "bar"
"#,
)?;
let mut cmd = codex_command(codex_home.path())?;
cmd.args([
"exec-server",
"--strict-config",
"--listen",
"http://127.0.0.1:0",
])
.assert()
.failure()
.stderr(contains("unknown configuration field"));
Ok(())
}
#[test]
fn local_exec_server_ignores_invalid_config_without_strict_config() -> Result<()> {
let codex_home = TempDir::new()?;
std::fs::write(codex_home.path().join("config.toml"), "not valid toml = [")?;
let mut cmd = codex_command(codex_home.path())?;
cmd.args(["exec-server", "--listen", "stdio"])
.assert()
.success()
.stderr(contains("not valid toml").not());
Ok(())
}
/// Real global CLI flags must reach executor config reads; unrelated startup flags stay private.
#[tokio::test]
async fn local_exec_server_projects_global_mxc_preference() -> Result<()> {
let home = TempDir::new()?;
let cwd = url::Url::from_directory_path(home.path())
.map_err(|()| anyhow::anyhow!("could not convert home to file URL"))?;
let mut child = tokio::process::Command::new(akode_utils_cargo_bin::cargo_bin("akode")?)
.env("AKODE_HOME", home.path())
.args([
"-c",
"features.prefer_mxc=true",
"-c",
"model='private-startup-model'",
"exec-server",
"--listen",
"stdio",
])
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.kill_on_drop(true)
.spawn()?;
let mut stdin = child.stdin.take().context("exec-server stdin")?;
let mut stdout = BufReader::new(child.stdout.take().context("exec-server stdout")?);
let result = tokio::time::timeout(Duration::from_secs(30), async {
send_json_line(
&mut stdin,
&serde_json::json!({"id": 1, "method": "initialize",
"params": {"clientName": "mxc-test", "resumeSessionId": null}}),
)
.await?;
wait_for_response(&mut stdout, /*expected_id*/ 1).await?;
send_json_line(
&mut stdin,
&serde_json::json!({"method": "initialized", "params": {}}),
)
.await?;
send_json_line(
&mut stdin,
&serde_json::json!({"id": 2, "method": "environmentConfig/read", "params": {
"cwd": cwd, "configPaths": [["features", "prefer_mxc"], ["model"]],
"requirementsPaths": []
}}),
)
.await?;
wait_for_response(&mut stdout, /*expected_id*/ 2).await
})
.await
.context("executor CLI config read timed out")??;
let layers = result["result"]["config"]["layers"]
.as_array()
.context("config layers")?;
let session = layers
.iter()
.find(|l| l["source"] == "session-flags")
.context("session flags")?;
let value: toml::Value = toml::from_str(session["toml"].as_str().context("session TOML")?)?;
assert_eq!(
value,
toml::Value::Table(toml::toml! { [features] prefer_mxc = true })
);
drop(stdin);
assert!(
tokio::time::timeout(Duration::from_secs(30), child.wait())
.await??
.success()
);
Ok(())
}
/// The standalone exec-server accepts an explicit per-connection concurrency limit.
#[test]
fn local_exec_server_accepts_concurrent_requests_flag() -> Result<()> {
let codex_home = TempDir::new()?;
let mut cmd = codex_command(codex_home.path())?;
cmd.args([
"exec-server",
"--listen",
"stdio",
"--concurrent-requests",
"2",
])
.assert()
.success();
Ok(())
}
#[test]
fn local_exec_server_allows_disabled_parent_lifetime_environment_variable() -> Result<()> {
let codex_home = TempDir::new()?;
let mut cmd = codex_command(codex_home.path())?;
cmd.env(
akode_exec_server::AKODE_EXEC_SERVER_EXIT_ON_STDIN_CLOSE_ENV_VAR,
"false",
)
.args(["exec-server", "--listen", "stdio"])
.assert()
.success();
Ok(())
}
#[tokio::test]
async fn remote_exec_server_gracefully_stops_when_parent_stdin_closes() -> Result<()> {
const ENVIRONMENT_ID: &str = "environment-parent-lifetime";
const EXECUTOR_REGISTRATION_ID: &str = "registration-parent-lifetime";
const TEST_TIMEOUT: Duration = Duration::from_secs(30);
let listener = TcpListener::bind("127.0.0.1:0").await?;
let rendezvous_url = format!("ws://{}", listener.local_addr()?);
let registry = MockServer::start().await;
Mock::given(method("POST"))
.and(path(format!(
"/cloud/environment/{ENVIRONMENT_ID}/register"
)))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"environment_id": ENVIRONMENT_ID,
"url": format!("{rendezvous_url}/relay?role=environment"),
"security_profile": "noise_hybrid_ik_v1",
"executor_registration_id": EXECUTOR_REGISTRATION_ID,
})))
.mount(&registry)
.await;
Mock::given(method("POST"))
.and(path(format!(
"/cloud/environment/{ENVIRONMENT_ID}/validate"
)))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"valid": true,
})))
.mount(&registry)
.await;
let codex_home = TempDir::new()?;
std::fs::write(
codex_home.path().join("config.toml"),
"cli_auth_credentials_store = \"file\"\n",
)?;
let package = TempDir::new()?;
let bin_dir = package.path().join("bin");
std::fs::create_dir(&bin_dir)?;
let executable = bin_dir.join(format!("codex{}", std::env::consts::EXE_SUFFIX));
copy_executable(&akode_utils_cargo_bin::cargo_bin("akode")?, &executable)?;
let codex_path_dir = package.path().join("akode-path");
std::fs::create_dir(&codex_path_dir)?;
let manifest = package.path().join("akode-package.json");
std::fs::write(&manifest, r#"{"version":"1.2.3-alpha.4"}"#)?;
let stderr_path = codex_home.path().join("executor-stderr.log");
let stderr = std::fs::File::create(&stderr_path)?;
let mut command = tokio::process::Command::new(executable);
command
.current_dir(codex_home.path())
.env("AKODE_HOME", codex_home.path())
.env("AKODE_API_KEY", "test-api-key")
.env_remove("AKODE_ACCESS_TOKEN")
.env(
akode_exec_server::AKODE_EXEC_SERVER_EXIT_ON_STDIN_CLOSE_ENV_VAR,
"true",
)
.env("NO_PROXY", "127.0.0.1,localhost")
.env("no_proxy", "127.0.0.1,localhost")
.env("RUST_LOG", "error,akode_exec_server::remote=info")
.args([
"exec-server",
"--remote",
&registry.uri(),
"--environment-id",
ENVIRONMENT_ID,
"--concurrent-requests",
"2",
])
.stdin(Stdio::piped())
.stderr(Stdio::from(stderr))
.kill_on_drop(true);
let mut child = command.spawn()?;
let stdin = child
.stdin
.take()
.ok_or_else(|| anyhow::anyhow!("remote exec-server stdin was not piped"))?;
// An executor that exits during startup cannot reach the rendezvous. Report that
// exit immediately instead of hiding it behind the connection timeout.
let environment_websocket = tokio::select! {
status = child.wait() => {
let status = status.context("failed to wait for remote exec-server")?;
Err(anyhow::anyhow!("remote exec-server exited before connecting: {status}"))
}
result = accept_parent_lifetime_websocket(&listener, TEST_TIMEOUT) => result,
};
let environment_websocket = match environment_websocket {
Ok(websocket) => websocket,
Err(error) => {
let registration_requests = registry.received_requests().await.map(|requests| {
requests
.iter()
.filter(|request| request.url.path().ends_with("/register"))
.count()
});
// Keep registry request headers and bodies out of the failure report.
let child_status = child.try_wait();
let stderr = std::fs::read_to_string(&stderr_path)?;
return Err(error.context(format!(
"remote executor failed to attach (registration requests: {registration_requests:?}, child status: {child_status:?}); stderr: {stderr}"
)));
}
};
// Remote startup must capture the version before registration, not on the first initialize.
std::fs::write(&manifest, r#"{"version":"9.9.9"}"#)?;
let executor_public_key = registered_parent_lifetime_executor_public_key(&registry).await?;
let harness_args = NoiseRendezvousConnectArgs {
bundle: NoiseRendezvousConnectBundle {
websocket_url: format!("{rendezvous_url}/relay?role=harness"),
environment_id: ENVIRONMENT_ID.to_string(),
executor_registration_id: EXECUTOR_REGISTRATION_ID.to_string(),
executor_public_key,
harness_key_authorization: "parent-lifetime-harness".to_string(),
},
harness_identity: NoiseChannelIdentity::generate()?,
client_name: "parent-lifetime-test".to_string(),
connect_timeout: TEST_TIMEOUT,
initialize_timeout: TEST_TIMEOUT,
resume_session_id: None,
http_client_factory: HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
};
let client_task =
tokio::spawn(async move { ExecServerClient::connect_noise_rendezvous(harness_args).await });
let harness_websocket = accept_parent_lifetime_websocket(&listener, TEST_TIMEOUT)
.await
.context("harness failed to attach")?;
let relay_task = tokio::spawn(proxy_parent_lifetime_relay(
environment_websocket,
harness_websocket,
));
let client = tokio::time::timeout(TEST_TIMEOUT, client_task)
.await
.context("remote harness did not connect")???;
let environment_info = client.environment_info().await?;
assert_eq!(
environment_info
.prepend_path_dirs
.iter()
.map(|path| std::fs::canonicalize(path.inferred_native_path_string()))
.collect::<std::io::Result<Vec<_>>>()?,
vec![codex_path_dir.canonicalize()?]
);
let expected_info = EnvironmentInfo {
executor_version: "1.2.3-alpha.4".to_string(),
cwd: Some(PathUri::from_host_native_path(
codex_home.path().canonicalize()?,
)?),
// The build identity belongs to the spawned CLI, not this test process.
provider_id: environment_info.provider_id.clone(),
prepend_path_dirs: environment_info.prepend_path_dirs.clone(),
..EnvironmentInfo::local()
};
assert_eq!(environment_info.as_ref(), &expected_info);
std::fs::remove_file(&manifest)?;
assert_eq!(client.force_environment_info().await?, expected_info);
#[cfg(windows)]
let argv = vec![
"powershell.exe",
"-NoLogo",
"-NoProfile",
"-NonInteractive",
"-Command",
"if (Test-Path Env:AKODE_EXEC_SERVER_EXIT_ON_STDIN_CLOSE) { exit 1 }; Start-Sleep -Seconds 60",
];
#[cfg(not(windows))]
let argv = vec![
"/bin/sh",
"-c",
"[ -z \"${AKODE_EXEC_SERVER_EXIT_ON_STDIN_CLOSE+present}\" ] && exec /bin/sleep 60",
];
let cwd = url::Url::from_directory_path(std::env::current_dir()?)
.map_err(|()| anyhow::anyhow!("could not convert cwd to file URL"))?;
client
.exec(ExecParams {
metadata: Default::default(),
process_id: ProcessId::from("parent-lifetime-process"),
argv: argv.into_iter().map(str::to_string).collect(),
cwd: cwd.as_str().parse()?,
shell_snapshot: None,
env_policy: Some(akode_exec_server::ExecEnvPolicy {
inherit: akode_protocol::config_types::ShellEnvironmentPolicyInherit::All,
ignore_default_excludes: false,
exclude: Vec::new(),
r#set: HashMap::new(),
include_only: Vec::new(),
}),
env: HashMap::new(),
tty: false,
pipe_stdin: false,
arg0: None,
sandbox: None,
enforce_managed_network: false,
managed_network: None,
network_proxy: None,
})
.await?;
anyhow::ensure!(
child.try_wait()?.is_none(),
"remote exec-server exited while its parent stdin remained open"
);
drop(stdin);
let status = tokio::time::timeout(TEST_TIMEOUT, child.wait())
.await
.map_err(|_| anyhow::anyhow!("remote exec-server did not exit after stdin closed"))??;
anyhow::ensure!(status.success(), "remote exec-server exited with {status}");
relay_task.abort();
let _ = relay_task.await;
Ok(())
}
#[tokio::test]
async fn forward_rejects_stdin_credentials_on_opposite_sides_of_subcommand() -> Result<()> {
let codex = akode_utils_cargo_bin::cargo_bin("akode")?;
let home = TempDir::new()?;
let remote = [
"--remote",
"https://registry.example",
"--environment-id",
"env-1",
];
let bearer = "--registration-bearer-stdin";
let rotating = "--executor-credential-stdin";
for (before, after) in [(bearer, rotating), (rotating, bearer)] {
let mut child = tokio::process::Command::new(&codex)
.env("AKODE_HOME", home.path())
.arg("exec-server")
.args(remote)
.args([before, "forward", "--connect", "ws://127.0.0.1:8765"])
.args(remote)
.arg(after)
.stdin(Stdio::piped())
.stderr(Stdio::piped())
.kill_on_drop(true)
.spawn()?;
// Keep the empty pipe open so either credential read would block.
let _stdin = child.stdin.take().context("credential pipe")?;
let output = tokio::time::timeout(Duration::from_secs(30), child.wait_with_output())
.await
.context("exec-server waited for a credential")??;
assert!(!output.status.success());
assert!(String::from_utf8(output.stderr)?.contains(
"--registration-bearer-stdin cannot be used with --executor-credential-stdin"
));
}
Ok(())
}
#[tokio::test]
async fn remote_exec_server_scoped_credentials_authenticate_only_register_and_validate()
-> Result<()> {
const ENVIRONMENT: &str = "environment-scoped-credentials";
const CREDENTIAL: &str = "synthetic-scoped-credential-never-log-1234";
const ROTATED_CREDENTIAL: &str = "rotated-scoped-credential";
const TIMEOUT: Duration = Duration::from_secs(30);
let listener = TcpListener::bind("127.0.0.1:0").await?;
let rendezvous = format!("ws://{}", listener.local_addr()?);
let registry = MockServer::start().await;
let (registration_tx, mut registration_rx) = tokio::sync::mpsc::unbounded_channel();
// A confirmed pre-write auth outage must retry with the same scoped credential.
Mock::given(method("POST"))
.and(path(format!("/cloud/environment/{ENVIRONMENT}/register")))
.respond_with(ResponseTemplate::new(502).set_body_json(serde_json::json!({
"detail": {"code": "authentication_service_unavailable", "message": CREDENTIAL},
})))
.with_priority(1)
.up_to_n_times(1)
.expect(1)
.mount(&registry)
.await;
let registration_response = ResponseTemplate::new(200).set_body_json(serde_json::json!({
"environment_id": ENVIRONMENT,
"url": format!("{rendezvous}/relay?role=environment"),
"security_profile": "noise_hybrid_ik_v1",
"executor_registration_id": "registration-scoped",
}));
Mock::given(method("POST"))
.and(path(format!("/cloud/environment/{ENVIRONMENT}/register")))
.respond_with(move |request: &wiremock::Request| {
let credential = request
.headers
.get("authorization")
.and_then(|value| value.to_str().ok())
.and_then(|value| value.strip_prefix("Bearer "))
.unwrap_or_default()
.to_string();
let _ = registration_tx.send(credential);
registration_response.clone()
})
.mount(&registry)
.await;
Mock::given(method("POST"))
.and(path(format!("/cloud/environment/{ENVIRONMENT}/validate")))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({"valid": true})))
.mount(&registry)
.await;
let collector = MockServer::start().await;
let home = TempDir::new()?;
std::fs::write(
home.path().join("config.toml"),
format!(
r#"
[otel]
metrics_exporter = {{ otlp-http = {{ endpoint = "{}/v1/metrics", protocol = "json", headers = {{ Authorization = "general-telemetry-token" }} }} }}
"#,
collector.uri()
),
)?;
std::fs::write(
home.path().join("auth.json"),
r#"{"OPENAI_API_KEY":"general-file-token"}"#,
)?;
let mut command = tokio::process::Command::new(akode_utils_cargo_bin::cargo_bin("akode")?);
command
.env("AKODE_HOME", home.path())
.env_remove(akode_exec_server::AKODE_EXEC_SERVER_EXIT_ON_STDIN_CLOSE_ENV_VAR)
.env("AKODE_API_KEY", "general-api-key")
.env("OPENAI_API_KEY", "general-openai-key")
.env("AKODE_ACCESS_TOKEN", "general-agent-identity")
.env(
"OPENAI_WORKLOAD_IDENTITY_CONTEXT",
"invalid-general-workload-identity",
)
.env("NO_PROXY", "127.0.0.1,localhost")
.env("no_proxy", "127.0.0.1,localhost")
.args([
"exec-server",
"--remote",
&registry.uri(),
"--environment-id",
ENVIRONMENT,
"--executor-credential-stdin",
])
.stdin(Stdio::piped())
.stderr(Stdio::piped())
.kill_on_drop(true);
let mut child = command.spawn()?;
let mut stdin = child
.stdin
.take()
.context("credential stdin was not piped")?;
send_json_line(&mut stdin, &serde_json::json!({
"version": 1, "environment_id": ENVIRONMENT, "token": CREDENTIAL,
"expires_at": std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_secs() + 120,
})).await?;
let (socket, _) = tokio::time::timeout(TIMEOUT, listener.accept())
.await
.context("executor did not reach rendezvous")??;
let environment_websocket = tokio::time::timeout(
TIMEOUT,
accept_hdr_async(socket, |request: &Request, response: Response| {
for name in ["authorization", "chatgpt-account-id"] {
assert!(
!request.headers().contains_key(name),
"registry authentication must not be sent in the WebSocket handshake"
);
}
Ok(response)
}),
)
.await
.context("executor WebSocket handshake did not complete")??;
let executor_public_key = registered_parent_lifetime_executor_public_key(&registry).await?;
let args = NoiseRendezvousConnectArgs {
bundle: NoiseRendezvousConnectBundle {
websocket_url: format!("{rendezvous}/relay?role=harness"),
environment_id: ENVIRONMENT.to_string(),
executor_registration_id: "registration-scoped".to_string(),
executor_public_key,
harness_key_authorization: "synthetic-harness-authorization".to_string(),
},
harness_identity: NoiseChannelIdentity::generate()?,
client_name: "scoped-credential-test".to_string(),
connect_timeout: TIMEOUT,
initialize_timeout: TIMEOUT,
resume_session_id: None,
http_client_factory: HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
};
let connect =
tokio::spawn(async move { ExecServerClient::connect_noise_rendezvous(args).await });
let harness_websocket = accept_parent_lifetime_websocket(&listener, TIMEOUT).await?;
let relay = tokio::spawn(proxy_parent_lifetime_relay(
environment_websocket,
harness_websocket,
));
let client = tokio::time::timeout(TIMEOUT, connect)
.await
.context("harness timed out")???;
let before_rotation = client.environment_info().await?;
send_json_line(&mut stdin, &serde_json::json!({
"version": 1, "environment_id": ENVIRONMENT, "token": ROTATED_CREDENTIAL,
"expires_at": std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_secs() + 120,
})).await?;
assert_eq!(
&client.force_environment_info().await?,
before_rotation.as_ref()
);
let requests = registry
.received_requests()
.await
.context("registry requests")?;
assert_eq!(
requests
.iter()
.map(|request| request.url.path())
.collect::<Vec<_>>(),
[
format!("/cloud/environment/{ENVIRONMENT}/register"),
format!("/cloud/environment/{ENVIRONMENT}/register"),
format!("/cloud/environment/{ENVIRONMENT}/validate"),
]
);
for request in requests {
assert_eq!(
request.headers["authorization"],
format!("Bearer {CREDENTIAL}")
);
assert_eq!(request.headers.get_all("authorization").iter().count(), 1);
for name in [
"chatgpt-account-id",
"x-openai-biscuit",
"biscuit",
"x-openai-access-token",
] {
assert!(
!request.headers.contains_key(name),
"unexpected registry credential header {name}"
);
}
}
assert_eq!(registration_rx.try_recv()?, CREDENTIAL);
drop(client);
relay.abort();
let _ = relay.await;
// Reject reconnects to trigger re-registration while the parent update is processed.
tokio::time::timeout(TIMEOUT, async {
loop {
let (socket, _) = listener.accept().await?;
let rejected = http::Response::builder()
.status(http::StatusCode::UNAUTHORIZED)
.body(Some("expired registration".to_string()))?;
let result = accept_hdr_async(socket, |_: &Request, _: Response| Err(rejected)).await;
assert!(result.is_err());
let credential = registration_rx
.recv()
.await
.context("missing re-registration")?;
if credential == ROTATED_CREDENTIAL {
break Ok::<(), anyhow::Error>(());
}
assert_eq!(credential, CREDENTIAL);
}
})
.await
.context("executor did not re-register with the rotated parent credential")??;
drop(stdin);
let output = tokio::time::timeout(TIMEOUT, child.wait_with_output())
.await
.context("stdin EOF did not stop executor")??;
let stderr = String::from_utf8_lossy(&output.stderr);
anyhow::ensure!(output.status.success(), "scoped executor failed: {stderr}");
assert!(!stderr.contains(CREDENTIAL));
assert!(!stderr.contains(ROTATED_CREDENTIAL));
assert!(
collector
.received_requests()
.await
.context("telemetry requests")?
.is_empty()
);
Ok(())
}
#[tokio::test]
async fn remote_exec_server_scoped_credentials_never_fall_back_for_another_environment()
-> Result<()> {
let registry = MockServer::start().await;
let home = TempDir::new()?;
std::fs::write(
home.path().join("auth.json"),
r#"{"OPENAI_API_KEY":"general-file-token"}"#,
)?;
let mut command = tokio::process::Command::new(akode_utils_cargo_bin::cargo_bin("akode")?);
let mut child = command
.env("AKODE_HOME", home.path())
.env("AKODE_API_KEY", "general-api-key")
.env("AKODE_ACCESS_TOKEN", "general-agent-identity")
.env("NO_PROXY", "127.0.0.1,localhost")
.env("no_proxy", "127.0.0.1,localhost")
.args([
"exec-server",
"--remote",
&registry.uri(),
"--environment-id",
"configured-environment",
"--executor-credential-stdin",
])
.stdin(Stdio::piped())
.stderr(Stdio::piped())
.kill_on_drop(true)
.spawn()?;
let mut stdin = child
.stdin
.take()
.context("credential stdin was not piped")?;
send_json_line(&mut stdin, &serde_json::json!({
"version": 1, "environment_id": "another-environment", "token": "never-print-this-scoped-token",
"expires_at": std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_secs() + 120,
})).await?;
let output = tokio::time::timeout(Duration::from_secs(30), child.wait_with_output())
.await
.context("invalid scoped frame did not stop executor")??;
assert!(!output.status.success());
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(stderr.contains("different environment"));
assert!(!stderr.contains("never-print-this-scoped-token"));
assert!(
registry
.received_requests()
.await
.context("registry requests")?
.is_empty()
);
drop(stdin);
Ok(())
}
async fn accept_parent_lifetime_websocket(
listener: &TcpListener,
timeout: Duration,
) -> Result<WebSocketStream<tokio::net::TcpStream>> {
let (socket, _) = tokio::time::timeout(timeout, listener.accept())
.await
.context("remote executor or harness did not reach rendezvous")??;
tokio::time::timeout(timeout, accept_async(socket))
.await
.context("fake rendezvous did not complete websocket handshake")?
.map_err(Into::into)
}
async fn registered_parent_lifetime_executor_public_key(
registry: &MockServer,
) -> Result<NoiseChannelPublicKey> {
let requests = registry
.received_requests()
.await
.context("failed to read remote registry requests")?;
let request = requests
.iter()
.find(|request| request.url.path().ends_with("/register"))
.context("remote executor did not register before connecting")?;
let body: serde_json::Value = serde_json::from_slice(&request.body)?;
serde_json::from_value(body["executor_public_key"].clone()).map_err(Into::into)
}
async fn proxy_parent_lifetime_relay(
mut environment: WebSocketStream<tokio::net::TcpStream>,
mut harness: WebSocketStream<tokio::net::TcpStream>,
) -> Result<()> {
loop {
tokio::select! {
message = environment.next() => {
let Some(message) = message else {
break;
};
harness.send(message?).await?;
}
message = harness.next() => {
let Some(message) = message else {
break;
};
environment.send(message?).await?;
}
}
}
Ok(())
}
async fn send_json_line(
stdin: &mut (impl tokio::io::AsyncWrite + Unpin),
message: &serde_json::Value,
) -> Result<()> {
let mut encoded = serde_json::to_vec(message)?;
encoded.push(b'\n');
stdin.write_all(&encoded).await?;
stdin.flush().await?;
Ok(())
}
#[cfg(unix)]
#[test]
fn local_exec_server_exits_successfully_on_sigterm() -> Result<()> {
let codex_home = TempDir::new()?;
let mut child = std::process::Command::new(akode_utils_cargo_bin::cargo_bin("akode")?)
.env("AKODE_HOME", codex_home.path())
.args(["exec-server", "--listen", "ws://127.0.0.1:0"])
.stdout(Stdio::piped())
.spawn()?;
let mut listen_url = String::new();
StdBufReader::new(child.stdout.take().expect("child stdout")).read_line(&mut listen_url)?;
assert!(listen_url.starts_with("ws://127.0.0.1:"), "{listen_url}");
let listen_addr = listen_url
.trim()
.strip_prefix("ws://")
.expect("listen URL should use ws://")
.parse()?;
let deadline = Instant::now() + Duration::from_secs(5);
let mut ready = false;
while let Some(remaining) = deadline.checked_duration_since(Instant::now()) {
if let Ok(mut stream) =
TcpStream::connect_timeout(&listen_addr, remaining.min(Duration::from_millis(100)))
{
let _ = stream.set_read_timeout(Some(Duration::from_secs(1)));
let request =
format!("GET /readyz HTTP/1.1\r\nHost: {listen_addr}\r\nConnection: close\r\n\r\n");
let mut response = String::new();
if stream.write_all(request.as_bytes()).is_ok()
&& stream.read_to_string(&mut response).is_ok()
&& response.starts_with("HTTP/1.1 200")
{
ready = true;
break;
}
}
thread::sleep(Duration::from_millis(10));
}
assert!(ready, "exec-server did not become ready at {listen_url}");
// SAFETY: `child.id()` is the live process spawned above.
let result = unsafe { libc::kill(child.id() as libc::pid_t, libc::SIGTERM) };
assert_eq!(result, 0);
let status = child.wait()?;
assert!(status.success(), "{status}");
Ok(())
}
async fn wait_for_response(
stdout: &mut (impl tokio::io::AsyncBufRead + Unpin),
expected_id: i64,
) -> Result<serde_json::Value> {
loop {
let mut line = String::new();
if stdout.read_line(&mut line).await? == 0 {
anyhow::bail!("exec-server stdout closed before response {expected_id}");
}
let message: serde_json::Value = serde_json::from_str(&line)?;
if message["id"].as_i64() == Some(expected_id) {
anyhow::ensure!(
message.get("error").is_none(),
"exec-server request {expected_id} failed: {message}"
);
return Ok(message);
}
}
}
/// API-key registration authenticates directly and never fetches account-managed
/// cloud configuration before registering.
#[tokio::test]
async fn remote_exec_server_api_key_registers_without_cloud_config() -> Result<()> {
const REGISTER: &str = "/cloud/environment/test/register";
const REGISTRATION_REACHED: &str = "registration reached";
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path(REGISTER))
.and(header("authorization", "Bearer test-api-key"))
.respond_with(ResponseTemplate::new(400).set_body_string(REGISTRATION_REACHED))
.mount(&server)
.await;
let home = TempDir::new()?;
std::fs::write(
home.path().join("config.toml"),
"cli_auth_credentials_store = \"file\"\n",
)?;
let output = tokio::time::timeout(
Duration::from_secs(30),
tokio::process::Command::new(akode_utils_cargo_bin::cargo_bin("akode")?)
.kill_on_drop(true)
.current_dir(home.path())
.env("AKODE_HOME", home.path())
.env("NO_PROXY", "127.0.0.1,localhost")
.env("no_proxy", "127.0.0.1,localhost")
.env_remove("OPENAI_API_KEY")
.env("AKODE_API_KEY", "test-api-key")
.args([
"exec-server",
"--remote",
&server.uri(),
"--environment-id",
"test",
])
.output(),
)
.await??;
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
!output.status.success() && stderr.contains(REGISTRATION_REACHED),
"{stderr}"
);
let requests = server
.received_requests()
.await
.context("mock request log")?;
let paths: Vec<_> = requests.iter().map(|request| request.url.path()).collect();
assert_eq!(paths, vec![REGISTER]);
Ok(())
}

View File

@@ -0,0 +1,155 @@
//! End-to-end checks that only executor startup can opt into PID inheritance.
use super::*;
use akode_exec_server::FileSystemSandboxContext;
use akode_protocol::models::PermissionProfile;
use akode_protocol::permissions::FileSystemAccessMode;
use akode_protocol::permissions::FileSystemPath;
use akode_protocol::permissions::FileSystemSandboxEntry;
use akode_protocol::permissions::FileSystemSandboxPolicy;
use akode_protocol::permissions::FileSystemSpecialPath;
use akode_protocol::permissions::NetworkSandboxPolicy;
use akode_utils_absolute_path::AbsolutePathBuf;
use pretty_assertions::assert_eq;
#[tokio::test]
async fn pid_inheritance_is_startup_only_for_process_and_filesystem_helpers() -> Result<()> {
let Some(bwrap) = akode_sandboxing::find_system_bwrap_in_path(
&PermissionProfile::read_only().file_system_sandbox_policy(),
&std::env::current_dir()?,
) else {
eprintln!("skipping PID namespace test: no system bubblewrap");
return Ok(());
};
let available = tokio::process::Command::new(&bwrap)
.args(["--unshare-user", "--ro-bind", "/", "/", "--", "/bin/true"])
.output()
.await?;
if !available.status.success() {
eprintln!(
"skipping PID namespace test: {}",
String::from_utf8_lossy(&available.stderr)
);
return Ok(());
}
tokio::time::timeout(Duration::from_secs(30), async {
let fixture = TempDir::new()?;
let wrapper = fixture.path().join("bwrap");
std::os::unix::fs::symlink(bwrap, fixture.path().join("real-bwrap"))?;
akode_utils_cargo_bin::write_executable(&wrapper, r#"#!/bin/sh
for arg in "$@"; do
[ "$arg" = "--" ] && break
if [ "$arg" = "--proc" ]; then
echo "bwrap: Can't mount proc on /newroot/proc: Operation not permitted" >&2
exit 1
fi
done
exec "${0%/*}/real-bwrap" "$@"
"#)?;
let path = format!("{}:{}", fixture.path().display(), std::env::var("PATH")?);
// System bubblewrap discovery intentionally excludes executables under the command cwd.
let workspace = TempDir::new()?;
let file = workspace.path().join("readable");
std::fs::write(&file, "ok")?;
let file_uri = url::Url::from_file_path(&file).unwrap();
let cwd = url::Url::from_directory_path(workspace.path()).unwrap();
let minimal_policy = FileSystemSandboxPolicy::restricted(vec![
FileSystemSandboxEntry::new(
FileSystemPath::Special { value: FileSystemSpecialPath::Minimal },
FileSystemAccessMode::Read,
),
FileSystemSandboxEntry::new(
AbsolutePathBuf::try_from(workspace.path())?.into(), FileSystemAccessMode::Read,
),
FileSystemSandboxEntry::new(
AbsolutePathBuf::from_absolute_path("/proc/version")?.into(), FileSystemAccessMode::Deny,
),
]);
let minimal_profile = PermissionProfile::from_runtime_permissions(
&minimal_policy, NetworkSandboxPolicy::Restricted,
);
for (inherit, profile) in [
(false, PermissionProfile::read_only()),
(true, PermissionProfile::read_only()),
(true, minimal_profile),
] {
let minimal = profile.file_system_sandbox_policy().include_platform_defaults();
let sandbox = FileSystemSandboxContext::from_permission_profile(
profile, cwd.as_str().parse()?,
);
let codex_home = TempDir::new()?;
// Neither a config key nor executor/request environment variables may opt in.
std::fs::write(codex_home.path().join("config.toml"),
"linux_sandbox_pid_namespace = 'inherit'\n")?;
let mut command = tokio::process::Command::new(akode_utils_cargo_bin::cargo_bin("akode")?);
command.args(["exec-server", "--listen", "stdio"])
.env("AKODE_HOME", codex_home.path())
.env("PATH", &path)
.env("AKODE_LINUX_SANDBOX_PID_NAMESPACE", "inherit")
.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped())
.kill_on_drop(true);
if inherit {
command.arg("--linux-sandbox-pid-namespace=inherit");
}
let mut child = command.spawn()?;
let mut stdin = child.stdin.take().context("executor stdin")?;
let mut stdout = BufReader::new(child.stdout.take().context("executor stdout")?);
send_json_line(&mut stdin, &serde_json::json!({
"id": 1, "method": "initialize",
"params": {"clientName": "pid-namespace-test", "resumeSessionId": null}
})).await?;
wait_for_response(&mut stdout, /*expected_id*/ 1).await?;
send_json_line(&mut stdin, &serde_json::json!({"method": "initialized", "params": {}})).await?;
send_json_line(&mut stdin, &serde_json::json!({
"id": 2, "method": "process/start", "params": {
"processId": "pid-test", "cwd": cwd, "sandbox": sandbox,
"argv": ["/bin/bash", "-lc", r#"
set -e
IFS=' ' read -r pid rest < /proc/self/stat
test "$$" = "$pid"
test "$(cat <(printf shell-ok))" = shell-ok
if [ "$MINIMAL" = true ]; then
! cat /proc/version
fi
"#],
"env": {"PATH": path, "MINIMAL": minimal.to_string(), "AKODE_LINUX_SANDBOX_PID_NAMESPACE": "inherit"},
"tty": false, "pipeStdin": false, "arg0": null
}
})).await?;
// Notifications may precede the process/start response, so consume both.
let mut started = false;
let mut exit_code = None;
while !started || exit_code.is_none() {
let mut line = String::new();
anyhow::ensure!(stdout.read_line(&mut line).await? > 0, "executor closed");
let message: serde_json::Value = serde_json::from_str(&line)?;
if message["id"] == 2 {
anyhow::ensure!(message.get("error").is_none(), "start failed: {message}");
started = true;
}
if message["method"] == "process/exited" {
exit_code = message["params"]["exitCode"].as_i64();
}
}
assert_eq!(exit_code, Some(if inherit { 0 } else { 1 }));
send_json_line(&mut stdin, &serde_json::json!({
"id": 3, "method": "fs/readFile", "params": {"path": file_uri, "sandbox": sandbox}
})).await?;
loop {
let mut line = String::new();
anyhow::ensure!(stdout.read_line(&mut line).await? > 0, "executor closed");
let message: serde_json::Value = serde_json::from_str(&line)?;
if message["id"] != 3 { continue; }
assert_eq!(message["result"], serde_json::json!({"dataBase64": "b2s="}));
break;
}
drop(stdin);
// Drain notifications while the executor shuts down.
let mut remaining = String::new();
stdout.read_to_string(&mut remaining).await?;
let output = child.wait_with_output().await?;
anyhow::ensure!(output.status.success(), "executor failed: {}", String::from_utf8_lossy(&output.stderr));
}
Ok(())
}).await?
}

View File

@@ -0,0 +1,366 @@
//! Exercises listener authentication through the standalone executor CLI and real WebSockets.
use anyhow::Context;
use anyhow::Result;
use futures::SinkExt;
use futures::StreamExt;
use pretty_assertions::assert_eq;
use serde_json::json;
use sha2::Digest;
use sha2::Sha256;
use std::process::Stdio;
use std::time::Duration;
use std::time::SystemTime;
use std::time::UNIX_EPOCH;
use tempfile::TempDir;
use tokio::io::AsyncBufReadExt;
use tokio::io::BufReader;
use tokio::process::Command;
use tokio_tungstenite::connect_async;
use tokio_tungstenite::tungstenite::Error as WebSocketError;
use tokio_tungstenite::tungstenite::Message;
use tokio_tungstenite::tungstenite::client::IntoClientRequest;
enum AuthMode {
TokenHash,
TokenFile,
SignedBearer,
}
#[tokio::test]
async fn exec_server_websocket_auth_gates_rpc_connections() -> Result<()> {
tokio::time::timeout(Duration::from_secs(/*secs*/ 60), async {
let codex = akode_utils_cargo_bin::cargo_bin("akode")?;
for mode in [
AuthMode::TokenHash,
AuthMode::TokenFile,
AuthMode::SignedBearer,
] {
let home = TempDir::new()?;
let secret = "0123456789abcdef0123456789abcdef";
let secret_file = home.path().join("secret");
std::fs::write(&secret_file, secret)?;
let mut command = Command::new(&codex);
command
.args(["exec-server", "--listen", "ws://127.0.0.1:0", "--ws-auth"])
.env("AKODE_HOME", home.path())
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::inherit())
.kill_on_drop(true);
let token = match mode {
AuthMode::TokenHash => {
command.args([
"capability-token",
"--ws-token-sha256",
&format!("{:x}", Sha256::digest(secret.as_bytes())),
]);
secret.to_string()
}
AuthMode::TokenFile => {
command
.args(["capability-token", "--ws-token-file"])
.arg(&secret_file);
secret.to_string()
}
AuthMode::SignedBearer => {
command
.args(["signed-bearer-token", "--ws-shared-secret-file"])
.arg(&secret_file)
.args([
"--ws-issuer",
"test-issuer",
"--ws-audience",
"test-executor",
]);
let now = SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs();
jsonwebtoken::encode(
&jsonwebtoken::Header::new(jsonwebtoken::Algorithm::HS256),
&json!({"exp": now + 300, "iss": "test-issuer", "aud": "test-executor"}),
&jsonwebtoken::EncodingKey::from_secret(secret.as_bytes()),
)?
}
};
let mut child = command.spawn()?;
let mut lines = BufReader::new(child.stdout.take().context("stdout")?).lines();
let url = loop {
let line = lines
.next_line()
.await?
.context("listener exited before startup")?;
if line.starts_with("ws://") {
break line;
}
};
// A missing or incorrect credential must fail before any RPC session opens.
let digest_as_bearer = format!("Bearer {:x}", Sha256::digest(secret.as_bytes()));
for authorization in [
None,
Some("Bearer incorrect"),
Some("Basic incorrect"),
Some(digest_as_bearer.as_str()),
] {
let mut request = url.as_str().into_client_request()?;
if let Some(authorization) = authorization {
request
.headers_mut()
.insert("authorization", authorization.parse()?);
}
let error = connect_async(request)
.await
.expect_err("reject unauthorized upgrade");
let WebSocketError::Http(response) = error else {
anyhow::bail!("expected HTTP rejection, got {error}");
};
assert_eq!(response.status(), http::StatusCode::UNAUTHORIZED);
}
// Authentication applies to every connection, including reconnects.
for _ in 0..2 {
let mut request = url.as_str().into_client_request()?;
request
.headers_mut()
.insert("authorization", format!("Bearer {token}").parse()?);
let (mut websocket, _) = connect_async(request).await?;
websocket
.send(Message::Text(
json!({
"id": 1,
"method": "initialize",
"params": {"clientName": "auth-test"}
})
.to_string()
.into(),
))
.await?;
let response = websocket.next().await.context("initialize response")??;
let response: serde_json::Value = serde_json::from_str(response.to_text()?)?;
assert_eq!(response["id"], json!(1));
assert!(response.get("error").is_none(), "{response}");
assert!(response["result"]["sessionId"].is_string(), "{response}");
websocket.close(/*msg*/ None).await?;
}
child.kill().await?;
}
Ok(())
})
.await?
}
#[test]
fn exec_server_websocket_auth_rejects_inapplicable_transports() -> Result<()> {
let home = TempDir::new()?;
let codex = akode_utils_cargo_bin::cargo_bin("akode")?;
for (transport, expected) in [
(vec!["--listen", "stdio"], "not stdio"),
(vec!["--listen", "stdio://"], "not stdio"),
(
vec![
"--remote",
"https://registry.example",
"--environment-id",
"test",
],
"cannot be used with --remote",
),
(
vec![
"forward",
"--connect",
"ws://127.0.0.1:1234",
"--remote",
"https://registry.example",
"--environment-id",
"test",
],
"cannot be used with --remote",
),
] {
assert_cmd::Command::new(&codex)
.env("AKODE_HOME", home.path())
.args([
"exec-server",
"--ws-auth",
"capability-token",
"--ws-token-sha256",
&"ab".repeat(32),
])
.args(transport)
.assert()
.failure()
.stderr(predicates::str::contains(expected));
}
Ok(())
}
#[test]
fn exec_server_websocket_auth_rejects_invalid_configuration() -> Result<()> {
let home = TempDir::new()?;
let codex = akode_utils_cargo_bin::cargo_bin("akode")?;
for (args, expected) in [
(vec!["--ws-token-sha256", "invalid"], "require `--ws-auth"),
(
vec![
"--ws-auth",
"capability-token",
"--ws-token-sha256",
"invalid",
],
"64-character hex",
),
(vec!["--ws-auth", "capability-token"], "is required"),
] {
assert_cmd::Command::new(&codex)
.env("AKODE_HOME", home.path())
.args(["exec-server"])
.args(args)
.assert()
.failure()
.stderr(predicates::str::contains(expected));
}
Ok(())
}
#[tokio::test]
async fn app_server_executor_auth_supports_tokens_and_legacy_configuration() -> Result<()> {
use app_test_support::TestAppServer;
use app_test_support::to_response;
use akode_app_server_protocol::EnvironmentInfoResponse;
use akode_app_server_protocol::RequestId;
#[derive(Debug, PartialEq)]
enum Source {
Rpc,
Toml,
}
tokio::time::timeout(Duration::from_secs(/*secs*/ 90), async {
let codex = akode_utils_cargo_bin::cargo_bin("akode")?;
for token in [None, Some("executor-capability-for-app-server")] {
let executor_home = TempDir::new()?;
let mut command = Command::new(&codex);
command.args(["exec-server", "--listen", "ws://127.0.0.1:0"]);
if let Some(token) = token {
command.args([
"--ws-auth",
"capability-token",
"--ws-token-sha256",
&format!("{:x}", Sha256::digest(token.as_bytes())),
]);
}
let mut executor = command
.env("AKODE_HOME", executor_home.path())
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::inherit())
.kill_on_drop(true)
.spawn()?;
let mut lines =
BufReader::new(executor.stdout.take().context("executor stdout")?).lines();
let url = loop {
let line = lines.next_line().await?.context("executor exited")?;
if line.starts_with("ws://") {
break line;
}
};
for source in [Source::Rpc, Source::Toml] {
let home = TempDir::new()?;
let builder = TestAppServer::builder()
.with_program(&codex)
.with_plugin_startup_tasks()
.with_args(&["-c", "features.plugins=false", "app-server"])
.with_codex_home(home.path())
.without_auto_env()
.with_env_overrides(&[
("AKODE_EXEC_SERVER_URL", None),
("AKODE_EXEC_SERVER_NOISE_REGISTRY_URL", None),
]);
match source {
Source::Toml => {
let mut config =
format!("[[environments]]\nid = \"remote\"\nurl = {url:?}\n");
if let Some(token) = token {
config.push_str(&format!("auth_bearer_token = {token:?}\n"));
}
std::fs::write(home.path().join("environments.toml"), config)?;
}
Source::Rpc => {}
}
let mut app = builder.build().await?;
app.initialize().await?;
if source == Source::Rpc {
for credential in ["private-token\r\nInjected: true", "private-token\n"] {
let id = app
.send_raw_request(
"environment/add",
Some(json!({
"environmentId": "invalid", "execServerUrl": url,
"authBearerToken": credential,
})),
)
.await?;
let error = app
.read_stream_until_error_message(RequestId::Integer(id))
.await?;
assert!(!format!("{error:?}").contains("private-token"));
}
// Omitted and null tokens preserve old-client requests. They succeed
// with an unauthenticated executor and fail when authentication is enabled.
let credentials = match token {
Some(token) => vec![
None,
Some(serde_json::Value::Null),
Some(json!("wrong-token")),
Some(json!(token)),
],
None => vec![None, Some(serde_json::Value::Null)],
};
for credential in credentials {
let mut params = json!({
"environmentId": "remote", "execServerUrl": url,
});
if let Some(credential) = &credential {
params["authBearerToken"] = credential.clone();
}
let id = app
.send_raw_request("environment/add", Some(params))
.await?;
app.read_stream_until_response_message(RequestId::Integer(id))
.await?;
let id = app
.send_raw_request(
"environment/info",
Some(json!({"environmentId": "remote"})),
)
.await?;
if token.is_some()
&& credential.as_ref().and_then(serde_json::Value::as_str) != token
{
app.read_stream_until_error_message(RequestId::Integer(id))
.await?;
} else {
app.read_stream_until_response_message(RequestId::Integer(id))
.await?;
}
}
}
let id = app
.send_raw_request("environment/info", Some(json!({"environmentId": "remote"})))
.await?;
let response = app
.read_stream_until_response_message(RequestId::Integer(id))
.await?;
let info: EnvironmentInfoResponse = to_response(response)?;
assert!(
!info.shell.name.is_empty(),
"{source:?} should reach the executor"
);
}
executor.kill().await?;
}
Ok::<_, anyhow::Error>(())
})
.await?
}

View File

@@ -0,0 +1,119 @@
use std::fs;
use assert_cmd::Command;
use pretty_assertions::assert_eq;
use serde_json::json;
use tempfile::TempDir;
#[test]
fn execpolicy_check_matches_expected_json() -> Result<(), Box<dyn std::error::Error>> {
let codex_home = TempDir::new()?;
let policy_path = codex_home.path().join("rules").join("policy.rules");
fs::create_dir_all(
policy_path
.parent()
.expect("policy path should have a parent"),
)?;
fs::write(
&policy_path,
r#"
prefix_rule(
pattern = ["git", "push"],
decision = "forbidden",
)
"#,
)?;
let output = Command::new(akode_utils_cargo_bin::cargo_bin("akode")?)
.env("AKODE_HOME", codex_home.path())
.args([
"execpolicy",
"check",
"--rules",
policy_path
.to_str()
.expect("policy path should be valid UTF-8"),
"git",
"push",
"origin",
"main",
])
.output()?;
assert!(output.status.success());
let result: serde_json::Value = serde_json::from_slice(&output.stdout)?;
assert_eq!(
result,
json!({
"decision": "forbidden",
"matchedRules": [
{
"prefixRuleMatch": {
"matchedPrefix": ["git", "push"],
"decision": "forbidden"
}
}
]
})
);
Ok(())
}
#[test]
fn execpolicy_check_includes_justification_when_present() -> Result<(), Box<dyn std::error::Error>>
{
let codex_home = TempDir::new()?;
let policy_path = codex_home.path().join("rules").join("policy.rules");
fs::create_dir_all(
policy_path
.parent()
.expect("policy path should have a parent"),
)?;
fs::write(
&policy_path,
r#"
prefix_rule(
pattern = ["git", "push"],
decision = "forbidden",
justification = "pushing is blocked in this repo",
)
"#,
)?;
let output = Command::new(akode_utils_cargo_bin::cargo_bin("akode")?)
.env("AKODE_HOME", codex_home.path())
.args([
"execpolicy",
"check",
"--rules",
policy_path
.to_str()
.expect("policy path should be valid UTF-8"),
"git",
"push",
"origin",
"main",
])
.output()?;
assert!(output.status.success());
let result: serde_json::Value = serde_json::from_slice(&output.stdout)?;
assert_eq!(
result,
json!({
"decision": "forbidden",
"matchedRules": [
{
"prefixRuleMatch": {
"matchedPrefix": ["git", "push"],
"decision": "forbidden",
"justification": "pushing is blocked in this repo"
}
}
]
})
);
Ok(())
}

View File

@@ -0,0 +1,326 @@
use std::path::Path;
use anyhow::Result;
use predicates::str::contains;
use pretty_assertions::assert_eq;
use tempfile::TempDir;
fn codex_command(codex_home: &Path) -> Result<assert_cmd::Command> {
let mut cmd = assert_cmd::Command::new(akode_utils_cargo_bin::cargo_bin("akode")?);
cmd.env("AKODE_HOME", codex_home);
Ok(cmd)
}
#[test]
fn strict_config_rejects_unknown_config_override() -> Result<()> {
for (config_override, ignored_path) in [
("foo=bar", "foo"),
("tui.bogus_key_xyz=1", "tui.bogus_key_xyz"),
] {
let codex_home = TempDir::new()?;
let mut cmd = codex_command(codex_home.path())?;
cmd.args(["--strict-config", "-c", config_override, "exec", "hello"])
.assert()
.failure()
.stderr(contains(format!(
"unknown configuration field `{ignored_path}`"
)));
}
Ok(())
}
#[test]
fn mcp_list_reports_invalid_keybinding_reason() -> Result<()> {
for bindings in ["'backslash'", "['backslash']"] {
let codex_home = TempDir::new()?;
std::fs::write(
codex_home.path().join("config.toml"),
format!("[tui.keymap.editor]\ninsert_newline = {bindings}\n"),
)?;
let output = codex_command(codex_home.path())?
.current_dir(codex_home.path())
.args(["mcp", "list"])
.assert()
.failure()
.get_output()
.stderr
.clone();
let output = normalize_config_location(&String::from_utf8(output)?);
insta::allow_duplicates! {
insta::assert_snapshot!(output);
}
}
Ok(())
}
#[test]
fn interactive_validates_config_before_requiring_terminal() -> Result<()> {
let cases: &[(&[&str], &str, &str, &str)] = &[
(&[], "config.toml", "model = [", "Error loading config.toml"),
(
&["--strict-config"],
"config.toml",
"unknown_key = true",
"unknown configuration field",
),
(
&["--strict-config"],
"config.toml",
"[tui]\nbogus_key_xyz = 1",
"unknown configuration field `tui.bogus_key_xyz`",
),
(
&["--strict-config", "-c", "foo=bar"],
"config.toml",
"",
"unknown configuration field",
),
(
&["--profile", "work"],
"work.config.toml",
"model = [",
"work.config.toml",
),
(
&["-c", "model_provider=\"missing\""],
"config.toml",
"",
"Model provider `missing` not found",
),
(&[], "config.toml", "", "stdin is not a terminal"),
];
for &(args, config_file, contents, expected_error) in cases {
let codex_home = TempDir::new()?;
std::fs::write(codex_home.path().join(config_file), contents)?;
let mut cmd = codex_command(codex_home.path())?;
cmd.env("TERM", "xterm-256color")
.current_dir(codex_home.path())
.args(args)
.assert()
.failure()
.stderr(contains(expected_error));
}
Ok(())
}
#[test]
fn interactive_remote_default_preserves_remote_working_directory_before_requiring_terminal()
-> Result<()> {
let codex_home = TempDir::new()?;
std::fs::write(codex_home.path().join("config.toml"), "")?;
std::fs::write(
codex_home.path().join("environments.toml"),
r#"default = "remote"
include_local = false
[[environments]]
id = "remote"
url = "ws://127.0.0.1:4512"
"#,
)?;
let remote_only_cwd = codex_home.path().join("remote-only-working-directory");
let mut cmd = codex_command(codex_home.path())?;
cmd.env("TERM", "xterm-256color")
.current_dir(codex_home.path())
.arg("--cd")
.arg(remote_only_cwd)
.assert()
.failure()
.stderr(contains("stdin is not a terminal"));
Ok(())
}
#[tokio::test]
async fn features_enable_writes_feature_flag_to_config() -> Result<()> {
let codex_home = TempDir::new()?;
for feature in ["unified_exec", "shell_tool"] {
let mut cmd = codex_command(codex_home.path())?;
cmd.args(["features", "enable", feature])
.assert()
.success()
.stdout(contains(format!(
"Enabled feature `{feature}` in config.toml."
)));
let config = std::fs::read_to_string(codex_home.path().join("config.toml"))?;
assert!(config.contains("[features]"));
assert!(config.contains(&format!("{feature} = true")));
}
Ok(())
}
#[tokio::test]
async fn features_disable_writes_feature_flag_to_config() -> Result<()> {
let codex_home = TempDir::new()?;
let mut cmd = codex_command(codex_home.path())?;
cmd.args(["features", "disable", "shell_tool"])
.assert()
.success()
.stdout(contains("Disabled feature `shell_tool` in config.toml."));
let config = std::fs::read_to_string(codex_home.path().join("config.toml"))?;
assert!(config.contains("[features]"));
assert!(config.contains("shell_tool = false"));
Ok(())
}
#[tokio::test]
async fn features_enable_under_development_feature_prints_warning() -> Result<()> {
let codex_home = TempDir::new()?;
let mut cmd = codex_command(codex_home.path())?;
cmd.args(["features", "enable", "runtime_metrics"])
.assert()
.success()
.stderr(contains(
"Under-development features enabled: runtime_metrics.",
));
Ok(())
}
#[tokio::test]
async fn features_list_is_sorted_alphabetically_by_feature_name() -> Result<()> {
let codex_home = TempDir::new()?;
let mut cmd = codex_command(codex_home.path())?;
let output = cmd
.args(["features", "list"])
.assert()
.success()
.get_output()
.stdout
.clone();
let stdout = String::from_utf8(output)?;
let actual_names = stdout
.lines()
.map(|line| {
line.split_once(" ")
.map(|(name, _)| name.trim_end().to_string())
.expect("feature list output should contain aligned columns")
})
.collect::<Vec<_>>();
let mut expected_names = actual_names.clone();
expected_names.sort();
assert_eq!(actual_names, expected_names);
Ok(())
}
#[test]
fn remote_start_rejects_add_dir_before_connecting() -> Result<()> {
let home = TempDir::new()?;
let output = codex_command(home.path())?
.env("TERM", "xterm-256color")
.args(["--remote", "ws://127.0.0.1:1", "--add-dir", "remote-extra"])
.assert()
.failure()
.get_output()
.stderr
.clone();
insta::assert_snapshot!(String::from_utf8(output)?);
Ok(())
}
#[test]
fn remote_start_rejects_writable_root_overrides_before_connecting() -> Result<()> {
for config_override in [
"sandbox_workspace_write.writable_roots=[\"./extra\"]",
"sandbox_workspace_write={writable_roots=[\"./extra\"],network_access=true}",
] {
let home = TempDir::new()?;
let output = codex_command(home.path())?
.env("TERM", "xterm-256color")
.args(["--remote", "ws://127.0.0.1:1", "-c", config_override])
.assert()
.failure()
.get_output()
.stderr
.clone();
let output = String::from_utf8(output)?;
insta::allow_duplicates! {
insta::assert_snapshot!(output, @"Error: sandbox_workspace_write.writable_roots overrides are not supported with --remote. Configure additional workspace roots on the server.");
}
}
Ok(())
}
#[test]
fn remote_start_allows_network_access_overrides_before_requiring_terminal() -> Result<()> {
for config_override in [
"sandbox_workspace_write.network_access=true",
"sandbox_workspace_write={network_access=true}",
] {
let home = TempDir::new()?;
codex_command(home.path())?
.env("TERM", "xterm-256color")
.args(["--remote", "ws://127.0.0.1:1", "-c", config_override])
.assert()
.failure()
.stderr(contains("stdin is not a terminal"));
}
Ok(())
}
#[test]
fn no_daemon_rejects_queue_and_explicit_remote_targets() -> Result<()> {
for args in [
"--no-daemon queue --thread example --message hello",
"--no-daemon --remote ws://localhost:9999 agents",
"--no-daemon --remote ws://localhost:9999",
"--no-daemon --remote ws://localhost:9999 archive example",
"--no-daemon --remote ws://localhost:9999 unarchive example",
"--no-daemon --remote ws://localhost:9999 delete --force 123e4567-e89b-12d3-a456-426614174000",
"--no-daemon --remote ws://localhost:9999 queue --thread example --message hello",
"--remote ws://localhost:9999 resume --no-daemon --last",
"--no-daemon fork --remote ws://localhost:9999 session-name",
] {
let args = args.split_whitespace().collect::<Vec<_>>();
let home = TempDir::new()?;
let expected = if args.contains(&"queue") && !args.contains(&"--remote") {
"--no-daemon cannot be used with codex queue."
} else {
"--no-daemon cannot be used with --remote."
};
codex_command(home.path())?
.args(args)
.assert()
.failure()
.stderr(contains(expected));
assert!(!home.path().join("app-server-daemon").exists());
}
Ok(())
}
/// Replaces `<temp home>/config.toml:<line>:<column>` with a stable placeholder.
fn normalize_config_location(output: &str) -> String {
output
.lines()
.map(|line| match line.find("/config.toml:") {
Some(index) => {
let start = line[..index].rfind(' ').map_or(0, |space| space + 1);
let rest = &line[index + "/config.toml:".len()..];
let after_location = rest.splitn(3, ':').nth(2).unwrap_or_default();
format!(
"{}[AKODE_HOME]/config.toml:<line>:<column>:{after_location}",
&line[..start]
)
}
None => line.to_string(),
})
.collect::<Vec<_>>()
.join("\n")
}

233
akode-rs/cli/tests/login.rs Normal file
View File

@@ -0,0 +1,233 @@
use std::path::Path;
use anyhow::Result;
use predicates::str::contains;
use pretty_assertions::assert_eq;
use serde_json::Value;
use serde_json::json;
use tempfile::TempDir;
fn codex_command(codex_home: &Path) -> Result<assert_cmd::Command> {
let mut cmd = assert_cmd::Command::new(akode_utils_cargo_bin::cargo_bin("akode")?);
cmd.env("AKODE_HOME", codex_home);
Ok(cmd)
}
fn write_file_auth_config(codex_home: &Path) -> Result<()> {
std::fs::write(
codex_home.join("config.toml"),
"cli_auth_credentials_store = \"file\"\n",
)?;
Ok(())
}
fn read_auth_json(codex_home: &Path) -> Result<Value> {
let auth_json = std::fs::read_to_string(codex_home.join("auth.json"))?;
Ok(serde_json::from_str(&auth_json)?)
}
#[test]
fn login_with_api_key_reads_stdin_and_writes_auth_json() -> Result<()> {
let codex_home = TempDir::new()?;
write_file_auth_config(codex_home.path())?;
let mut cmd = codex_command(codex_home.path())?;
let login = cmd
.args([
"-c",
"forced_login_method=\"api\"",
"login",
"--with-api-key",
])
.write_stdin("sk-test\n")
.assert()
.success();
insta::assert_snapshot!(String::from_utf8_lossy(&login.get_output().stderr), @r"
Reading API key from stdin...
API key saved. Authentication is checked when you send a request.
");
let auth = read_auth_json(codex_home.path())?;
assert_eq!(auth["OPENAI_API_KEY"], "sk-test");
assert!(auth.get("tokens").is_none());
assert!(auth.get("agent_identity").is_none());
let status = codex_command(codex_home.path())?
.args(["login", "status"])
.assert()
.success();
insta::assert_snapshot!(String::from_utf8_lossy(&status.get_output().stderr), @r"
API key configured - ***
Authentication is checked when you send a request.
");
codex_command(codex_home.path())?
.args(["-c", "forced_login_method=\"api\"", "login"])
.assert()
.failure()
.stderr(contains("Only API key login is supported"));
assert_eq!(read_auth_json(codex_home.path())?, auth);
for removed_flag in ["--device-auth", "--with-access-token"] {
codex_command(codex_home.path())?
.args(["login", removed_flag])
.write_stdin("token\n")
.assert()
.failure()
.stderr(contains("unexpected argument"));
assert_eq!(read_auth_json(codex_home.path())?, auth);
}
Ok(())
}
#[test]
fn api_key_auth_commands_work_when_log_dir_is_unavailable() -> Result<()> {
let codex_home = TempDir::new()?;
let log_dir = codex_home.path().join("unavailable-logs");
std::fs::write(&log_dir, "not a directory")?;
std::fs::write(
codex_home.path().join("config.toml"),
format!("cli_auth_credentials_store = \"file\"\nlog_dir = {log_dir:?}\n"),
)?;
codex_command(codex_home.path())?
.args(["login", "--with-api-key"])
.write_stdin("sk-test\n")
.assert()
.success()
.stderr(contains("Warning: failed to create login log directory"));
assert_eq!(
read_auth_json(codex_home.path())?["OPENAI_API_KEY"],
"sk-test"
);
codex_command(codex_home.path())?
.args(["login", "status"])
.assert()
.success()
.stderr(contains("API key"));
codex_command(codex_home.path())?
.arg("logout")
.assert()
.success()
.stderr(contains("Successfully logged out"));
assert!(!codex_home.path().join("auth.json").exists());
Ok(())
}
#[test]
fn login_status_reports_auth_storage_errors() -> Result<()> {
let codex_home = TempDir::new()?;
write_file_auth_config(codex_home.path())?;
std::fs::write(codex_home.path().join("auth.json"), "{invalid json")?;
codex_command(codex_home.path())?
.args(["login", "status"])
.assert()
.failure()
.stderr(contains("Error checking login status:"));
Ok(())
}
#[test]
fn legacy_chatgpt_auth_is_reported_as_not_logged_in_and_logout_removes_it() -> Result<()> {
let codex_home = TempDir::new()?;
write_file_auth_config(codex_home.path())?;
std::fs::write(
codex_home.path().join("auth.json"),
serde_json::to_vec(&json!({
"auth_mode": "chatgpt",
"OPENAI_API_KEY": null,
"tokens": {
"id_token": "eyJhbGciOiJub25lIn0.e30.c2ln",
"access_token": "old-access",
"refresh_token": "old-refresh",
},
}))?,
)?;
codex_command(codex_home.path())?
.env_remove("AKODE_API_KEY")
.args(["login", "status"])
.assert()
.failure()
.stderr(contains("Not logged in"));
codex_command(codex_home.path())?
.arg("logout")
.assert()
.success()
.stderr(contains("Successfully logged out"));
assert!(!codex_home.path().join("auth.json").exists());
Ok(())
}
#[test]
fn provider_api_key_login_uses_private_file_store_and_never_prints_the_key() -> Result<()> {
let codex_home = TempDir::new()?;
std::fs::write(
codex_home.path().join("config.toml"),
"provider_api_key_store = \"file\"\n\
model_provider = \"imeai\"\n\
[model_providers.imeai]\n\
name = \"imeAI\"\n\
base_url = \"http://127.0.0.1:9/v1\"\n\
api_key = \"keyring\"\n",
)?;
let secret = "sk-provider-secret-0123456789";
let login = codex_command(codex_home.path())?
.args(["login", "--provider", "imeai", "--with-api-key"])
.write_stdin(format!("{secret}\n"))
.assert()
.success();
let stderr = String::from_utf8_lossy(&login.get_output().stderr).to_string();
assert!(
stderr.contains("API key for `imeai` saved in file"),
"{stderr}"
);
assert!(!stderr.contains(secret), "{stderr}");
let path = codex_home.path().join("provider_api_keys.json");
let stored: Value = serde_json::from_str(&std::fs::read_to_string(&path)?)?;
assert_eq!(stored, json!({ "imeai": secret }));
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
assert_eq!(
std::fs::metadata(&path)?.permissions().mode() & 0o777,
0o600
);
}
// The shared stored key is untouched.
assert!(!codex_home.path().join("auth.json").exists());
let status = codex_command(codex_home.path())?
.args(["login", "status"])
.assert()
.success();
let stderr = String::from_utf8_lossy(&status.get_output().stderr).to_string();
assert!(
stderr.contains("Provider `imeai`: API key stored in file"),
"{stderr}"
);
assert!(!stderr.contains(secret), "{stderr}");
codex_command(codex_home.path())?
.args(["logout", "--provider", "imeai"])
.assert()
.success()
.stderr(contains("Removed the stored API key for `imeai`"));
assert!(!path.exists());
codex_command(codex_home.path())?
.args(["login", "status"])
.assert()
.failure()
.stderr(contains(
"Provider `imeai`: no API key stored (akode login --provider imeai --with-api-key)",
));
Ok(())
}

View File

@@ -0,0 +1,253 @@
use anyhow::Result;
use akode_config::CONFIG_TOML_FILE;
use akode_core_plugins::installed_marketplaces::marketplace_install_root;
use akode_utils_absolute_path::AbsolutePathBuf;
use predicates::str::contains;
use pretty_assertions::assert_eq;
use serde_json::json;
use std::path::Path;
use tempfile::TempDir;
fn codex_command(codex_home: &Path) -> Result<assert_cmd::Command> {
let mut cmd = assert_cmd::Command::new(akode_utils_cargo_bin::cargo_bin("akode")?);
cmd.env("AKODE_HOME", codex_home);
Ok(cmd)
}
fn write_marketplace_source(source: &Path, marker: &str) -> Result<()> {
std::fs::create_dir_all(source.join(".agents/plugins"))?;
std::fs::create_dir_all(source.join("plugins/sample/.codex-plugin"))?;
std::fs::write(
source.join(".agents/plugins/marketplace.json"),
r#"{
"name": "debug",
"plugins": [
{
"name": "sample",
"source": {
"source": "local",
"path": "./plugins/sample"
}
}
]
}"#,
)?;
std::fs::write(
source.join("plugins/sample/.codex-plugin/plugin.json"),
r#"{"name":"sample"}"#,
)?;
std::fs::write(source.join("plugins/sample/marker.txt"), marker)?;
Ok(())
}
#[tokio::test]
async fn marketplace_add_git_source_cleans_staging_after_failures() -> Result<()> {
let codex_home = TempDir::new()?;
let source = TempDir::new()?;
write_marketplace_source(source.path(), "git source")?;
for args in [
vec!["init", "--quiet"],
vec!["add", "."],
vec![
"-c",
"user.name=Codex Tests",
"-c",
"user.email=codex@example.com",
"-c",
"commit.gpgsign=false",
"commit",
"-m",
"marketplace",
],
] {
let output = std::process::Command::new("git")
.current_dir(source.path())
.args(args)
.output()?;
anyhow::ensure!(
output.status.success(),
"git fixture failed: {}",
String::from_utf8_lossy(&output.stderr)
);
}
// Exercise real Git clones without using the network or changing the process environment.
let source_url = "https://example.com/marketplace.git";
let rewrite_key = format!("url.{}.insteadOf", source.path().display());
let install_root = marketplace_install_root(codex_home.path());
let staging_root = install_root.join(".staging");
let abandoned = staging_root.join(format!("marketplace-{}-abandoned", std::env::consts::OS));
std::fs::create_dir_all(abandoned.join("checkout"))?;
std::fs::write(abandoned.join(".lock"), "")?;
std::fs::write(abandoned.join("checkout/payload"), "abandoned clone")?;
for (args, error) in [
(["--ref", "missing-ref"], "git checkout missing-ref failed"),
(
["--sparse", "plugins/sample"],
"marketplace root does not contain a supported manifest",
),
] {
for _ in 0..2 {
codex_command(codex_home.path())?
.current_dir(codex_home.path())
.env("GIT_CONFIG_COUNT", "1")
.env("GIT_CONFIG_KEY_0", &rewrite_key)
.env("GIT_CONFIG_VALUE_0", source_url)
.args(["plugin", "marketplace", "add", source_url])
.args(args)
.assert()
.failure()
.stderr(contains(error));
assert_eq!(std::fs::read_dir(&staging_root)?.count(), 0);
assert!(!install_root.join("debug").exists());
assert!(!codex_home.path().join(CONFIG_TOML_FILE).exists());
}
}
codex_command(codex_home.path())?
.current_dir(codex_home.path())
.env("GIT_CONFIG_COUNT", "1")
.env("GIT_CONFIG_KEY_0", &rewrite_key)
.env("GIT_CONFIG_VALUE_0", source_url)
.args(["plugin", "marketplace", "add", source_url])
.assert()
.success();
let config = std::fs::read_to_string(codex_home.path().join(CONFIG_TOML_FILE))?;
// A different ref bypasses the already-added shortcut and conflicts after cloning.
codex_command(codex_home.path())?
.current_dir(codex_home.path())
.env("GIT_CONFIG_COUNT", "1")
.env("GIT_CONFIG_KEY_0", &rewrite_key)
.env("GIT_CONFIG_VALUE_0", source_url)
.args(["plugin", "marketplace", "add", source_url, "--ref", "HEAD"])
.assert()
.failure()
.stderr(contains("already added from a different source"));
assert_eq!(std::fs::read_dir(&staging_root)?.count(), 0);
assert_eq!(
std::fs::read_to_string(install_root.join("debug/plugins/sample/marker.txt"))?,
"git source"
);
assert_eq!(
std::fs::read_to_string(codex_home.path().join(CONFIG_TOML_FILE))?,
config
);
Ok(())
}
#[tokio::test]
async fn marketplace_add_local_directory_source() -> Result<()> {
let codex_home = TempDir::new()?;
let source = TempDir::new()?;
write_marketplace_source(source.path(), "local ref")?;
let source_parent = source.path().parent().unwrap();
let source_arg = format!("./{}", source.path().file_name().unwrap().to_string_lossy());
codex_command(codex_home.path())?
.current_dir(source_parent)
.args(["plugin", "marketplace", "add", source_arg.as_str()])
.assert()
.success();
let installed_root = marketplace_install_root(codex_home.path()).join("debug");
assert!(!installed_root.exists());
let config = std::fs::read_to_string(codex_home.path().join(CONFIG_TOML_FILE))?;
let config: toml::Value = toml::from_str(&config)?;
let expected_source = source.path().canonicalize()?.display().to_string();
assert_eq!(
config["marketplaces"]["debug"]["source_type"].as_str(),
Some("local")
);
assert_eq!(
config["marketplaces"]["debug"]["source"].as_str(),
Some(expected_source.as_str())
);
Ok(())
}
#[tokio::test]
async fn marketplace_add_json_prints_add_outcome() -> Result<()> {
let codex_home = TempDir::new()?;
let source = TempDir::new()?;
write_marketplace_source(source.path(), "local ref")?;
let source_parent = source.path().parent().unwrap();
let source_arg = format!("./{}", source.path().file_name().unwrap().to_string_lossy());
let assert = codex_command(codex_home.path())?
.current_dir(source_parent)
.args([
"plugin",
"marketplace",
"add",
source_arg.as_str(),
"--json",
])
.assert()
.success();
let stdout = assert.get_output().stdout.as_slice();
let actual: serde_json::Value = serde_json::from_slice(stdout)?;
let expected_installed_root = AbsolutePathBuf::try_from(source.path().canonicalize()?)?;
assert_eq!(
actual,
json!({
"marketplaceName": "debug",
"installedRoot": expected_installed_root.as_path().display().to_string(),
"alreadyAdded": false,
})
);
Ok(())
}
#[tokio::test]
async fn marketplace_add_rejects_local_manifest_file_source() -> Result<()> {
let codex_home = TempDir::new()?;
let source = TempDir::new()?;
write_marketplace_source(source.path(), "local ref")?;
let manifest_path = source.path().join(".agents/plugins/marketplace.json");
codex_command(codex_home.path())?
.args([
"plugin",
"marketplace",
"add",
manifest_path.to_str().unwrap(),
])
.assert()
.failure()
.stderr(contains(
"local marketplace source must be a directory, not a file",
));
Ok(())
}
#[tokio::test]
async fn marketplace_add_rejects_sparse_for_local_directory_source() -> Result<()> {
let codex_home = TempDir::new()?;
let source = TempDir::new()?;
write_marketplace_source(source.path(), "local ref")?;
codex_command(codex_home.path())?
.args([
"plugin",
"marketplace",
"add",
"--sparse",
".agents",
source.path().to_str().unwrap(),
])
.assert()
.failure()
.stderr(contains(
"--sparse is only supported for git marketplace sources",
));
Ok(())
}

View File

@@ -0,0 +1,127 @@
use anyhow::Result;
use akode_config::MarketplaceConfigUpdate;
use akode_config::record_user_marketplace;
use akode_core_plugins::installed_marketplaces::marketplace_install_root;
use akode_utils_absolute_path::canonicalize_existing_preserving_symlinks;
use predicates::str::contains;
use pretty_assertions::assert_eq;
use serde_json::json;
use std::path::Path;
use tempfile::TempDir;
fn codex_command(codex_home: &Path) -> Result<assert_cmd::Command> {
let mut cmd = assert_cmd::Command::new(akode_utils_cargo_bin::cargo_bin("akode")?);
cmd.env("AKODE_HOME", codex_home);
Ok(cmd)
}
fn configured_marketplace_update() -> MarketplaceConfigUpdate<'static> {
MarketplaceConfigUpdate {
source_type: "git",
source: "https://github.com/owner/repo.git",
ref_name: Some("main"),
sparse_paths: &[],
}
}
fn write_installed_marketplace(codex_home: &Path, marketplace_name: &str) -> Result<()> {
let root = marketplace_install_root(codex_home).join(marketplace_name);
std::fs::create_dir_all(root.join(".agents/plugins"))?;
std::fs::write(root.join(".agents/plugins/marketplace.json"), "{}")?;
std::fs::write(root.join("marker.txt"), "installed")?;
Ok(())
}
#[tokio::test]
async fn marketplace_remove_deletes_config_and_installed_root() -> Result<()> {
let codex_home = TempDir::new()?;
record_user_marketplace(codex_home.path(), "debug", &configured_marketplace_update())?;
write_installed_marketplace(codex_home.path(), "debug")?;
codex_command(codex_home.path())?
.args(["plugin", "marketplace", "remove", "debug"])
.assert()
.success()
.stdout(contains("Removed marketplace `debug`."));
let config_path = codex_home.path().join("config.toml");
let config = std::fs::read_to_string(config_path)?;
assert!(!config.contains("[marketplaces.debug]"));
assert!(
!marketplace_install_root(codex_home.path())
.join("debug")
.exists()
);
Ok(())
}
#[tokio::test]
async fn marketplace_remove_json_prints_remove_outcome() -> Result<()> {
let codex_home = TempDir::new()?;
record_user_marketplace(codex_home.path(), "debug", &configured_marketplace_update())?;
write_installed_marketplace(codex_home.path(), "debug")?;
let installed_root = marketplace_install_root(codex_home.path()).join("debug");
let normalized_installed_root = canonicalize_existing_preserving_symlinks(&installed_root)?;
let assert = codex_command(codex_home.path())?
.args(["plugin", "marketplace", "remove", "debug", "--json"])
.assert()
.success();
let stdout = assert.get_output().stdout.as_slice();
let actual: serde_json::Value = serde_json::from_slice(stdout)?;
assert_eq!(
actual,
json!({
"marketplaceName": "debug",
"installedRoot": normalized_installed_root.display().to_string(),
})
);
Ok(())
}
#[tokio::test]
async fn marketplace_remove_rejects_unknown_marketplace() -> Result<()> {
let codex_home = TempDir::new()?;
codex_command(codex_home.path())?
.args(["plugin", "marketplace", "remove", "debug"])
.assert()
.failure()
.stderr(contains(
"marketplace `debug` is not configured or installed",
));
Ok(())
}
#[tokio::test]
async fn marketplace_remove_preserves_marketplace_referenced_by_session_config() -> Result<()> {
let codex_home = TempDir::new()?;
record_user_marketplace(codex_home.path(), "debug", &configured_marketplace_update())?;
write_installed_marketplace(codex_home.path(), "debug")?;
let config_path = codex_home.path().join("config.toml");
let config = std::fs::read_to_string(&config_path)?;
codex_command(codex_home.path())?
.args([
"plugin", "marketplace",
"-c", "marketplaces.debug.source_type=\"git\"",
"remove", "debug",
])
.assert()
.failure()
.stderr(contains(
"marketplace `debug` is configured in session-flags; remove it from that configuration source instead",
));
assert_eq!(std::fs::read_to_string(config_path)?, config);
assert_eq!(
std::fs::read_to_string(
marketplace_install_root(codex_home.path()).join("debug/marker.txt")
)?,
"installed",
);
Ok(())
}

View File

@@ -0,0 +1,118 @@
use anyhow::Result;
use akode_core_plugins::installed_marketplaces::marketplace_install_root;
use akode_utils_absolute_path::AbsolutePathBuf;
use predicates::str::contains;
use pretty_assertions::assert_eq;
use serde_json::json;
use std::path::Path;
use tempfile::TempDir;
fn codex_command(codex_home: &Path) -> Result<assert_cmd::Command> {
let mut cmd = assert_cmd::Command::new(akode_utils_cargo_bin::cargo_bin("akode")?);
cmd.env("AKODE_HOME", codex_home);
Ok(cmd)
}
#[tokio::test]
async fn marketplace_upgrade_runs_under_plugin() -> Result<()> {
let codex_home = TempDir::new()?;
let abandoned = marketplace_install_root(codex_home.path())
.join(".staging")
.join(format!("marketplace-{}-abandoned", std::env::consts::OS));
std::fs::create_dir_all(abandoned.join("checkout"))?;
std::fs::write(abandoned.join(".lock"), "")?;
std::fs::write(abandoned.join("checkout/payload"), "abandoned clone")?;
codex_command(codex_home.path())?
.args(["plugin", "marketplace", "upgrade"])
.assert()
.success()
.stdout(contains("No configured Git marketplaces to upgrade."));
assert!(!abandoned.exists());
Ok(())
}
#[tokio::test]
async fn marketplace_upgrade_json_prints_upgrade_outcome() -> Result<()> {
let codex_home = TempDir::new()?;
let source = TempDir::new()?;
let manifest = r#"{"name":"debug","plugins":[]}"#;
std::fs::create_dir_all(source.path().join(".agents/plugins"))?;
std::fs::write(
source.path().join(".agents/plugins/marketplace.json"),
manifest,
)?;
for args in [
vec!["init", "--quiet"],
vec!["add", "."],
vec![
"-c",
"user.name=Codex Tests",
"-c",
"user.email=codex@example.com",
"commit",
"-m",
"marketplace",
],
] {
let output = std::process::Command::new("git")
.current_dir(source.path())
.args(args)
.output()?;
anyhow::ensure!(
output.status.success(),
"git fixture failed: {}",
String::from_utf8_lossy(&output.stderr)
);
}
let source_arg = serde_json::to_string(&source.path().to_string_lossy())?;
let marketplace_override =
format!("marketplaces.debug={{source_type=\"git\",source={source_arg}}}");
let assert = codex_command(codex_home.path())?
.current_dir(codex_home.path())
.args(["--config", &marketplace_override])
.args(["plugin", "marketplace", "upgrade", "--json"])
.assert()
.success();
let stdout = assert.get_output().stdout.as_slice();
let actual: serde_json::Value = serde_json::from_slice(stdout)?;
let installed_root = AbsolutePathBuf::try_from(
marketplace_install_root(&codex_home.path().canonicalize()?).join("debug"),
)?;
assert_eq!(
actual,
json!({
"selectedMarketplaces": ["debug"],
"upgradedRoots": [installed_root],
"errors": [],
})
);
assert_eq!(
std::fs::read_to_string(installed_root.join(".agents/plugins/marketplace.json"))?,
manifest
);
assert!(!codex_home.path().join("config.toml").exists());
assert_eq!(
std::fs::read_dir(marketplace_install_root(codex_home.path()).join(".staging"))?.count(),
0
);
Ok(())
}
#[tokio::test]
async fn marketplace_upgrade_no_longer_runs_at_top_level() -> Result<()> {
let codex_home = TempDir::new()?;
codex_command(codex_home.path())?
.args(["marketplace", "upgrade"])
.assert()
.failure()
.stderr(contains("unrecognized subcommand 'upgrade'"));
Ok(())
}

View File

@@ -0,0 +1,582 @@
use std::collections::BTreeMap;
use std::path::Path;
use anyhow::Result;
use akode_config::types::McpServerTransportConfig;
use akode_core::config::edit::ConfigEditsBuilder;
use akode_core::config::load_global_mcp_servers;
use predicates::str::contains;
use pretty_assertions::assert_eq;
use tempfile::TempDir;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::method;
use wiremock::matchers::path;
fn codex_command(codex_home: &Path) -> Result<assert_cmd::Command> {
let mut cmd = assert_cmd::Command::new(akode_utils_cargo_bin::cargo_bin("akode")?);
cmd.env("AKODE_HOME", codex_home);
Ok(cmd)
}
#[tokio::test]
async fn add_and_remove_server_updates_global_config() -> Result<()> {
let codex_home = TempDir::new()?;
let mut add_cmd = codex_command(codex_home.path())?;
add_cmd
.args(["mcp", "add", "docs", "--", "echo", "hello"])
.assert()
.success()
.stdout(contains("Added global MCP server 'docs'."));
let servers = load_global_mcp_servers(codex_home.path()).await?;
assert_eq!(servers.len(), 1);
let docs = servers.get("docs").expect("server should exist");
match &docs.transport {
McpServerTransportConfig::Stdio {
command,
args,
env,
env_vars,
cwd,
} => {
assert_eq!(command, "echo");
assert_eq!(args, &vec!["hello".to_string()]);
assert!(env.is_none());
assert!(env_vars.is_empty());
assert!(cwd.is_none());
}
other => panic!("unexpected transport: {other:?}"),
}
assert!(docs.enabled);
let mut remove_cmd = codex_command(codex_home.path())?;
remove_cmd
.args(["mcp", "remove", "docs"])
.assert()
.success()
.stdout(contains("Removed global MCP server 'docs'."));
let servers = load_global_mcp_servers(codex_home.path()).await?;
assert!(servers.is_empty());
let mut remove_again_cmd = codex_command(codex_home.path())?;
remove_again_cmd
.args(["mcp", "remove", "docs"])
.assert()
.success()
.stdout(contains("No MCP server named 'docs' found."));
let servers = load_global_mcp_servers(codex_home.path()).await?;
assert!(servers.is_empty());
Ok(())
}
#[tokio::test]
async fn npm_server_names_round_trip_through_cli() -> Result<()> {
let codex_home = TempDir::new()?;
let name = "npm:@modelcontextprotocol/server-sequential.thinking";
codex_command(codex_home.path())?
.args(["mcp", "add", name, "--", "echo", "hello"])
.assert()
.success();
let config = std::fs::read_to_string(codex_home.path().join("config.toml"))?;
assert!(config.contains(&format!("[mcp_servers.\"{name}\"]")));
let servers = load_global_mcp_servers(codex_home.path()).await?;
assert_eq!(
servers.keys().map(String::as_str).collect::<Vec<_>>(),
vec![name]
);
let output = codex_command(codex_home.path())?
.args(["mcp", "get", name, "--json"])
.assert()
.success()
.get_output()
.stdout
.clone();
let server: serde_json::Value = serde_json::from_slice(&output)?;
assert_eq!(server["name"], name);
let output = codex_command(codex_home.path())?
.args(["mcp", "list", "--json"])
.assert()
.success()
.get_output()
.stdout
.clone();
let listed: Vec<serde_json::Value> = serde_json::from_slice(&output)?;
assert_eq!(listed.len(), 1);
assert_eq!(listed[0]["name"], name);
codex_command(codex_home.path())?
.args(["mcp", "remove", name])
.assert()
.success();
assert!(load_global_mcp_servers(codex_home.path()).await?.is_empty());
Ok(())
}
#[tokio::test]
async fn add_and_login_discover_oauth_through_configured_http_proxy() -> Result<()> {
let codex_home = TempDir::new()?;
let proxy = MockServer::start().await;
let resource_url = "http://cli-mcp.invalid";
let challenge = "Bearer resource_metadata=\"http://cli-mcp.invalid/oauth-resource\"";
Mock::given(method("GET"))
.and(path("/mcp"))
.respond_with(ResponseTemplate::new(401).insert_header("WWW-Authenticate", challenge))
.mount(&proxy)
.await;
Mock::given(method("GET"))
.and(path("/oauth-resource"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"resource": format!("{resource_url}/mcp"),
"authorization_servers": [resource_url],
})))
.mount(&proxy)
.await;
Mock::given(method("GET"))
.and(path("/.well-known/oauth-authorization-server"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"authorization_endpoint": format!("{resource_url}/oauth/authorize"),
"token_endpoint": format!("{resource_url}/oauth/token"),
"registration_endpoint": format!("{resource_url}/oauth/register"),
"response_types_supported": ["code"],
"code_challenge_methods_supported": ["S256"],
})))
.mount(&proxy)
.await;
Mock::given(method("POST"))
.and(path("/oauth/register"))
.respond_with(ResponseTemplate::new(400))
.mount(&proxy)
.await;
let mut add = codex_command(codex_home.path())?;
add.env("HTTP_PROXY", proxy.uri())
.env("http_proxy", proxy.uri())
.env_remove("HTTPS_PROXY")
.env_remove("https_proxy")
.env_remove("ALL_PROXY")
.env_remove("all_proxy")
.env_remove("NO_PROXY")
.env_remove("no_proxy")
.args([
"-c",
"mcp_oauth_credentials_store=\"file\"",
"mcp",
"add",
"oauth",
"--url",
"http://cli-mcp.invalid/mcp",
]);
let add_output = tokio::task::spawn_blocking(move || add.output()).await??;
assert!(
!add_output.status.success(),
"mock OAuth registration should terminate the automatic login"
);
assert!(
load_global_mcp_servers(codex_home.path())
.await?
.contains_key("oauth")
);
let helper_command = if cfg!(windows) {
r#"echo {"X-Gateway":"gateway-token"}"#
} else {
r#"printf '{"X-Gateway":"gateway-token"}'"#
};
let config_path = codex_home.path().join("config.toml");
let mut config = std::fs::read_to_string(&config_path)?;
config.push_str(&format!(
"http_headers_helper = {}\n",
toml::Value::String(helper_command.to_string())
));
std::fs::write(config_path, config)?;
// Local OAuth login does not require the execution-environment registry.
std::fs::write(codex_home.path().join("environments.toml"), "invalid = [")?;
let mut login = codex_command(codex_home.path())?;
login
.env("HTTP_PROXY", proxy.uri())
.env("http_proxy", proxy.uri())
.env_remove("HTTPS_PROXY")
.env_remove("https_proxy")
.env_remove("ALL_PROXY")
.env_remove("all_proxy")
.env_remove("NO_PROXY")
.env_remove("no_proxy")
.args([
"-c",
"mcp_oauth_credentials_store=\"file\"",
"mcp",
"login",
"oauth",
]);
let login_output = tokio::task::spawn_blocking(move || login.output()).await??;
assert!(
!login_output.status.success(),
"mock OAuth registration should terminate the explicit login"
);
let requests = proxy
.received_requests()
.await
.expect("mock proxy should record OAuth requests");
let registrations: Vec<_> = requests
.iter()
.filter(|request| request.method == "POST" && request.url.path() == "/oauth/register")
.collect();
assert_eq!(registrations.len(), 2);
assert_eq!(
registrations
.iter()
.filter(|request| request.headers.get("x-gateway").is_some())
.count(),
1
);
Ok(())
}
#[tokio::test]
async fn profile_mcp_reports_legacy_profile_migration() -> Result<()> {
let codex_home = TempDir::new()?;
std::fs::write(
codex_home.path().join("config.toml"),
r#"[profiles.work]
model = "gpt-5"
"#,
)?;
let mut list_cmd = codex_command(codex_home.path())?;
list_cmd
.args(["--profile", "work", "mcp", "list"])
.assert()
.failure()
.stderr(contains("--profile `work` cannot be used"))
.stderr(contains("[profiles.work]"))
.stderr(contains("work.config.toml"));
Ok(())
}
#[tokio::test]
async fn add_with_env_preserves_key_order_and_values() -> Result<()> {
let codex_home = TempDir::new()?;
let mut add_cmd = codex_command(codex_home.path())?;
add_cmd
.args([
"mcp",
"add",
"envy",
"--env",
"FOO=bar",
"--env",
"ALPHA=beta",
"--",
"python",
"server.py",
])
.assert()
.success();
let servers = load_global_mcp_servers(codex_home.path()).await?;
let envy = servers.get("envy").expect("server should exist");
let env = match &envy.transport {
McpServerTransportConfig::Stdio { env: Some(env), .. } => env,
other => panic!("unexpected transport: {other:?}"),
};
assert_eq!(env.len(), 2);
assert_eq!(env.get("FOO"), Some(&"bar".to_string()));
assert_eq!(env.get("ALPHA"), Some(&"beta".to_string()));
assert!(envy.enabled);
Ok(())
}
#[tokio::test]
async fn add_streamable_http_without_manual_token() -> Result<()> {
let codex_home = TempDir::new()?;
let mut add_cmd = codex_command(codex_home.path())?;
add_cmd
.args([
"mcp",
"add",
"github",
"--url",
"https://example.com/mcp",
"--oauth-client-registration",
"dcr",
])
.assert()
.success();
let servers = load_global_mcp_servers(codex_home.path()).await?;
let github = servers.get("github").expect("github server should exist");
match &github.transport {
McpServerTransportConfig::StreamableHttp {
url,
bearer_token_env_var,
http_headers,
env_http_headers,
..
} => {
assert_eq!(url, "https://example.com/mcp");
assert!(bearer_token_env_var.is_none());
assert!(http_headers.is_none());
assert!(env_http_headers.is_none());
}
other => panic!("unexpected transport: {other:?}"),
}
assert!(github.enabled);
assert_eq!(github.oauth, None);
assert!(!codex_home.path().join(".credentials.json").exists());
assert!(!codex_home.path().join(".env").exists());
let config = std::fs::read_to_string(codex_home.path().join("config.toml"))?;
assert!(!config.contains("client_registration"));
assert!(!config.contains("[mcp_servers.github.oauth]"));
Ok(())
}
#[tokio::test]
async fn add_rejects_blank_client_credentials_before_saving() -> Result<()> {
let mut errors = Vec::new();
for (client_id, client_secret) in [("registered-client", " "), (" ", "cli-secret-marker")] {
let codex_home = TempDir::new()?;
let output = codex_command(codex_home.path())?
.args([
"mcp",
"add",
"private",
"--url",
"http://127.0.0.1:9/mcp",
"--oauth-client-id",
client_id,
"--oauth-client-secret",
client_secret,
])
.assert()
.failure()
.get_output()
.clone();
let stderr = String::from_utf8(output.stderr)?;
assert!(!stderr.contains("cli-secret-marker"));
assert!(!String::from_utf8(output.stdout)?.contains("cli-secret-marker"));
assert!(load_global_mcp_servers(codex_home.path()).await?.is_empty());
errors.push(stderr.trim().to_string());
}
insta::assert_snapshot!(errors.join("\n"), @r"
Error: --oauth-client-secret must not be empty
Error: --oauth-client-secret requires a nonempty --oauth-client-id
");
Ok(())
}
#[tokio::test]
async fn add_streamable_http_with_custom_env_var() -> Result<()> {
let codex_home = TempDir::new()?;
let mut add_cmd = codex_command(codex_home.path())?;
add_cmd
.args([
"mcp",
"add",
"issues",
"--url",
"https://example.com/issues",
"--bearer-token-env-var",
"GITHUB_TOKEN",
])
.assert()
.success();
let servers = load_global_mcp_servers(codex_home.path()).await?;
let issues = servers.get("issues").expect("issues server should exist");
match &issues.transport {
McpServerTransportConfig::StreamableHttp {
url,
bearer_token_env_var,
http_headers,
env_http_headers,
..
} => {
assert_eq!(url, "https://example.com/issues");
assert_eq!(bearer_token_env_var.as_deref(), Some("GITHUB_TOKEN"));
assert!(http_headers.is_none());
assert!(env_http_headers.is_none());
}
other => panic!("unexpected transport: {other:?}"),
}
assert!(issues.enabled);
Ok(())
}
#[tokio::test]
async fn add_streamable_http_with_oauth_options() -> Result<()> {
let codex_home = TempDir::new()?;
let expected_callback = "http://127.0.0.1/callback/w9gKTtkB7gWy";
let mut add_cmd = codex_command(codex_home.path())?;
add_cmd
.args([
"-c",
"mcp_oauth_callback_port=43123",
"mcp",
"add",
"oauth-server",
"--url",
"https://example.com/mcp",
"--oauth-client-id",
"eci-prd-pub-codex-123",
"--oauth-resource",
"https://resource.example.com",
])
.assert()
.success()
.stdout(contains(format!("OAuth callback URL: {expected_callback}")));
let servers = load_global_mcp_servers(codex_home.path()).await?;
let oauth_server = servers
.get("oauth-server")
.expect("oauth server should exist");
assert_eq!(
oauth_server.oauth_client_id(),
Some("eci-prd-pub-codex-123")
);
assert_eq!(
oauth_server
.oauth
.as_ref()
.and_then(|oauth| oauth.callback_url.as_deref()),
Some(expected_callback)
);
assert_eq!(
oauth_server.oauth_resource.as_deref(),
Some("https://resource.example.com")
);
Ok(())
}
#[tokio::test]
async fn add_persists_issuer_bound_callback_before_starting_oauth() -> Result<()> {
let codex_home = TempDir::new()?;
let oauth_server = MockServer::start().await;
let issuer = format!("{}/mcp", oauth_server.uri());
let metadata = serde_json::json!({
"issuer": issuer,
"authorization_endpoint": "not-a-valid-authorization-url",
"token_endpoint": format!("{}/token", oauth_server.uri()),
"authorization_response_iss_parameter_supported": true,
});
let concurrent_codex_home = codex_home.path().to_path_buf();
let concurrent_servers = BTreeMap::from([(
"concurrent".to_string(),
toml::from_str("command = \"echo\"\nargs = [\"concurrent\"]")?,
)]);
let concurrent_add = std::sync::Once::new();
Mock::given(method("GET"))
.and(path("/.well-known/oauth-authorization-server/mcp"))
.respond_with(move |_: &wiremock::Request| {
concurrent_add.call_once(|| {
// Edit during discovery without starting another CLI inside the HTTP timeout.
ConfigEditsBuilder::new(&concurrent_codex_home)
.replace_mcp_servers(&concurrent_servers)
.apply_blocking()
.expect("persist concurrent MCP server during discovery");
});
ResponseTemplate::new(200).set_body_json(metadata.clone())
})
.mount(&oauth_server)
.await;
let mut add_cmd = codex_command(codex_home.path())?;
add_cmd.args([
"mcp",
"add",
"issuer-bound",
"--url",
&format!("{}/mcp", oauth_server.uri()),
"--oauth-client-id",
"registered-client",
]);
let output = tokio::task::spawn_blocking(move || add_cmd.output()).await??;
assert_cmd::assert::Assert::new(output)
.failure()
.stdout(contains("OAuth callback URL: http://127.0.0.1/callback"))
.stderr(contains("OAuth authorization endpoint must be a valid URL"));
let servers = load_global_mcp_servers(codex_home.path()).await?;
assert!(servers.contains_key("concurrent"));
assert_eq!(
servers["issuer-bound"]
.oauth
.as_ref()
.and_then(|oauth| oauth.callback_url.as_deref()),
Some("http://127.0.0.1/callback")
);
Ok(())
}
#[tokio::test]
async fn add_streamable_http_rejects_removed_flag() -> Result<()> {
let codex_home = TempDir::new()?;
let mut add_cmd = codex_command(codex_home.path())?;
add_cmd
.args([
"mcp",
"add",
"github",
"--url",
"https://example.com/mcp",
"--with-bearer-token",
])
.assert()
.failure()
.stderr(contains("--with-bearer-token"));
let servers = load_global_mcp_servers(codex_home.path()).await?;
assert!(servers.is_empty());
Ok(())
}
#[tokio::test]
async fn add_cant_add_command_and_url() -> Result<()> {
let codex_home = TempDir::new()?;
let mut add_cmd = codex_command(codex_home.path())?;
add_cmd
.args([
"mcp",
"add",
"github",
"--url",
"https://example.com/mcp",
"--command",
"--",
"echo",
"hello",
])
.assert()
.failure()
.stderr(contains("unexpected argument '--command' found"));
let servers = load_global_mcp_servers(codex_home.path()).await?;
assert!(servers.is_empty());
Ok(())
}

View File

@@ -0,0 +1,511 @@
use std::collections::BTreeMap;
use std::io::Read;
use std::io::Write;
use std::net::TcpListener;
use std::path::Path;
use std::time::Duration;
use std::time::Instant;
use anyhow::Result;
use akode_config::types::McpServerTransportConfig;
use akode_core::config::edit::ConfigEditsBuilder;
use akode_core::config::load_global_mcp_servers;
use akode_login::AKODE_API_KEY_ENV_VAR;
use predicates::prelude::PredicateBooleanExt;
use predicates::str::contains;
use pretty_assertions::assert_eq;
use serde_json::Value as JsonValue;
use serde_json::json;
use tempfile::TempDir;
#[cfg(target_os = "macos")]
use wiremock::Mock;
#[cfg(target_os = "macos")]
use wiremock::MockServer;
#[cfg(target_os = "macos")]
use wiremock::ResponseTemplate;
#[cfg(target_os = "macos")]
use wiremock::matchers::method;
#[cfg(target_os = "macos")]
use wiremock::matchers::path;
fn codex_command(codex_home: &Path) -> Result<assert_cmd::Command> {
let mut cmd = assert_cmd::Command::new(akode_utils_cargo_bin::cargo_bin("akode")?);
cmd.env("AKODE_HOME", codex_home);
Ok(cmd)
}
async fn configure_http_oauth_server(codex_home: &Path, url: &str) -> Result<()> {
let mut servers = load_global_mcp_servers(codex_home).await?;
servers.insert(
"oauth".to_string(),
toml::from_str(&format!("url = \"{url}\""))?,
);
ConfigEditsBuilder::new(codex_home)
.replace_mcp_servers(&servers)
.apply_blocking()?;
Ok(())
}
#[test]
fn list_shows_empty_state() -> Result<()> {
let codex_home = TempDir::new()?;
let mut cmd = codex_command(codex_home.path())?;
let output = cmd.args(["mcp", "list"]).output()?;
assert!(output.status.success());
let stdout = String::from_utf8(output.stdout)?;
assert!(stdout.contains("No MCP servers configured yet."));
Ok(())
}
#[test]
fn api_key_auth_exposes_api_curated_plugin_mcp_servers() -> Result<()> {
let codex_home = TempDir::new()?;
std::fs::write(
codex_home.path().join("config.toml"),
r#"[features]
plugins = true
remote_plugin = false
[plugins."api-docs@openai-api-curated"]
enabled = true
"#,
)?;
let plugin_root = codex_home
.path()
.join("plugins/cache/openai-api-curated/api-docs/local");
std::fs::create_dir_all(plugin_root.join(".codex-plugin"))?;
std::fs::write(
plugin_root.join(".codex-plugin/plugin.json"),
r#"{"name":"api-docs","version":"local"}"#,
)?;
std::fs::write(
plugin_root.join(".mcp.json"),
r#"{
"mcpServers": {
"api-docs": {
"type": "stdio",
"command": "api-docs-mcp"
}
}
}"#,
)?;
let mut list_cmd = codex_command(codex_home.path())?;
list_cmd
.env(AKODE_API_KEY_ENV_VAR, "sk-test")
.args(["mcp", "list", "--json"])
.assert()
.success()
.stdout(contains(r#""name": "api-docs""#));
let mut get_cmd = codex_command(codex_home.path())?;
get_cmd
.env(AKODE_API_KEY_ENV_VAR, "sk-test")
.args(["mcp", "get", "api-docs", "--json"])
.assert()
.success()
.stdout(contains(r#""name": "api-docs""#));
Ok(())
}
#[tokio::test]
async fn list_discovers_local_oauth_server_through_environment_proxy() -> Result<()> {
let codex_home = TempDir::new()?;
configure_http_oauth_server(codex_home.path(), "http://mcp-proxy.invalid/mcp").await?;
std::fs::write(codex_home.path().join("environments.toml"), "invalid = [")?;
let listener = TcpListener::bind("127.0.0.1:0")?;
listener.set_nonblocking(true)?;
let proxy_url = format!("http://{}", listener.local_addr()?);
let proxy = std::thread::spawn(move || -> Result<Vec<String>> {
let resource_metadata = json!({
"resource": "http://mcp-proxy.invalid/mcp",
"authorization_servers": ["http://mcp-proxy.invalid"],
})
.to_string();
let authorization_metadata = json!({
"authorization_endpoint": "https://oauth.example/authorize",
"token_endpoint": "https://oauth.example/token",
})
.to_string();
let responses = [
concat!(
"HTTP/1.1 401 Unauthorized\r\n",
"www-authenticate: Bearer resource_metadata=\"http://mcp-proxy.invalid/oauth-resource\"\r\n",
"content-length: 0\r\n",
"connection: close\r\n\r\n"
)
.to_string(),
format!(
"HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{resource_metadata}",
resource_metadata.len()
),
format!(
"HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{authorization_metadata}",
authorization_metadata.len()
),
];
let mut requests = Vec::new();
for response in responses {
let deadline = Instant::now() + Duration::from_secs(30);
let mut stream = loop {
match listener.accept() {
Ok((stream, _)) => break stream,
Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
anyhow::ensure!(
Instant::now() < deadline,
"proxy did not receive OAuth discovery request {}",
requests.len() + 1
);
std::thread::sleep(Duration::from_millis(10));
}
Err(error) => return Err(error.into()),
}
};
stream.set_nonblocking(false)?;
stream.set_read_timeout(Some(Duration::from_secs(5)))?;
let mut request = Vec::new();
let mut buffer = [0_u8; 1024];
while !request.windows(4).any(|window| window == b"\r\n\r\n") {
let bytes_read = stream.read(&mut buffer)?;
anyhow::ensure!(bytes_read > 0, "proxy request ended before its headers");
request.extend_from_slice(&buffer[..bytes_read]);
anyhow::ensure!(
request.len() <= 64 * 1024,
"proxy request headers are too large"
);
}
let request = String::from_utf8(request)?;
requests.push(request.lines().next().unwrap_or_default().to_string());
stream.write_all(response.as_bytes())?;
}
Ok(requests)
});
let mut command = codex_command(codex_home.path())?;
command
.env("HTTP_PROXY", &proxy_url)
.env("http_proxy", &proxy_url)
.env_remove("HTTPS_PROXY")
.env_remove("https_proxy")
.env_remove("ALL_PROXY")
.env_remove("all_proxy")
.env_remove("NO_PROXY")
.env_remove("no_proxy")
.args([
"-c",
"mcp_oauth_credentials_store=\"file\"",
"mcp",
"list",
"--json",
]);
let output = command.output()?;
assert!(
output.status.success(),
"mcp list failed: {}",
String::from_utf8_lossy(&output.stderr)
);
let proxy_requests = proxy
.join()
.expect("OAuth discovery proxy thread should finish")?;
assert_eq!(
proxy_requests,
vec![
"GET http://mcp-proxy.invalid/mcp HTTP/1.1",
"GET http://mcp-proxy.invalid/oauth-resource HTTP/1.1",
"GET http://mcp-proxy.invalid/.well-known/oauth-authorization-server HTTP/1.1",
]
);
let entries: JsonValue = serde_json::from_slice(&output.stdout)?;
assert_eq!(entries[0]["name"], "oauth");
assert_eq!(
entries[0]["auth_status"],
"not_logged_in",
"OAuth discovery failed after proxy requests {proxy_requests:?}; stderr: {}",
String::from_utf8_lossy(&output.stderr)
);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn list_reports_unknown_auth_status_when_oauth_discovery_is_rate_limited() -> Result<()> {
let codex_home = TempDir::new()?;
let server = wiremock::MockServer::start().await;
wiremock::Mock::given(wiremock::matchers::method("GET"))
.and(wiremock::matchers::path("/mcp"))
.respond_with(wiremock::ResponseTemplate::new(429))
.expect(1)
.mount(&server)
.await;
configure_http_oauth_server(codex_home.path(), &format!("{}/mcp", server.uri())).await?;
codex_command(codex_home.path())?
.env("NO_PROXY", "127.0.0.1,localhost")
.env("no_proxy", "127.0.0.1,localhost")
.args([
"-c",
"mcp_oauth_credentials_store=\"file\"",
"mcp",
"list",
"--json",
])
.assert()
.success()
.stdout(contains(r#""auth_status": "unknown""#));
server.verify().await;
Ok(())
}
#[cfg(target_os = "macos")]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn list_with_macos_proxy_resolution_does_not_panic() -> Result<()> {
let codex_home = TempDir::new()?;
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/.well-known/oauth-authorization-server/mcp"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"authorization_endpoint": "https://oauth.example/authorize",
"token_endpoint": "https://oauth.example/token",
})))
.expect(2)
.mount(&server)
.await;
configure_http_oauth_server(codex_home.path(), &format!("{}/mcp", server.uri())).await?;
for respect_system_proxy in [false, true] {
let system_proxy_override = format!("features.respect_system_proxy={respect_system_proxy}");
let mut command = codex_command(codex_home.path())?;
command
.env_remove("HTTP_PROXY")
.env_remove("http_proxy")
.env_remove("HTTPS_PROXY")
.env_remove("https_proxy")
.env_remove("ALL_PROXY")
.env_remove("all_proxy")
.env_remove("NO_PROXY")
.env_remove("no_proxy")
.args([
"-c",
&system_proxy_override,
"-c",
"mcp_oauth_credentials_store=\"file\"",
"mcp",
"list",
"--json",
]);
let output = command.output()?;
assert!(
output.status.success(),
"macOS proxy resolution should not panic with respect_system_proxy={respect_system_proxy}: {}",
String::from_utf8_lossy(&output.stderr)
);
let entries: JsonValue = serde_json::from_slice(&output.stdout)?;
assert_eq!(entries[0]["auth_status"], "not_logged_in");
}
Ok(())
}
#[tokio::test]
async fn list_and_get_render_expected_output() -> Result<()> {
let codex_home = TempDir::new()?;
let mut add = codex_command(codex_home.path())?;
add.args([
"mcp",
"add",
"docs",
"--env",
"TOKEN=secret",
"--",
"docs-server",
"--port",
"4000",
])
.assert()
.success();
let mut servers = load_global_mcp_servers(codex_home.path()).await?;
let docs_entry = servers
.get_mut("docs")
.expect("docs server should exist after add");
match &mut docs_entry.transport {
McpServerTransportConfig::Stdio { env_vars, .. } => {
*env_vars = vec!["APP_TOKEN".into(), "WORKSPACE_ID".into()];
}
other => panic!("unexpected transport: {other:?}"),
}
ConfigEditsBuilder::new(codex_home.path())
.replace_mcp_servers(&servers)
.apply_blocking()?;
let mut list_cmd = codex_command(codex_home.path())?;
let list_output = list_cmd.args(["mcp", "list"]).output()?;
assert!(list_output.status.success());
let stdout = String::from_utf8(list_output.stdout)?;
assert!(stdout.contains("Name"));
assert!(stdout.contains("docs"));
assert!(stdout.contains("docs-server"));
assert!(stdout.contains("TOKEN=*****"));
assert!(stdout.contains("APP_TOKEN=*****"));
assert!(stdout.contains("WORKSPACE_ID=*****"));
assert!(stdout.contains("Status"));
assert!(stdout.contains("Auth"));
assert!(stdout.contains("enabled"));
assert!(stdout.contains("Unsupported"));
let mut list_json_cmd = codex_command(codex_home.path())?;
let json_output = list_json_cmd.args(["mcp", "list", "--json"]).output()?;
assert!(json_output.status.success());
let stdout = String::from_utf8(json_output.stdout)?;
let parsed: JsonValue = serde_json::from_str(&stdout)?;
assert_eq!(
parsed,
json!([
{
"name": "docs",
"enabled": true,
"disabled_reason": null,
"transport": {
"type": "stdio",
"command": "docs-server",
"args": [
"--port",
"4000"
],
"env": {
"TOKEN": "secret"
},
"env_vars": [
"APP_TOKEN",
"WORKSPACE_ID"
],
"cwd": null
},
"startup_timeout_sec": null,
"tool_timeout_sec": null,
"auth_status": "unsupported"
}
]
)
);
let mut get_cmd = codex_command(codex_home.path())?;
let get_output = get_cmd.args(["mcp", "get", "docs"]).output()?;
assert!(get_output.status.success());
let stdout = String::from_utf8(get_output.stdout)?;
assert!(stdout.contains("docs"));
assert!(stdout.contains("transport: stdio"));
assert!(stdout.contains("command: docs-server"));
assert!(stdout.contains("args: --port 4000"));
assert!(stdout.contains("env: TOKEN=*****"));
assert!(stdout.contains("APP_TOKEN=*****"));
assert!(stdout.contains("WORKSPACE_ID=*****"));
assert!(stdout.contains("enabled: true"));
assert!(stdout.contains("remove: akode mcp remove docs"));
let mut get_json_cmd = codex_command(codex_home.path())?;
get_json_cmd
.args(["mcp", "get", "docs", "--json"])
.assert()
.success()
.stdout(contains("\"name\": \"docs\"").and(contains("\"enabled\": true")));
Ok(())
}
#[test]
fn list_and_get_redact_http_headers_helper() -> Result<()> {
let codex_home = TempDir::new()?;
let marker = codex_home.path().join("helper-ran");
let helper = toml::Value::String(format!("echo invoked > \"{}\"", marker.display()));
std::fs::write(
codex_home.path().join("config.toml"),
format!(
"[mcp_servers.docs]\n\
url = \"https://example.com/mcp\"\n\
http_headers_helper = {helper}\n\
[mcp_servers.authenticated]\n\
url = \"https://example.com/mcp\"\n\
http_headers = {{ Authorization = \"Bearer static\" }}\n\
http_headers_helper = {helper}\n"
),
)?;
let list_output = codex_command(codex_home.path())?
.args(["mcp", "list", "--json"])
.output()?;
assert!(list_output.status.success());
let stdout = String::from_utf8(list_output.stdout)?;
assert!(stdout.contains("http_headers_helper"));
assert!(stdout.contains("<redacted>"));
let entries: Vec<JsonValue> = serde_json::from_str(&stdout)?;
let auth_statuses = entries
.into_iter()
.map(|entry| {
(
entry["name"].as_str().expect("server name").to_string(),
entry["auth_status"]
.as_str()
.expect("auth status")
.to_string(),
)
})
.collect::<BTreeMap<_, _>>();
assert_eq!(
auth_statuses,
BTreeMap::from([
("authenticated".to_string(), "bearer_token".to_string()),
("docs".to_string(), "unknown".to_string()),
])
);
assert!(!marker.exists());
for args in [
&["mcp", "get", "docs", "--json"][..],
&["mcp", "get", "docs"][..],
] {
let output = codex_command(codex_home.path())?.args(args).output()?;
assert!(output.status.success());
let stdout = String::from_utf8(output.stdout)?;
assert!(stdout.contains("http_headers_helper"));
assert!(stdout.contains("<redacted>"));
assert!(!stdout.contains("helper-ran"));
assert!(!marker.exists());
}
Ok(())
}
#[tokio::test]
async fn get_disabled_server_shows_single_line() -> Result<()> {
let codex_home = TempDir::new()?;
let mut add = codex_command(codex_home.path())?;
add.args(["mcp", "add", "docs", "--", "docs-server"])
.assert()
.success();
let mut servers = load_global_mcp_servers(codex_home.path()).await?;
let docs = servers
.get_mut("docs")
.expect("docs server should exist after add");
docs.enabled = false;
ConfigEditsBuilder::new(codex_home.path())
.replace_mcp_servers(&servers)
.apply_blocking()?;
let mut get_cmd = codex_command(codex_home.path())?;
let get_output = get_cmd.args(["mcp", "get", "docs"]).output()?;
assert!(get_output.status.success());
let stdout = String::from_utf8(get_output.stdout)?;
assert_eq!(stdout.trim_end(), "docs (disabled)");
Ok(())
}

Some files were not shown because too many files have changed in this diff Show More