Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 70 additions & 0 deletions cli/src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ const RUNTIME_SHUTDOWN_GRACE: Duration = Duration::from_millis(500);
const REPEATED_COMMAND_DISPATCH_ERROR: &str =
"Command lifecycle telemetry attempted to execute command dispatch more than once";
const CLAUDE_ONLY_HOOK_SUBCOMMANDS: [&str; 2] = ["claude-mutation-scope", "claude-model-state"];
const CODEX_HOOK_SUBCOMMANDS: [&str; 2] = ["codex", "codex-mutation-scope"];
const SHARED_CLAUDE_HOOK_SUBCOMMANDS: [&str; 2] = ["diff-trace", "conversation-trace"];
const CLAUDE_HOOK_CALLER_MARKERS: [&str; 2] = ["CLAUDECODE", "CLAUDE_PROJECT_DIR"];

Expand Down Expand Up @@ -317,12 +318,18 @@ fn managed_span_kind(args: &[String], claude_hook_caller: bool) -> Option<Manage
.map(String::as_str)
.filter(|arg| !arg.starts_with('-'));
let claude_hook = match (words.next(), words.next()) {
(Some(first), Some(subcommand))
if first == services::hooks::NAME && CODEX_HOOK_SUBCOMMANDS.contains(&subcommand) =>
{
return Some(ManagedSpanKind::CodexHook);
}
(Some(first), Some(subcommand)) if first == services::hooks::NAME => {
CLAUDE_ONLY_HOOK_SUBCOMMANDS.contains(&subcommand)
|| (claude_hook_caller && SHARED_CLAUDE_HOOK_SUBCOMMANDS.contains(&subcommand))
}
(Some(first), _) if first == services::hooks::NAME => false,
(Some(first), _) if first == services::setup::NAME => false,
(Some(first), _) if first == services::codex_telemetry::NAME => false,
(Some(first), Some("bash")) if first == services::bash_policy::NAME => claude_hook_caller,
(Some(first), Some("telemetry-headers")) if first == services::auth_command::NAME => false,
_ => return Some(ManagedSpanKind::Command),
Expand Down Expand Up @@ -1130,4 +1137,67 @@ pub(crate) mod tests {
.await;
assert!(matches!(telemetry, RuntimeTelemetry::Noop(_)));
}

fn span_kind_for(command_line: &[&str], claude_hook_caller: bool) -> Option<ManagedSpanKind> {
let args = command_line
.iter()
.map(|arg| (*arg).to_string())
.collect::<Vec<_>>();
managed_span_kind(&args, claude_hook_caller)
}

#[test]
fn managed_span_kind_admits_codex_hook_subcommands_without_caller_marker() {
for caller in [false, true] {
for argv in [
["sce", "hooks", "codex"].as_slice(),
["sce", "hooks", "codex-mutation-scope"].as_slice(),
] {
assert_eq!(
span_kind_for(argv, caller),
Some(ManagedSpanKind::CodexHook),
"{argv:?} caller={caller}"
);
}
}
}

#[test]
fn managed_span_kind_keeps_claude_and_shared_hook_admission() {
assert_eq!(
span_kind_for(&["sce", "hooks", "claude-mutation-scope"], false),
Some(ManagedSpanKind::ClaudeHook)
);
assert_eq!(
span_kind_for(&["sce", "hooks", "diff-trace"], true),
Some(ManagedSpanKind::ClaudeHook)
);
assert_eq!(span_kind_for(&["sce", "hooks", "diff-trace"], false), None);
assert_eq!(span_kind_for(&["sce", "hooks", "pre-commit"], true), None);
assert_eq!(
span_kind_for(&["sce", "config", "show"], false),
Some(ManagedSpanKind::Command)
);
}

#[test]
fn managed_span_kind_never_instruments_the_header_helper_or_codex_launcher() {
for argv in [
["sce", "auth", "telemetry-headers"].as_slice(),
["sce", "auth", "telemetry-headers", "--repo", "/work/repo"].as_slice(),
["sce", "auth", "telemetry-headers", "--repo=/work/repo"].as_slice(),
["sce", "auth", "--repo", "telemetry-headers"].as_slice(),
["sce", "codex"].as_slice(),
["sce", "codex", "exec", "prompt"].as_slice(),
["sce", "codex", "hooks", "codex"].as_slice(),
] {
for caller in [false, true] {
assert_eq!(
span_kind_for(argv, caller),
None,
"{argv:?} caller={caller}"
);
}
}
}
}
25 changes: 24 additions & 1 deletion cli/src/cli_schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,11 @@ pub const SYNC_TOP_LEVEL_PURPOSE: &str =
"Synchronize the current repository's Agent Trace database";
pub const SYNC_SHOW_IN_TOP_LEVEL_HELP: bool = true;

pub const CODEX_CLAP_ABOUT: &str =
"Launch Codex with SCE native telemetry for the current repository";
pub const CODEX_TOP_LEVEL_PURPOSE: &str = "Launch Codex with SCE native telemetry";
pub const CODEX_SHOW_IN_TOP_LEVEL_HELP: bool = true;

pub const TOP_LEVEL_COMMANDS: &[TopLevelCommandMetadata] = &[
TopLevelCommandMetadata {
name: crate::services::auth_command::NAME,
Expand Down Expand Up @@ -99,6 +104,11 @@ pub const TOP_LEVEL_COMMANDS: &[TopLevelCommandMetadata] = &[
purpose: SYNC_TOP_LEVEL_PURPOSE,
show_in_top_level_help: SYNC_SHOW_IN_TOP_LEVEL_HELP,
},
TopLevelCommandMetadata {
name: crate::services::codex_telemetry::NAME,
purpose: CODEX_TOP_LEVEL_PURPOSE,
show_in_top_level_help: CODEX_SHOW_IN_TOP_LEVEL_HELP,
},
];

#[derive(Parser, Debug)]
Expand Down Expand Up @@ -241,6 +251,16 @@ pub enum Commands {
#[arg(long, value_enum, default_value_t = OutputFormat::Text)]
format: OutputFormat,
},

#[command(
about = CODEX_CLAP_ABOUT,
hide = !CODEX_SHOW_IN_TOP_LEVEL_HELP,
disable_help_flag = true
)]
Codex {
#[arg(trailing_var_arg = true, allow_hyphen_values = true, num_args = 0..)]
args: Vec<String>,
},
}

#[derive(Subcommand, Debug, Clone, PartialEq, Eq)]
Expand All @@ -264,7 +284,10 @@ pub enum AuthSubcommand {
},

#[command(hide = true, about = "Print telemetry authorization headers")]
TelemetryHeaders,
TelemetryHeaders {
#[arg(long, hide = true)]
repo: Option<PathBuf>,
},
}

#[derive(Subcommand, Debug, Clone, PartialEq, Eq)]
Expand Down
7 changes: 7 additions & 0 deletions cli/src/command_surface.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,13 @@ const HELP_SECTIONS: &[HelpSection] = &[
suffix: " [--fix] [--format <text|json>]",
}],
},
HelpSection {
title: "Codex Usage:",
body: &[HelpSectionBodyLine::Command {
cmd: " sce codex",
suffix: " [codex arguments...]",
}],
},
HelpSection {
title: "Version Usage:",
body: &[HelpSectionBodyLine::Command {
Expand Down
2 changes: 1 addition & 1 deletion cli/src/services/auth_command/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,6 @@ pub struct AuthCommand {

impl AuthCommand {
pub async fn execute<C>(&self, _context: &C) -> Result<String, CliError> {
auth_command::run_auth_subcommand(self.request).await
auth_command::run_auth_subcommand(self.request.clone()).await
}
}
99 changes: 92 additions & 7 deletions cli/src/services/auth_command/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,15 +64,16 @@ pub(crate) struct LoginReport {
pub(crate) telemetry: TelemetryProvisioningResult,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum AuthSubcommand {
Login { format: AuthFormat },
Logout { format: AuthFormat },
Whoami { format: AuthFormat },
TelemetryHeaders,
TelemetryHeadersForRepository { repository: PathBuf },
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct AuthRequest {
pub subcommand: AuthSubcommand,
}
Expand All @@ -96,7 +97,7 @@ async fn run_auth_subcommand_with<L, O, S, H, LF, OF, SF, HF>(
telemetry_headers: H,
) -> Result<String, CliError>
where
H: FnOnce() -> HF,
H: FnOnce(Option<PathBuf>) -> HF,
HF: Future<Output = Result<String, CliError>>,
L: FnOnce(AuthFormat) -> LF,
LF: Future<Output = Result<String, CliError>>,
Expand All @@ -109,12 +110,15 @@ where
AuthSubcommand::Login { format } => login(format).await,
AuthSubcommand::Logout { format } => logout(format).await,
AuthSubcommand::Whoami { format } => whoami(format).await,
AuthSubcommand::TelemetryHeaders => telemetry_headers().await,
AuthSubcommand::TelemetryHeaders => telemetry_headers(None).await,
AuthSubcommand::TelemetryHeadersForRepository { repository } => {
telemetry_headers(Some(repository)).await
}
}
}

async fn run_telemetry_headers() -> Result<String, CliError> {
let working_dir = std::env::current_dir().ok();
async fn run_telemetry_headers(repository: Option<PathBuf>) -> Result<String, CliError> {
let working_dir = telemetry_headers_working_dir(repository);
let telemetry_enabled = working_dir.as_deref().is_some_and(telemetry_enabled_for);
telemetry_headers_with(
working_dir,
Expand All @@ -127,7 +131,16 @@ async fn run_telemetry_headers() -> Result<String, CliError> {
.await
}

fn telemetry_enabled_for(working_dir: &Path) -> bool {
fn telemetry_headers_working_dir(repository: Option<PathBuf>) -> Option<PathBuf> {
match repository {
Some(path) => std::fs::canonicalize(path)
.ok()
.filter(|path| path.is_dir()),
None => std::env::current_dir().ok(),
}
}

pub(crate) fn telemetry_enabled_for(working_dir: &Path) -> bool {
config::resolve_auth_runtime_config(working_dir)
.is_ok_and(|config| config.access_policy.telemetry_enabled())
}
Expand Down Expand Up @@ -1096,6 +1109,78 @@ mod tests {
assert_eq!(headers, r#"{"Authorization":"Bearer tok-scoped"}"#);
}

#[tokio::test]
async fn telemetry_headers_route_repository_argument_and_keep_no_argument_form() {
let unexpected = |_: AuthFormat| async { panic!("unexpected auth subcommand") };
let routed = |subcommand: AuthSubcommand| {
run_auth_subcommand_with(
AuthRequest { subcommand },
unexpected,
unexpected,
unexpected,
|repository: Option<PathBuf>| async move { Ok(format!("{repository:?}")) },
)
};

assert_eq!(
routed(AuthSubcommand::TelemetryHeaders).await.unwrap(),
"None"
);
assert_eq!(
routed(AuthSubcommand::TelemetryHeadersForRepository {
repository: PathBuf::from("/work/b"),
})
.await
.unwrap(),
r#"Some("/work/b")"#
);
}

#[tokio::test]
async fn telemetry_headers_bind_the_explicit_repository_and_fail_closed_elsewhere() {
use crate::services::managed_telemetry::claude_helper::tests::git_repository_with_remote;

let dir = tempfile::tempdir().unwrap();
let enrolled = git_repository_with_remote(dir.path(), "a", "git@github.com:acme/a.git");
let unenrolled = git_repository_with_remote(dir.path(), "b", "git@github.com:acme/b.git");
let enrolled_subdir = enrolled.join("src").join("module");
std::fs::create_dir_all(&enrolled_subdir).unwrap();
let enrolled_file = enrolled.join("file");
std::fs::write(&enrolled_file, "").unwrap();
let not_git = dir.path().join("plain");
std::fs::create_dir_all(&not_git).unwrap();
let enrolled_id = repository_id_for(&enrolled).expect("enrolled repository identity");

let headers_for = |repository: PathBuf| {
let enrolled_id = enrolled_id.clone();
telemetry_headers_with(
telemetry_headers_working_dir(Some(repository)),
true,
false,
|| true,
repository_id_for,
move |repository_id: String| async move {
Ok((repository_id == enrolled_id).then(|| telemetry_credential("tok-a")))
},
)
};

assert_eq!(
headers_for(enrolled_subdir).await.unwrap(),
r#"{"Authorization":"Bearer tok-a"}"#
);
for (case, repository) in [
("unenrolled", unenrolled),
("not git", not_git),
("missing", dir.path().join("missing")),
("missing inside enrolled repo", enrolled.join("missing")),
("file inside enrolled repo", enrolled_file),
] {
let error = headers_for(repository).await.expect_err(case);
assert_eq!(error.to_string(), TELEMETRY_HEADERS_UNAVAILABLE, "{case}");
}
}

#[test]
fn telemetry_headers_failures_use_fixed_secret_free_diagnostic() {
let missing = render_telemetry_headers(Ok(None)).expect_err("missing should fail");
Expand Down
69 changes: 69 additions & 0 deletions cli/src/services/codex_telemetry/command.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
use std::io::Write;

use anyhow::anyhow;

use super::{
plan_launch_with, read_config_file, repository_root_for, LaunchContext, LaunchPlan,
CODEX_PROGRAM,
};
use crate::services::auth_command::{repository_telemetry_authorized, telemetry_enabled_for};
use crate::services::error::CliError;

pub struct CodexCommand {
pub args: Vec<String>,
}

impl CodexCommand {
pub async fn execute_with_stderr<C, W>(
&self,
_context: &C,
stderr: &mut W,
) -> Result<String, CliError>
where
W: Write,
{
let context = LaunchContext::from_process().map_err(|error| {
CliError::runtime(anyhow!(
"Failed to determine the Codex launch directory: {error}"
))
})?;
let plan = plan_launch_with(
self.args.clone(),
&context,
read_config_file,
|key| std::env::var(key).ok(),
repository_root_for,
telemetry_enabled_for,
async |repository_root| repository_telemetry_authorized(&repository_root).await,
)
.await;
if let Some(notice) = &plan.notice {
let _ = writeln!(stderr, "{notice}");
}
let _ = stderr.flush();
launch(plan)
}
}

#[cfg(unix)]
fn launch(plan: LaunchPlan) -> Result<String, CliError> {
use std::os::unix::process::CommandExt;

let error = std::process::Command::new(CODEX_PROGRAM)
.args(plan.argv)
.exec();
Err(launch_failure(&error))
}

#[cfg(not(unix))]
fn launch(plan: LaunchPlan) -> Result<String, CliError> {
let status = std::process::Command::new(CODEX_PROGRAM)
.args(plan.argv)
.status()
.map_err(|error| launch_failure(&error))?;
std::process::exit(status.code().unwrap_or(1));
}

fn launch_failure(error: &std::io::Error) -> CliError {
CliError::runtime(anyhow!("Failed to launch `{CODEX_PROGRAM}`: {error}"))
}
Loading
Loading