mirror of
https://github.com/openai/codex.git
synced 2026-04-24 14:45:27 +00:00
Move commit attribution to prompt guidance
- remove hook/env interception path for commit attribution\n- inject commit trailer instruction via codex_git_commit feature\n- treat command_attribution override as verbatim trailer value\n- keep blank override as opt-out and default to Codex noreply trailer
This commit is contained in:
@@ -191,6 +191,9 @@
|
||||
"child_agents_md": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"codex_git_commit": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"collab": {
|
||||
"type": "boolean"
|
||||
},
|
||||
@@ -1240,7 +1243,7 @@
|
||||
"description": "Preferred backend for storing CLI auth credentials. file (default): Use a file in the Codex home directory. keyring: Use an OS-specific keyring service. auto: Use the keyring if available, otherwise use a file."
|
||||
},
|
||||
"command_attribution": {
|
||||
"description": "Optional command attribution label for commit message co-author trailers.\n\nSet to an empty string to disable automatic command attribution.",
|
||||
"description": "Optional command attribution text for commit message co-author trailers.\n\nSet to an empty string to disable automatic command attribution.\n\nWhen set, the value is used verbatim in the `Co-authored-by:` trailer.",
|
||||
"type": "string"
|
||||
},
|
||||
"compact_prompt": {
|
||||
@@ -1279,6 +1282,9 @@
|
||||
"child_agents_md": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"codex_git_commit": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"collab": {
|
||||
"type": "boolean"
|
||||
},
|
||||
@@ -1697,4 +1703,4 @@
|
||||
},
|
||||
"title": "ConfigToml",
|
||||
"type": "object"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,6 +16,7 @@ use crate::agent::agent_status_from_event;
|
||||
use crate::analytics_client::AnalyticsEventsClient;
|
||||
use crate::analytics_client::build_track_events_context;
|
||||
use crate::apps::render_apps_section;
|
||||
use crate::command_attribution::commit_message_trailer_instruction;
|
||||
use crate::compact;
|
||||
use crate::compact::run_inline_auto_compact_task;
|
||||
use crate::compact::should_use_remote_compact_task;
|
||||
@@ -2427,6 +2428,13 @@ impl Session {
|
||||
if turn_context.features.enabled(Feature::Apps) {
|
||||
items.push(DeveloperInstructions::new(render_apps_section()).into());
|
||||
}
|
||||
if turn_context.features.enabled(Feature::CodexGitCommit)
|
||||
&& let Some(commit_message_instruction) = commit_message_trailer_instruction(
|
||||
turn_context.config.command_attribution.as_deref(),
|
||||
)
|
||||
{
|
||||
items.push(DeveloperInstructions::new(commit_message_instruction).into());
|
||||
}
|
||||
if let Some(user_instructions) = turn_context.user_instructions.as_deref() {
|
||||
items.push(
|
||||
UserInstructions {
|
||||
|
||||
@@ -1,43 +1,20 @@
|
||||
use std::collections::HashMap;
|
||||
use std::fs;
|
||||
#[cfg(unix)]
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
const DEFAULT_ATTRIBUTION_VALUE: &str = "Codex <noreply@openai.com>";
|
||||
|
||||
use crate::config::Config;
|
||||
|
||||
const DEFAULT_ATTRIBUTION_LABEL: &str = "Codex";
|
||||
const PREPARE_COMMIT_MSG_HOOK_NAME: &str = "prepare-commit-msg";
|
||||
|
||||
pub(crate) fn configure_git_hooks_env_for_config(
|
||||
env: &mut HashMap<String, String>,
|
||||
config: &Config,
|
||||
) {
|
||||
configure_git_hooks_env(
|
||||
env,
|
||||
config.codex_home.as_path(),
|
||||
config.command_attribution.as_deref(),
|
||||
);
|
||||
pub(crate) fn commit_message_trailer(config_attribution: Option<&str>) -> Option<String> {
|
||||
let value = resolve_attribution_value(config_attribution)?;
|
||||
Some(format!("Co-authored-by: {value}"))
|
||||
}
|
||||
|
||||
pub(crate) fn configure_git_hooks_env(
|
||||
env: &mut HashMap<String, String>,
|
||||
codex_home: &Path,
|
||||
pub(crate) fn commit_message_trailer_instruction(
|
||||
config_attribution: Option<&str>,
|
||||
) {
|
||||
let Some(label) = resolve_attribution_label(config_attribution) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let Ok(hooks_path) = ensure_codex_hook_scripts(codex_home, &label) else {
|
||||
return;
|
||||
};
|
||||
|
||||
set_git_runtime_config(env, "core.hooksPath", hooks_path.to_string_lossy().as_ref());
|
||||
) -> Option<String> {
|
||||
let trailer = commit_message_trailer(config_attribution)?;
|
||||
Some(format!(
|
||||
"When you write or edit a git commit message, ensure the message ends with this trailer exactly once:\n{trailer}\n\nRules:\n- Keep existing trailers and append this trailer at the end if missing.\n- Do not duplicate this trailer if it already exists.\n- Keep one blank line between the commit body and trailer block."
|
||||
))
|
||||
}
|
||||
|
||||
fn resolve_attribution_label(config_attribution: Option<&str>) -> Option<String> {
|
||||
fn resolve_attribution_value(config_attribution: Option<&str>) -> Option<String> {
|
||||
match config_attribution {
|
||||
Some(value) => {
|
||||
let trimmed = value.trim();
|
||||
@@ -47,126 +24,53 @@ fn resolve_attribution_label(config_attribution: Option<&str>) -> Option<String>
|
||||
Some(trimmed.to_string())
|
||||
}
|
||||
}
|
||||
None => Some(DEFAULT_ATTRIBUTION_LABEL.to_string()),
|
||||
None => Some(DEFAULT_ATTRIBUTION_VALUE.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
fn ensure_codex_hook_scripts(codex_home: &Path, label: &str) -> std::io::Result<PathBuf> {
|
||||
let hooks_dir = codex_home.join("hooks").join("command-attribution");
|
||||
fs::create_dir_all(&hooks_dir)?;
|
||||
|
||||
let script = build_hook_script(label);
|
||||
let hook_path = hooks_dir.join(PREPARE_COMMIT_MSG_HOOK_NAME);
|
||||
let should_write = match fs::read_to_string(&hook_path) {
|
||||
Ok(existing) => existing != script,
|
||||
Err(_) => true,
|
||||
};
|
||||
|
||||
if should_write {
|
||||
fs::write(&hook_path, script.as_bytes())?;
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
{
|
||||
let mut perms = fs::metadata(&hook_path)?.permissions();
|
||||
perms.set_mode(0o755);
|
||||
fs::set_permissions(&hook_path, perms)?;
|
||||
}
|
||||
|
||||
Ok(hooks_dir)
|
||||
}
|
||||
|
||||
fn build_hook_script(label: &str) -> String {
|
||||
let escaped_label = label.replace('\'', "'\"'\"'");
|
||||
format!(
|
||||
"#!/usr/bin/env bash\nset -euo pipefail\n\nmsg_file=\"${{1:-}}\"\nif [[ -n \"$msg_file\" && -f \"$msg_file\" ]]; then\n git interpret-trailers \\\n --in-place \\\n --if-exists doNothing \\\n --if-missing add \\\n --trailer 'Co-authored-by={escaped_label} <noreply@openai.com>' \\\n \"$msg_file\" || true\nfi\n\nunset GIT_CONFIG_COUNT\nwhile IFS='=' read -r name _; do\n case \"$name\" in\n GIT_CONFIG_KEY_*|GIT_CONFIG_VALUE_*) unset \"$name\" ;;\n esac\ndone < <(env)\n\nexisting_hooks_path=\"$(git config --path core.hooksPath 2>/dev/null || true)\"\nif [[ -z \"$existing_hooks_path\" ]]; then\n git_dir=\"$(git rev-parse --git-common-dir 2>/dev/null || git rev-parse --git-dir 2>/dev/null || true)\"\n if [[ -n \"$git_dir\" ]]; then\n existing_hooks_path=\"$git_dir/hooks\"\n fi\nfi\n\nif [[ -n \"$existing_hooks_path\" ]]; then\n existing_hook=\"$existing_hooks_path/{PREPARE_COMMIT_MSG_HOOK_NAME}\"\n if [[ -x \"$existing_hook\" && \"$existing_hook\" != \"$0\" ]]; then\n \"$existing_hook\" \"$@\"\n fi\nfi\n"
|
||||
)
|
||||
}
|
||||
|
||||
fn set_git_runtime_config(env: &mut HashMap<String, String>, key: &str, value: &str) {
|
||||
let mut index = env
|
||||
.get("GIT_CONFIG_COUNT")
|
||||
.and_then(|count| count.parse::<usize>().ok())
|
||||
.unwrap_or(0);
|
||||
|
||||
while env.contains_key(&format!("GIT_CONFIG_KEY_{index}"))
|
||||
|| env.contains_key(&format!("GIT_CONFIG_VALUE_{index}"))
|
||||
{
|
||||
index += 1;
|
||||
}
|
||||
|
||||
env.insert(format!("GIT_CONFIG_KEY_{index}"), key.to_string());
|
||||
env.insert(format!("GIT_CONFIG_VALUE_{index}"), value.to_string());
|
||||
env.insert("GIT_CONFIG_COUNT".to_string(), (index + 1).to_string());
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::configure_git_hooks_env;
|
||||
use super::configure_git_hooks_env_for_config;
|
||||
use super::resolve_attribution_label;
|
||||
use crate::config::test_config;
|
||||
use std::collections::HashMap;
|
||||
use tempfile::tempdir;
|
||||
use super::commit_message_trailer;
|
||||
use super::commit_message_trailer_instruction;
|
||||
use super::resolve_attribution_value;
|
||||
|
||||
#[test]
|
||||
fn blank_attribution_disables_hook_env_injection() {
|
||||
let tmp = tempdir().expect("create temp dir");
|
||||
let mut env = HashMap::new();
|
||||
|
||||
configure_git_hooks_env(&mut env, tmp.path(), Some(""));
|
||||
|
||||
assert!(env.is_empty());
|
||||
fn blank_attribution_disables_trailer_prompt() {
|
||||
assert_eq!(commit_message_trailer(Some("")), None);
|
||||
assert_eq!(commit_message_trailer_instruction(Some(" ")), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_attribution_injects_hooks_path() {
|
||||
let tmp = tempdir().expect("create temp dir");
|
||||
let mut env = HashMap::new();
|
||||
|
||||
configure_git_hooks_env(&mut env, tmp.path(), None);
|
||||
|
||||
assert_eq!(env.get("GIT_CONFIG_COUNT"), Some(&"1".to_string()));
|
||||
fn default_attribution_uses_codex_trailer() {
|
||||
assert_eq!(
|
||||
env.get("GIT_CONFIG_KEY_0"),
|
||||
Some(&"core.hooksPath".to_string())
|
||||
);
|
||||
assert!(
|
||||
env.get("GIT_CONFIG_VALUE_0")
|
||||
.expect("missing hooks path")
|
||||
.contains("command-attribution")
|
||||
commit_message_trailer(None).as_deref(),
|
||||
Some("Co-authored-by: Codex <noreply@openai.com>")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_label_handles_default_custom_and_blank() {
|
||||
assert_eq!(resolve_attribution_label(None), Some("Codex".to_string()));
|
||||
fn resolve_value_handles_default_custom_and_blank() {
|
||||
assert_eq!(
|
||||
resolve_attribution_label(Some("MyAgent")),
|
||||
resolve_attribution_value(None),
|
||||
Some("Codex <noreply@openai.com>".to_string())
|
||||
);
|
||||
assert_eq!(
|
||||
resolve_attribution_value(Some("MyAgent <me@example.com>")),
|
||||
Some("MyAgent <me@example.com>".to_string())
|
||||
);
|
||||
assert_eq!(
|
||||
resolve_attribution_value(Some("MyAgent")),
|
||||
Some("MyAgent".to_string())
|
||||
);
|
||||
assert_eq!(resolve_attribution_label(Some(" ")), None);
|
||||
assert_eq!(resolve_attribution_value(Some(" ")), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn helper_configures_env_from_config() {
|
||||
let tmp = tempdir().expect("create temp dir");
|
||||
let mut config = test_config();
|
||||
config.codex_home = tmp.path().to_path_buf();
|
||||
config.command_attribution = Some("AgentX".to_string());
|
||||
let mut env = HashMap::new();
|
||||
|
||||
configure_git_hooks_env_for_config(&mut env, &config);
|
||||
|
||||
assert_eq!(env.get("GIT_CONFIG_COUNT"), Some(&"1".to_string()));
|
||||
assert_eq!(
|
||||
env.get("GIT_CONFIG_KEY_0"),
|
||||
Some(&"core.hooksPath".to_string())
|
||||
);
|
||||
assert!(
|
||||
env.get("GIT_CONFIG_VALUE_0")
|
||||
.expect("missing hooks path")
|
||||
.contains("command-attribution")
|
||||
);
|
||||
fn instruction_mentions_trailer_and_omits_generated_with() {
|
||||
let instruction = commit_message_trailer_instruction(Some("AgentX <agent@example.com>"))
|
||||
.expect("instruction expected");
|
||||
assert!(instruction.contains("Co-authored-by: AgentX <agent@example.com>"));
|
||||
assert!(instruction.contains("exactly once"));
|
||||
assert!(!instruction.contains("Generated-with"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -187,11 +187,11 @@ pub struct Config {
|
||||
/// Compact prompt override.
|
||||
pub compact_prompt: Option<String>,
|
||||
|
||||
/// Optional command attribution label for commit message co-author trailers.
|
||||
/// Optional command attribution text for commit message co-author trailers.
|
||||
///
|
||||
/// - `None`: use default attribution ("Codex")
|
||||
/// - `None`: use default attribution (`Codex <noreply@openai.com>`)
|
||||
/// - `Some("")` or whitespace-only: disable command attribution
|
||||
/// - `Some("...")`: use the provided attribution text
|
||||
/// - `Some("...")`: use the provided attribution text verbatim
|
||||
pub command_attribution: Option<String>,
|
||||
|
||||
/// Optional external notifier command. When set, Codex will spawn this
|
||||
@@ -903,7 +903,7 @@ pub struct ConfigToml {
|
||||
/// Compact prompt used for history compaction.
|
||||
pub compact_prompt: Option<String>,
|
||||
|
||||
/// Optional command attribution label for commit message co-author trailers.
|
||||
/// Optional command attribution text for commit message co-author trailers.
|
||||
///
|
||||
/// Set to an empty string to disable automatic command attribution.
|
||||
pub command_attribution: Option<String>,
|
||||
|
||||
@@ -103,6 +103,8 @@ pub enum Feature {
|
||||
RemoteModels,
|
||||
/// Experimental shell snapshotting.
|
||||
ShellSnapshot,
|
||||
/// Enable git commit attribution guidance via model instructions.
|
||||
CodexGitCommit,
|
||||
/// Enable runtime metrics snapshots via a manual reader.
|
||||
RuntimeMetrics,
|
||||
/// Persist rollout metadata to a local SQLite database.
|
||||
@@ -449,6 +451,12 @@ pub const FEATURES: &[FeatureSpec] = &[
|
||||
default_enabled: false,
|
||||
},
|
||||
// Experimental program. Rendered in the `/experimental` menu for users.
|
||||
FeatureSpec {
|
||||
id: Feature::CodexGitCommit,
|
||||
key: "codex_git_commit",
|
||||
stage: Stage::UnderDevelopment,
|
||||
default_enabled: false,
|
||||
},
|
||||
FeatureSpec {
|
||||
id: Feature::RuntimeMetrics,
|
||||
key: "runtime_metrics",
|
||||
|
||||
@@ -120,10 +120,11 @@ impl ShellSnapshot {
|
||||
.join(format!("{session_id}.{extension}"));
|
||||
|
||||
// Clean the (unlikely) leaked snapshot files.
|
||||
let codex_home = codex_home.to_path_buf();
|
||||
let cleanup_codex_home = codex_home.to_path_buf();
|
||||
let cleanup_session_id = session_id;
|
||||
tokio::spawn(async move {
|
||||
if let Err(err) = cleanup_stale_snapshots(&codex_home, cleanup_session_id).await {
|
||||
if let Err(err) = cleanup_stale_snapshots(&cleanup_codex_home, cleanup_session_id).await
|
||||
{
|
||||
tracing::warn!("Failed to clean up shell snapshots: {err:?}");
|
||||
}
|
||||
});
|
||||
|
||||
@@ -6,7 +6,6 @@ use codex_protocol::models::ShellToolCallParams;
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::codex::TurnContext;
|
||||
use crate::command_attribution::configure_git_hooks_env_for_config;
|
||||
use crate::exec::ExecParams;
|
||||
use crate::exec_env::create_env;
|
||||
use crate::exec_policy::ExecApprovalRequest;
|
||||
@@ -251,7 +250,6 @@ impl ShellHandler {
|
||||
};
|
||||
|
||||
let mut exec_params = exec_params;
|
||||
configure_git_hooks_env_for_config(&mut exec_params.env, turn.config.as_ref());
|
||||
let dependency_env = session.dependency_env().await;
|
||||
if !dependency_env.is_empty() {
|
||||
exec_params.env.extend(dependency_env);
|
||||
|
||||
@@ -12,7 +12,6 @@ use tokio::time::Duration;
|
||||
use tokio::time::Instant;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use crate::command_attribution::configure_git_hooks_env_for_config;
|
||||
use crate::exec_env::create_env;
|
||||
use crate::exec_policy::ExecApprovalRequest;
|
||||
use crate::protocol::ExecCommandSource;
|
||||
@@ -518,11 +517,10 @@ impl UnifiedExecProcessManager {
|
||||
cwd: PathBuf,
|
||||
context: &UnifiedExecContext,
|
||||
) -> Result<UnifiedExecProcess, UnifiedExecError> {
|
||||
let mut env = create_env(
|
||||
let env = create_env(
|
||||
&context.turn.shell_environment_policy,
|
||||
Some(context.session.conversation_id),
|
||||
);
|
||||
configure_git_hooks_env_for_config(&mut env, context.turn.config.as_ref());
|
||||
let env = apply_unified_exec_env(env);
|
||||
let mut orchestrator = ToolOrchestrator::new();
|
||||
let mut runtime = UnifiedExecRuntime::new(self);
|
||||
|
||||
Reference in New Issue
Block a user