chore: merge hooks precedence into hook safety controls

Co-authored-by: Codex noreply@openai.com
This commit is contained in:
viyatb-oai
2026-04-16 16:43:48 -07:00
co-authored by Codex noreply@openai.com
1092 changed files with 83948 additions and 22758 deletions
+177 -154
View File
@@ -1,9 +1,9 @@
use std::fs;
use std::path::Path;
use codex_app_server_protocol::ConfigLayerSource;
use codex_config::ConfigLayerSource;
use codex_config::ConfigLayerStack;
use codex_config::ConfigLayerStackOrdering;
use codex_protocol::protocol::HookSource;
use codex_utils_absolute_path::AbsolutePathBuf;
use std::fs;
use super::ConfiguredHandler;
use super::config::HookHandlerConfig;
@@ -106,8 +106,8 @@ pub(crate) fn discover_handlers(config_layer_stack: Option<&ConfigLayerStack>) -
&mut handlers,
&mut warnings,
&mut display_order,
source_path.as_path(),
matches!(layer.name, ConfigLayerSource::Project { .. }),
&source_path,
hook_source_for_config_layer_source(&layer.name),
event_name,
groups,
);
@@ -131,116 +131,123 @@ pub(crate) fn discover_handlers(config_layer_stack: Option<&ConfigLayerStack>) -
DiscoveryResult { handlers, warnings }
}
fn append_group_handlers(
handlers: &mut Vec<ConfiguredHandler>,
warnings: &mut Vec<String>,
display_order: &mut i64,
context: AppendGroupContext<'_>,
matcher: Option<&str>,
group_handlers: Vec<HookHandlerConfig>,
) {
if let Some(matcher) = matcher
&& let Err(err) = validate_matcher_pattern(matcher)
{
warnings.push(format!(
"invalid matcher {matcher:?} in {}: {err}",
context.source_path.display()
));
return;
}
for handler in group_handlers {
match handler {
HookHandlerConfig::Command {
command,
timeout_sec,
r#async,
status_message,
} => {
if r#async {
warnings.push(format!(
"skipping async hook in {}: async hooks are not supported yet",
context.source_path.display()
));
continue;
}
if command.trim().is_empty() {
warnings.push(format!(
"skipping empty hook command in {}",
context.source_path.display()
));
continue;
}
let timeout_sec = timeout_sec.unwrap_or(600).max(1);
handlers.push(ConfiguredHandler {
event_name: context.event_name,
matcher: matcher.map(ToOwned::to_owned),
command,
timeout_sec,
status_message,
source_path: context.source_path.to_path_buf(),
is_project: context.is_project,
display_order: *display_order,
});
*display_order += 1;
}
HookHandlerConfig::Prompt {} => warnings.push(format!(
"skipping prompt hook in {}: prompt hooks are not supported yet",
context.source_path.display()
)),
HookHandlerConfig::Agent {} => warnings.push(format!(
"skipping agent hook in {}: agent hooks are not supported yet",
context.source_path.display()
)),
}
}
}
#[derive(Clone, Copy)]
struct AppendGroupContext<'a> {
source_path: &'a Path,
is_project: bool,
event_name: codex_protocol::protocol::HookEventName,
}
fn append_matcher_groups(
handlers: &mut Vec<ConfiguredHandler>,
warnings: &mut Vec<String>,
display_order: &mut i64,
source_path: &Path,
is_project: bool,
source_path: &AbsolutePathBuf,
source: HookSource,
event_name: codex_protocol::protocol::HookEventName,
groups: Vec<MatcherGroup>,
) {
for group in groups {
append_group_handlers(
handlers,
warnings,
display_order,
AppendGroupContext {
source_path,
is_project,
event_name,
},
matcher_pattern_for_event(event_name, group.matcher.as_deref()),
group.hooks,
);
let matcher = matcher_pattern_for_event(event_name, group.matcher.as_deref());
if let Some(matcher) = matcher
&& let Err(err) = validate_matcher_pattern(matcher)
{
warnings.push(format!(
"invalid matcher {matcher:?} in {}: {err}",
source_path.display()
));
continue;
}
for handler in group.hooks {
match handler {
HookHandlerConfig::Command {
command,
timeout_sec,
r#async,
status_message,
} => {
if r#async {
warnings.push(format!(
"skipping async hook in {}: async hooks are not supported yet",
source_path.display()
));
continue;
}
if command.trim().is_empty() {
warnings.push(format!(
"skipping empty hook command in {}",
source_path.display()
));
continue;
}
let timeout_sec = timeout_sec.unwrap_or(600).max(1);
handlers.push(ConfiguredHandler {
event_name,
matcher: matcher.map(ToOwned::to_owned),
command,
timeout_sec,
status_message,
source_path: source_path.clone(),
source,
display_order: *display_order,
});
*display_order += 1;
}
HookHandlerConfig::Prompt {} => warnings.push(format!(
"skipping prompt hook in {}: prompt hooks are not supported yet",
source_path.display()
)),
HookHandlerConfig::Agent {} => warnings.push(format!(
"skipping agent hook in {}: agent hooks are not supported yet",
source_path.display()
)),
}
}
}
}
fn hook_source_for_config_layer_source(source: &ConfigLayerSource) -> HookSource {
match source {
ConfigLayerSource::System { .. } => HookSource::System,
ConfigLayerSource::User { .. } => HookSource::User,
ConfigLayerSource::Project { .. } => HookSource::Project,
ConfigLayerSource::Mdm { .. } => HookSource::Mdm,
ConfigLayerSource::SessionFlags => HookSource::SessionFlags,
ConfigLayerSource::LegacyManagedConfigTomlFromFile { .. } => {
HookSource::LegacyManagedConfigFile
}
ConfigLayerSource::LegacyManagedConfigTomlFromMdm => HookSource::LegacyManagedConfigMdm,
}
}
#[cfg(test)]
mod tests {
use std::path::Path;
use std::path::PathBuf;
use codex_config::ConfigLayerSource;
use codex_protocol::protocol::HookEventName;
use codex_protocol::protocol::HookSource;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_absolute_path::test_support::PathBufExt;
use codex_utils_absolute_path::test_support::test_path_buf;
use pretty_assertions::assert_eq;
use super::AppendGroupContext;
use super::ConfiguredHandler;
use super::HookHandlerConfig;
use super::append_group_handlers;
use crate::events::common::matcher_pattern_for_event;
use super::MatcherGroup;
use super::append_matcher_groups;
fn source_path() -> AbsolutePathBuf {
test_path_buf("/tmp/hooks.json").abs()
}
fn hook_source() -> HookSource {
HookSource::User
}
fn command_group(matcher: Option<&str>) -> MatcherGroup {
MatcherGroup {
matcher: matcher.map(str::to_string),
hooks: vec![HookHandlerConfig::Command {
command: "echo hello".to_string(),
timeout_sec: None,
r#async: false,
status_message: None,
}],
}
}
#[test]
fn user_prompt_submit_ignores_invalid_matcher_during_discovery() {
@@ -248,22 +255,14 @@ mod tests {
let mut warnings = Vec::new();
let mut display_order = 0;
append_group_handlers(
append_matcher_groups(
&mut handlers,
&mut warnings,
&mut display_order,
AppendGroupContext {
source_path: Path::new("/tmp/hooks.json"),
is_project: false,
event_name: HookEventName::UserPromptSubmit,
},
matcher_pattern_for_event(HookEventName::UserPromptSubmit, Some("[")),
vec![HookHandlerConfig::Command {
command: "echo hello".to_string(),
timeout_sec: None,
r#async: false,
status_message: None,
}],
&source_path(),
hook_source(),
HookEventName::UserPromptSubmit,
vec![command_group(Some("["))],
);
assert_eq!(warnings, Vec::<String>::new());
@@ -275,8 +274,8 @@ mod tests {
command: "echo hello".to_string(),
timeout_sec: 600,
status_message: None,
source_path: PathBuf::from("/tmp/hooks.json"),
is_project: false,
source_path: source_path(),
source: hook_source(),
display_order: 0,
}]
);
@@ -288,22 +287,14 @@ mod tests {
let mut warnings = Vec::new();
let mut display_order = 0;
append_group_handlers(
append_matcher_groups(
&mut handlers,
&mut warnings,
&mut display_order,
AppendGroupContext {
source_path: Path::new("/tmp/hooks.json"),
is_project: false,
event_name: HookEventName::PreToolUse,
},
matcher_pattern_for_event(HookEventName::PreToolUse, Some("^Bash$")),
vec![HookHandlerConfig::Command {
command: "echo hello".to_string(),
timeout_sec: None,
r#async: false,
status_message: None,
}],
&source_path(),
hook_source(),
HookEventName::PreToolUse,
vec![command_group(Some("^Bash$"))],
);
assert_eq!(warnings, Vec::<String>::new());
@@ -315,8 +306,8 @@ mod tests {
command: "echo hello".to_string(),
timeout_sec: 600,
status_message: None,
source_path: PathBuf::from("/tmp/hooks.json"),
is_project: false,
source_path: source_path(),
source: hook_source(),
display_order: 0,
}]
);
@@ -328,22 +319,14 @@ mod tests {
let mut warnings = Vec::new();
let mut display_order = 0;
append_group_handlers(
append_matcher_groups(
&mut handlers,
&mut warnings,
&mut display_order,
AppendGroupContext {
source_path: Path::new("/tmp/hooks.json"),
is_project: false,
event_name: HookEventName::PreToolUse,
},
matcher_pattern_for_event(HookEventName::PreToolUse, Some("*")),
vec![HookHandlerConfig::Command {
command: "echo hello".to_string(),
timeout_sec: None,
r#async: false,
status_message: None,
}],
&source_path(),
hook_source(),
HookEventName::PreToolUse,
vec![command_group(Some("*"))],
);
assert_eq!(warnings, Vec::<String>::new());
@@ -357,22 +340,14 @@ mod tests {
let mut warnings = Vec::new();
let mut display_order = 0;
append_group_handlers(
append_matcher_groups(
&mut handlers,
&mut warnings,
&mut display_order,
AppendGroupContext {
source_path: Path::new("/tmp/hooks.json"),
is_project: false,
event_name: HookEventName::PostToolUse,
},
matcher_pattern_for_event(HookEventName::PostToolUse, Some("Edit|Write")),
vec![HookHandlerConfig::Command {
command: "echo hello".to_string(),
timeout_sec: None,
r#async: false,
status_message: None,
}],
&source_path(),
hook_source(),
HookEventName::PostToolUse,
vec![command_group(Some("Edit|Write"))],
);
assert_eq!(warnings, Vec::<String>::new());
@@ -380,4 +355,52 @@ mod tests {
assert_eq!(handlers[0].event_name, HookEventName::PostToolUse);
assert_eq!(handlers[0].matcher.as_deref(), Some("Edit|Write"));
}
#[test]
fn hook_source_for_config_layer_source_discards_source_details() {
let config_file = test_path_buf("/tmp/.codex/config.toml").abs();
let dot_codex_folder = test_path_buf("/tmp/worktree/.codex").abs();
assert_eq!(
super::hook_source_for_config_layer_source(&ConfigLayerSource::System {
file: config_file.clone(),
}),
HookSource::System,
);
assert_eq!(
super::hook_source_for_config_layer_source(&ConfigLayerSource::User {
file: config_file.clone(),
}),
HookSource::User,
);
assert_eq!(
super::hook_source_for_config_layer_source(&ConfigLayerSource::Project {
dot_codex_folder
}),
HookSource::Project,
);
assert_eq!(
super::hook_source_for_config_layer_source(&ConfigLayerSource::Mdm {
domain: "com.openai.codex".to_string(),
key: "config".to_string(),
}),
HookSource::Mdm,
);
assert_eq!(
super::hook_source_for_config_layer_source(&ConfigLayerSource::SessionFlags),
HookSource::SessionFlags,
);
assert_eq!(
super::hook_source_for_config_layer_source(
&ConfigLayerSource::LegacyManagedConfigTomlFromFile { file: config_file },
),
HookSource::LegacyManagedConfigFile,
);
assert_eq!(
super::hook_source_for_config_layer_source(
&ConfigLayerSource::LegacyManagedConfigTomlFromMdm,
),
HookSource::LegacyManagedConfigMdm,
);
}
}
+14 -7
View File
@@ -50,6 +50,7 @@ pub(crate) fn running_summary(handler: &ConfiguredHandler) -> HookRunSummary {
execution_mode: HookExecutionMode::Sync,
scope: scope_for_event(handler.event_name),
source_path: handler.source_path.clone(),
source: handler.source,
display_order: handler.display_order,
status: HookRunStatus::Running,
status_message: handler.status_message.clone(),
@@ -90,7 +91,7 @@ pub(crate) fn select_handlers_by_trust_precedence(
let mut non_project = Vec::new();
let mut project = Vec::new();
for handler in select_handlers(handlers, event_name, matcher_input) {
if handler.is_project {
if handler.source == codex_protocol::protocol::HookSource::Project {
project.push(handler);
} else {
non_project.push(handler);
@@ -136,6 +137,7 @@ pub(crate) fn completed_summary(
execution_mode: HookExecutionMode::Sync,
scope: scope_for_event(handler.event_name),
source_path: handler.source_path.clone(),
source: handler.source,
display_order: handler.display_order,
status,
status_message: handler.status_message.clone(),
@@ -158,9 +160,10 @@ fn scope_for_event(event_name: HookEventName) -> HookScope {
#[cfg(test)]
mod tests {
use std::path::PathBuf;
use codex_protocol::protocol::HookEventName;
use codex_protocol::protocol::HookSource;
use codex_utils_absolute_path::test_support::PathBufExt;
use codex_utils_absolute_path::test_support::test_path_buf;
use super::ConfiguredHandler;
use super::select_handlers;
@@ -178,8 +181,8 @@ mod tests {
command: command.to_string(),
timeout_sec: 5,
status_message: None,
source_path: PathBuf::from("/tmp/hooks.json"),
is_project: false,
source_path: test_path_buf("/tmp/hooks.json").abs(),
source: HookSource::User,
display_order,
}
}
@@ -197,8 +200,12 @@ mod tests {
command: command.to_string(),
timeout_sec: 5,
status_message: None,
source_path: PathBuf::from(source_path),
is_project: source_path.contains("/project/"),
source_path: test_path_buf(source_path).abs(),
source: if source_path.contains("/project/") {
HookSource::Project
} else {
HookSource::User
},
display_order,
}
}
+4 -15
View File
@@ -5,10 +5,10 @@ pub(crate) mod dispatcher;
pub(crate) mod output_parser;
pub(crate) mod schema_loader;
use std::path::PathBuf;
use codex_config::ConfigLayerStack;
use codex_protocol::protocol::HookRunSummary;
use codex_protocol::protocol::HookSource;
use codex_utils_absolute_path::AbsolutePathBuf;
use crate::events::post_tool_use::PostToolUseOutcome;
use crate::events::post_tool_use::PostToolUseRequest;
@@ -34,8 +34,8 @@ pub(crate) struct ConfiguredHandler {
pub command: String,
pub timeout_sec: u64,
pub status_message: Option<String>,
pub source_path: PathBuf,
pub is_project: bool,
pub source_path: AbsolutePathBuf,
pub source: HookSource,
pub display_order: i64,
}
@@ -81,17 +81,6 @@ impl ClaudeHooksEngine {
};
}
if cfg!(windows) {
return Self {
handlers: Vec::new(),
warnings: vec![
"Disabled `codex_hooks` for this session because `hooks.json` lifecycle hooks are not supported on Windows yet."
.to_string(),
],
shell,
};
}
let _ = schema_loader::generated_hook_schemas();
let discovered = discovery::discover_handlers(config_layer_stack);
Self {
+26
View File
@@ -3,6 +3,7 @@ use codex_protocol::protocol::HookEventName;
use codex_protocol::protocol::HookOutputEntry;
use codex_protocol::protocol::HookOutputEntryKind;
use codex_protocol::protocol::HookRunStatus;
use codex_protocol::protocol::HookRunSummary;
use crate::engine::ConfiguredHandler;
use crate::engine::dispatcher;
@@ -69,6 +70,31 @@ pub(crate) fn serialization_failure_hook_events(
.collect()
}
pub(crate) fn serialization_failure_hook_events_for_tool_use(
handlers: Vec<ConfiguredHandler>,
turn_id: Option<String>,
error_message: String,
tool_use_id: &str,
) -> Vec<HookCompletedEvent> {
serialization_failure_hook_events(handlers, turn_id, error_message)
.into_iter()
.map(|event| hook_completed_for_tool_use(event, tool_use_id))
.collect()
}
pub(crate) fn hook_completed_for_tool_use(
mut event: HookCompletedEvent,
tool_use_id: &str,
) -> HookCompletedEvent {
event.run = hook_run_for_tool_use(event.run, tool_use_id);
event
}
pub(crate) fn hook_run_for_tool_use(mut run: HookRunSummary, tool_use_id: &str) -> HookRunSummary {
run.id = format!("{}:{tool_use_id}", run.id);
run
}
pub(crate) fn matcher_pattern_for_event(
event_name: HookEventName,
matcher: Option<&str>,
+80 -11
View File
@@ -7,6 +7,7 @@ use codex_protocol::protocol::HookOutputEntry;
use codex_protocol::protocol::HookOutputEntryKind;
use codex_protocol::protocol::HookRunStatus;
use codex_protocol::protocol::HookRunSummary;
use codex_utils_absolute_path::AbsolutePathBuf;
use serde_json::Value;
use super::common;
@@ -22,7 +23,7 @@ use crate::schema::PostToolUseToolInput;
pub struct PostToolUseRequest {
pub session_id: ThreadId,
pub turn_id: String,
pub cwd: PathBuf,
pub cwd: AbsolutePathBuf,
pub transcript_path: Option<PathBuf>,
pub model: String,
pub permission_mode: String,
@@ -59,7 +60,9 @@ pub(crate) fn preview(
Some(&request.tool_name),
)
.into_iter()
.map(|handler| dispatcher::running_summary(&handler))
.map(|handler| {
common::hook_run_for_tool_use(dispatcher::running_summary(&handler), &request.tool_use_id)
})
.collect()
}
@@ -100,11 +103,13 @@ pub(crate) async fn run(
}) {
Ok(input_json) => input_json,
Err(error) => {
return serialization_failure_outcome(common::serialization_failure_hook_events(
let hook_events = common::serialization_failure_hook_events_for_tool_use(
matched,
Some(request.turn_id),
Some(request.turn_id.clone()),
format!("failed to serialize post tool use hook input: {error}"),
));
&request.tool_use_id,
);
return serialization_failure_outcome(hook_events);
}
};
@@ -113,7 +118,7 @@ pub(crate) async fn run(
matched,
input_json,
request.cwd.as_path(),
Some(request.turn_id),
Some(request.turn_id.clone()),
parse_completed,
)
.await;
@@ -135,7 +140,12 @@ pub(crate) async fn run(
);
PostToolUseOutcome {
hook_events: results.into_iter().map(|result| result.completed).collect(),
hook_events: results
.into_iter()
.map(|result| {
common::hook_completed_for_tool_use(result.completed, &request.tool_use_id)
})
.collect(),
should_stop,
stop_reason,
additional_contexts,
@@ -293,18 +303,22 @@ fn serialization_failure_outcome(hook_events: Vec<HookCompletedEvent>) -> PostTo
#[cfg(test)]
mod tests {
use std::path::PathBuf;
use codex_protocol::ThreadId;
use codex_protocol::protocol::HookEventName;
use codex_protocol::protocol::HookOutputEntry;
use codex_protocol::protocol::HookOutputEntryKind;
use codex_protocol::protocol::HookRunStatus;
use codex_utils_absolute_path::test_support::PathBufExt;
use codex_utils_absolute_path::test_support::test_path_buf;
use pretty_assertions::assert_eq;
use serde_json::json;
use super::PostToolUseHandlerData;
use super::parse_completed;
use super::preview;
use crate::engine::ConfiguredHandler;
use crate::engine::command_runner::CommandRunResult;
use crate::events::common;
#[test]
fn block_decision_stops_normal_processing() {
@@ -463,6 +477,46 @@ mod tests {
assert_eq!(parsed.completed.run.entries, Vec::<HookOutputEntry>::new());
}
#[test]
fn preview_and_completed_run_ids_include_tool_use_id() {
let request = request_for_tool_use("tool-call-456");
let runs = preview(&[handler()], &request);
assert_eq!(runs.len(), 1);
assert_eq!(
runs[0].id,
format!(
"post-tool-use:0:{}:tool-call-456",
test_path_buf("/tmp/hooks.json").display()
)
);
let parsed = parse_completed(
&handler(),
run_result(Some(0), "", ""),
Some("turn-1".to_string()),
);
let completed = common::hook_completed_for_tool_use(parsed.completed, &request.tool_use_id);
assert_eq!(completed.run.id, runs[0].id);
}
#[test]
fn serialization_failure_run_ids_include_tool_use_id() {
let request = request_for_tool_use("tool-call-456");
let runs = preview(&[handler()], &request);
let completed = common::serialization_failure_hook_events_for_tool_use(
vec![handler()],
Some(request.turn_id.clone()),
"serialize failed".into(),
&request.tool_use_id,
);
assert_eq!(completed.len(), 1);
assert_eq!(completed[0].run.id, runs[0].id);
}
fn handler() -> ConfiguredHandler {
ConfiguredHandler {
event_name: HookEventName::PostToolUse,
@@ -470,8 +524,8 @@ mod tests {
command: "python3 post_tool_use_hook.py".to_string(),
timeout_sec: 5,
status_message: Some("running post tool use hook".to_string()),
source_path: PathBuf::from("/tmp/hooks.json"),
is_project: false,
source_path: test_path_buf("/tmp/hooks.json").abs(),
source: codex_protocol::protocol::HookSource::User,
display_order: 0,
}
}
@@ -487,4 +541,19 @@ mod tests {
error: None,
}
}
fn request_for_tool_use(tool_use_id: &str) -> super::PostToolUseRequest {
super::PostToolUseRequest {
session_id: ThreadId::new(),
turn_id: "turn-1".to_string(),
cwd: test_path_buf("/tmp").abs(),
transcript_path: None,
model: "gpt-test".to_string(),
permission_mode: "default".to_string(),
tool_name: "Bash".to_string(),
tool_use_id: tool_use_id.to_string(),
command: "echo hello".to_string(),
tool_response: json!({"ok": true}),
}
}
}
+81 -15
View File
@@ -7,6 +7,7 @@ use codex_protocol::protocol::HookOutputEntry;
use codex_protocol::protocol::HookOutputEntryKind;
use codex_protocol::protocol::HookRunStatus;
use codex_protocol::protocol::HookRunSummary;
use codex_utils_absolute_path::AbsolutePathBuf;
use super::common;
use crate::engine::CommandShell;
@@ -20,7 +21,7 @@ use crate::schema::PreToolUseCommandInput;
pub struct PreToolUseRequest {
pub session_id: ThreadId,
pub turn_id: String,
pub cwd: PathBuf,
pub cwd: AbsolutePathBuf,
pub transcript_path: Option<PathBuf>,
pub model: String,
pub permission_mode: String,
@@ -52,7 +53,9 @@ pub(crate) fn preview(
Some(&request.tool_name),
)
.into_iter()
.map(|handler| dispatcher::running_summary(&handler))
.map(|handler| {
common::hook_run_for_tool_use(dispatcher::running_summary(&handler), &request.tool_use_id)
})
.collect()
}
@@ -90,11 +93,13 @@ pub(crate) async fn run(
}) {
Ok(input_json) => input_json,
Err(error) => {
return serialization_failure_outcome(common::serialization_failure_hook_events(
let hook_events = common::serialization_failure_hook_events_for_tool_use(
matched,
Some(request.turn_id),
Some(request.turn_id.clone()),
format!("failed to serialize pre tool use hook input: {error}"),
));
&request.tool_use_id,
);
return serialization_failure_outcome(hook_events);
}
};
@@ -142,7 +147,12 @@ pub(crate) async fn run(
.find_map(|result| result.data.block_reason.clone());
PreToolUseOutcome {
hook_events: results.into_iter().map(|result| result.completed).collect(),
hook_events: results
.into_iter()
.map(|result| {
common::hook_completed_for_tool_use(result.completed, &request.tool_use_id)
})
.collect(),
should_block,
block_reason,
}
@@ -258,21 +268,23 @@ fn serialization_failure_outcome(hook_events: Vec<HookCompletedEvent>) -> PreToo
#[cfg(test)]
mod tests {
use std::path::PathBuf;
use codex_protocol::ThreadId;
use codex_protocol::protocol::HookEventName;
use codex_protocol::protocol::HookOutputEntry;
use codex_protocol::protocol::HookOutputEntryKind;
use codex_protocol::protocol::HookRunStatus;
use codex_utils_absolute_path::test_support::PathBufExt;
use codex_utils_absolute_path::test_support::test_path_buf;
use pretty_assertions::assert_eq;
use super::PreToolUseHandlerData;
use super::PreToolUseRequest;
use super::parse_completed;
use super::preview;
use crate::engine::CommandShell;
use crate::engine::ConfiguredHandler;
use crate::engine::command_runner::CommandRunResult;
use crate::events::common;
#[test]
fn permission_decision_deny_blocks_processing() {
@@ -510,8 +522,8 @@ mod tests {
command: blocking_command,
timeout_sec: 5,
status_message: None,
source_path: PathBuf::from("/tmp/home/.codex/hooks.json"),
is_project: false,
source_path: test_path_buf("/tmp/home/.codex/hooks.json").abs(),
source: codex_protocol::protocol::HookSource::User,
display_order: 0,
},
ConfiguredHandler {
@@ -520,8 +532,8 @@ mod tests {
command: project_command,
timeout_sec: 5,
status_message: None,
source_path: PathBuf::from("/tmp/project/.codex/hooks.json"),
is_project: true,
source_path: test_path_buf("/tmp/project/.codex/hooks.json").abs(),
source: codex_protocol::protocol::HookSource::Project,
display_order: 1,
},
];
@@ -535,7 +547,7 @@ mod tests {
PreToolUseRequest {
session_id: ThreadId::new(),
turn_id: "turn-1".to_string(),
cwd: temp.path().to_path_buf(),
cwd: temp.path().to_path_buf().abs(),
transcript_path: None,
model: "gpt-5".to_string(),
permission_mode: "default".to_string(),
@@ -564,6 +576,46 @@ mod tests {
Ok(())
}
#[test]
fn preview_and_completed_run_ids_include_tool_use_id() {
let request = request_for_tool_use("tool-call-123");
let runs = preview(&[handler()], &request);
assert_eq!(runs.len(), 1);
assert_eq!(
runs[0].id,
format!(
"pre-tool-use:0:{}:tool-call-123",
test_path_buf("/tmp/hooks.json").display()
)
);
let parsed = parse_completed(
&handler(),
run_result(Some(0), "", ""),
Some("turn-1".to_string()),
);
let completed = common::hook_completed_for_tool_use(parsed.completed, &request.tool_use_id);
assert_eq!(completed.run.id, runs[0].id);
}
#[test]
fn serialization_failure_run_ids_include_tool_use_id() {
let request = request_for_tool_use("tool-call-123");
let runs = preview(&[handler()], &request);
let completed = common::serialization_failure_hook_events_for_tool_use(
vec![handler()],
Some(request.turn_id.clone()),
"serialize failed".into(),
&request.tool_use_id,
);
assert_eq!(completed.len(), 1);
assert_eq!(completed[0].run.id, runs[0].id);
}
fn handler() -> ConfiguredHandler {
ConfiguredHandler {
event_name: HookEventName::PreToolUse,
@@ -571,8 +623,8 @@ mod tests {
command: "echo hook".to_string(),
timeout_sec: 5,
status_message: None,
source_path: PathBuf::from("/tmp/hooks.json"),
is_project: false,
source_path: test_path_buf("/tmp/hooks.json").abs(),
source: codex_protocol::protocol::HookSource::User,
display_order: 0,
}
}
@@ -588,4 +640,18 @@ mod tests {
error: None,
}
}
fn request_for_tool_use(tool_use_id: &str) -> super::PreToolUseRequest {
super::PreToolUseRequest {
session_id: ThreadId::new(),
turn_id: "turn-1".to_string(),
cwd: test_path_buf("/tmp").abs(),
transcript_path: None,
model: "gpt-test".to_string(),
permission_mode: "default".to_string(),
tool_name: "Bash".to_string(),
tool_use_id: tool_use_id.to_string(),
command: "echo hello".to_string(),
}
}
}
+13 -10
View File
@@ -7,6 +7,7 @@ use codex_protocol::protocol::HookOutputEntry;
use codex_protocol::protocol::HookOutputEntryKind;
use codex_protocol::protocol::HookRunStatus;
use codex_protocol::protocol::HookRunSummary;
use codex_utils_absolute_path::AbsolutePathBuf;
use super::common;
use crate::engine::CommandShell;
@@ -20,6 +21,7 @@ use crate::schema::SessionStartCommandInput;
pub enum SessionStartSource {
Startup,
Resume,
Clear,
}
impl SessionStartSource {
@@ -27,6 +29,7 @@ impl SessionStartSource {
match self {
Self::Startup => "startup",
Self::Resume => "resume",
Self::Clear => "clear",
}
}
}
@@ -34,7 +37,7 @@ impl SessionStartSource {
#[derive(Debug, Clone)]
pub struct SessionStartRequest {
pub session_id: ThreadId,
pub cwd: PathBuf,
pub cwd: AbsolutePathBuf,
pub transcript_path: Option<PathBuf>,
pub model: String,
pub permission_mode: String,
@@ -277,13 +280,13 @@ fn serialization_failure_outcome(hook_events: Vec<HookCompletedEvent>) -> Sessio
#[cfg(test)]
mod tests {
use std::path::PathBuf;
use codex_protocol::ThreadId;
use codex_protocol::protocol::HookEventName;
use codex_protocol::protocol::HookOutputEntry;
use codex_protocol::protocol::HookOutputEntryKind;
use codex_protocol::protocol::HookRunStatus;
use codex_utils_absolute_path::test_support::PathBufExt;
use codex_utils_absolute_path::test_support::test_path_buf;
use pretty_assertions::assert_eq;
use super::SessionStartHandlerData;
@@ -412,8 +415,8 @@ mod tests {
command: stopping_command,
timeout_sec: 5,
status_message: None,
source_path: PathBuf::from("/tmp/home/.codex/hooks.json"),
is_project: false,
source_path: test_path_buf("/tmp/home/.codex/hooks.json").abs(),
source: codex_protocol::protocol::HookSource::User,
display_order: 0,
},
ConfiguredHandler {
@@ -422,8 +425,8 @@ mod tests {
command: project_command,
timeout_sec: 5,
status_message: None,
source_path: PathBuf::from("/tmp/project/.codex/hooks.json"),
is_project: true,
source_path: test_path_buf("/tmp/project/.codex/hooks.json").abs(),
source: codex_protocol::protocol::HookSource::Project,
display_order: 1,
},
];
@@ -436,7 +439,7 @@ mod tests {
},
SessionStartRequest {
session_id: ThreadId::new(),
cwd: temp.path().to_path_buf(),
cwd: temp.path().to_path_buf().abs(),
transcript_path: None,
model: "gpt-5".to_string(),
permission_mode: "default".to_string(),
@@ -475,8 +478,8 @@ mod tests {
command: "echo hook".to_string(),
timeout_sec: 600,
status_message: None,
source_path: PathBuf::from("/tmp/hooks.json"),
is_project: false,
source_path: test_path_buf("/tmp/hooks.json").abs(),
source: codex_protocol::protocol::HookSource::User,
display_order: 0,
}
}
+6 -5
View File
@@ -8,6 +8,7 @@ use codex_protocol::protocol::HookOutputEntry;
use codex_protocol::protocol::HookOutputEntryKind;
use codex_protocol::protocol::HookRunStatus;
use codex_protocol::protocol::HookRunSummary;
use codex_utils_absolute_path::AbsolutePathBuf;
use super::common;
use crate::engine::CommandShell;
@@ -22,7 +23,7 @@ use crate::schema::StopCommandInput;
pub struct StopRequest {
pub session_id: ThreadId,
pub turn_id: String,
pub cwd: PathBuf,
pub cwd: AbsolutePathBuf,
pub transcript_path: Option<PathBuf>,
pub model: String,
pub permission_mode: String,
@@ -310,12 +311,12 @@ fn serialization_failure_outcome(hook_events: Vec<HookCompletedEvent>) -> StopOu
#[cfg(test)]
mod tests {
use std::path::PathBuf;
use codex_protocol::protocol::HookEventName;
use codex_protocol::protocol::HookOutputEntry;
use codex_protocol::protocol::HookOutputEntryKind;
use codex_protocol::protocol::HookRunStatus;
use codex_utils_absolute_path::test_support::PathBufExt;
use codex_utils_absolute_path::test_support::test_path_buf;
use pretty_assertions::assert_eq;
use codex_protocol::items::HookPromptFragment;
@@ -526,8 +527,8 @@ mod tests {
command: "echo hook".to_string(),
timeout_sec: 600,
status_message: None,
source_path: PathBuf::from("/tmp/hooks.json"),
is_project: false,
source_path: test_path_buf("/tmp/hooks.json").abs(),
source: codex_protocol::protocol::HookSource::User,
display_order: 0,
}
}
+11 -10
View File
@@ -7,6 +7,7 @@ use codex_protocol::protocol::HookOutputEntry;
use codex_protocol::protocol::HookOutputEntryKind;
use codex_protocol::protocol::HookRunStatus;
use codex_protocol::protocol::HookRunSummary;
use codex_utils_absolute_path::AbsolutePathBuf;
use super::common;
use crate::engine::CommandShell;
@@ -21,7 +22,7 @@ use crate::schema::UserPromptSubmitCommandInput;
pub struct UserPromptSubmitRequest {
pub session_id: ThreadId,
pub turn_id: String,
pub cwd: PathBuf,
pub cwd: AbsolutePathBuf,
pub transcript_path: Option<PathBuf>,
pub model: String,
pub permission_mode: String,
@@ -300,13 +301,13 @@ fn serialization_failure_outcome(hook_events: Vec<HookCompletedEvent>) -> UserPr
#[cfg(test)]
mod tests {
use std::path::PathBuf;
use codex_protocol::ThreadId;
use codex_protocol::protocol::HookEventName;
use codex_protocol::protocol::HookOutputEntry;
use codex_protocol::protocol::HookOutputEntryKind;
use codex_protocol::protocol::HookRunStatus;
use codex_utils_absolute_path::test_support::PathBufExt;
use codex_utils_absolute_path::test_support::test_path_buf;
use pretty_assertions::assert_eq;
use super::UserPromptSubmitHandlerData;
@@ -471,8 +472,8 @@ mod tests {
command: stopping_command,
timeout_sec: 5,
status_message: None,
source_path: PathBuf::from("/tmp/home/.codex/hooks.json"),
is_project: false,
source_path: test_path_buf("/tmp/home/.codex/hooks.json").abs(),
source: codex_protocol::protocol::HookSource::User,
display_order: 0,
},
ConfiguredHandler {
@@ -481,8 +482,8 @@ mod tests {
command: project_command,
timeout_sec: 5,
status_message: None,
source_path: PathBuf::from("/tmp/project/.codex/hooks.json"),
is_project: true,
source_path: test_path_buf("/tmp/project/.codex/hooks.json").abs(),
source: codex_protocol::protocol::HookSource::Project,
display_order: 1,
},
];
@@ -496,7 +497,7 @@ mod tests {
UserPromptSubmitRequest {
session_id: ThreadId::new(),
turn_id: "turn-1".to_string(),
cwd: temp.path().to_path_buf(),
cwd: temp.path().to_path_buf().abs(),
transcript_path: None,
model: "gpt-5".to_string(),
permission_mode: "default".to_string(),
@@ -535,8 +536,8 @@ mod tests {
command: "echo hook".to_string(),
timeout_sec: 5,
status_message: None,
source_path: PathBuf::from("/tmp/hooks.json"),
is_project: false,
source_path: test_path_buf("/tmp/hooks.json").abs(),
source: codex_protocol::protocol::HookSource::User,
display_order: 0,
}
}
+8 -4
View File
@@ -76,20 +76,22 @@ pub fn notify_hook(argv: Vec<String>) -> Hook {
mod tests {
use anyhow::Result;
use codex_protocol::ThreadId;
use codex_utils_absolute_path::test_support::PathBufExt;
use codex_utils_absolute_path::test_support::test_path_buf;
use pretty_assertions::assert_eq;
use serde_json::Value;
use serde_json::json;
use std::path::Path;
use super::*;
use crate::HookEventAfterAgent;
fn expected_notification_json() -> Value {
let cwd = test_path_buf("/Users/example/project");
json!({
"type": "agent-turn-complete",
"thread-id": "b5f6c1c2-1111-2222-3333-444455556666",
"turn-id": "12345",
"cwd": "/Users/example/project",
"cwd": cwd.display().to_string(),
"client": "codex-tui",
"input-messages": ["Rename `foo` to `bar` and update the callsites."],
"last-assistant-message": "Rename complete and verified `cargo build` succeeds.",
@@ -101,7 +103,9 @@ mod tests {
let notification = UserNotification::AgentTurnComplete {
thread_id: "b5f6c1c2-1111-2222-3333-444455556666".to_string(),
turn_id: "12345".to_string(),
cwd: "/Users/example/project".to_string(),
cwd: test_path_buf("/Users/example/project")
.display()
.to_string(),
client: Some("codex-tui".to_string()),
input_messages: vec!["Rename `foo` to `bar` and update the callsites.".to_string()],
last_assistant_message: Some(
@@ -118,7 +122,7 @@ mod tests {
fn legacy_notify_json_matches_historical_wire_shape() -> Result<()> {
let payload = HookPayload {
session_id: ThreadId::new(),
cwd: Path::new("/Users/example/project").to_path_buf(),
cwd: test_path_buf("/Users/example/project").abs(),
client: Some("codex-tui".to_string()),
triggered_at: chrono::Utc::now(),
hook_event: HookEvent::AfterAgent {
+10 -8
View File
@@ -1,4 +1,3 @@
use std::path::PathBuf;
use std::sync::Arc;
use chrono::DateTime;
@@ -6,6 +5,7 @@ use chrono::SecondsFormat;
use chrono::Utc;
use codex_protocol::ThreadId;
use codex_protocol::models::SandboxPermissions;
use codex_utils_absolute_path::AbsolutePathBuf;
use futures::future::BoxFuture;
use serde::Serialize;
use serde::Serializer;
@@ -64,7 +64,7 @@ impl Hook {
#[serde(rename_all = "snake_case")]
pub struct HookPayload {
pub session_id: ThreadId,
pub cwd: PathBuf,
pub cwd: AbsolutePathBuf,
#[serde(skip_serializing_if = "Option::is_none")]
pub client: Option<String>,
#[serde(serialize_with = "serialize_triggered_at")]
@@ -159,12 +159,12 @@ pub enum HookEvent {
#[cfg(test)]
mod tests {
use std::path::PathBuf;
use chrono::TimeZone;
use chrono::Utc;
use codex_protocol::ThreadId;
use codex_protocol::models::SandboxPermissions;
use codex_utils_absolute_path::test_support::PathBufExt;
use codex_utils_absolute_path::test_support::test_path_buf;
use pretty_assertions::assert_eq;
use serde_json::json;
@@ -180,9 +180,10 @@ mod tests {
fn hook_payload_serializes_stable_wire_shape() {
let session_id = ThreadId::new();
let thread_id = ThreadId::new();
let cwd = test_path_buf("/tmp").abs();
let payload = HookPayload {
session_id,
cwd: PathBuf::from("tmp"),
cwd: cwd.clone(),
client: None,
triggered_at: Utc
.with_ymd_and_hms(2025, 1, 1, 0, 0, 0)
@@ -201,7 +202,7 @@ mod tests {
let actual = serde_json::to_value(payload).expect("serialize hook payload");
let expected = json!({
"session_id": session_id.to_string(),
"cwd": "tmp",
"cwd": cwd.display().to_string(),
"triggered_at": "2025-01-01T00:00:00Z",
"hook_event": {
"event_type": "after_agent",
@@ -218,9 +219,10 @@ mod tests {
#[test]
fn after_tool_use_payload_serializes_stable_wire_shape() {
let session_id = ThreadId::new();
let cwd = test_path_buf("/tmp").abs();
let payload = HookPayload {
session_id,
cwd: PathBuf::from("tmp"),
cwd: cwd.clone(),
client: None,
triggered_at: Utc
.with_ymd_and_hms(2025, 1, 1, 0, 0, 0)
@@ -256,7 +258,7 @@ mod tests {
let actual = serde_json::to_value(payload).expect("serialize hook payload");
let expected = json!({
"session_id": session_id.to_string(),
"cwd": "tmp",
"cwd": cwd.display().to_string(),
"triggered_at": "2025-01-01T00:00:00Z",
"hook_event": {
"event_type": "after_tool_use",
+8 -3
View File
@@ -81,6 +81,8 @@ pub fn notify_hook(argv: Vec<String>) -> Hook {
mod tests {
use anyhow::Result;
use codex_protocol::ThreadId;
use codex_utils_absolute_path::test_support::PathBufExt;
use codex_utils_absolute_path::test_support::test_path_buf;
use pretty_assertions::assert_eq;
use serde_json::Value;
use serde_json::json;
@@ -88,11 +90,12 @@ mod tests {
use super::*;
fn expected_notification_json() -> Value {
let cwd = test_path_buf("/Users/example/project");
json!({
"type": "agent-turn-complete",
"thread-id": "b5f6c1c2-1111-2222-3333-444455556666",
"turn-id": "12345",
"cwd": "/Users/example/project",
"cwd": cwd.display().to_string(),
"client": "codex-tui",
"input-messages": ["Rename `foo` to `bar` and update the callsites."],
"last-assistant-message": "Rename complete and verified `cargo build` succeeds.",
@@ -104,7 +107,9 @@ mod tests {
let notification = UserNotification::AgentTurnComplete {
thread_id: "b5f6c1c2-1111-2222-3333-444455556666".to_string(),
turn_id: "12345".to_string(),
cwd: "/Users/example/project".to_string(),
cwd: test_path_buf("/Users/example/project")
.display()
.to_string(),
client: Some("codex-tui".to_string()),
input_messages: vec!["Rename `foo` to `bar` and update the callsites.".to_string()],
last_assistant_message: Some(
@@ -121,7 +126,7 @@ mod tests {
fn legacy_notify_json_matches_historical_wire_shape() -> Result<()> {
let payload = HookPayload {
session_id: ThreadId::new(),
cwd: std::path::Path::new("/Users/example/project").to_path_buf(),
cwd: test_path_buf("/Users/example/project").abs(),
client: Some("codex-tui".to_string()),
triggered_at: chrono::Utc::now(),
hook_event: HookEvent::AfterAgent {