From c61e04a5fc7d9a19ee16a89005302523d3bcbbaa Mon Sep 17 00:00:00 2001 From: Abhijeet Prasad Date: Wed, 25 Nov 2026 10:48:39 -0500 Subject: [PATCH 1/4] Surface Codex hook activation failures and accept null feature values Codex 0.172.0 returns `features.network_proxy = null` from `config/read`, which failed to deserialize into `BTreeMap` and aborted hook activation. Only the `hooks`/`codex_hooks` toggles are now interpreted. Activation errors now inline their cause chain, and both app-server probes capture the tail of Codex's stderr so failures such as an older Codex rejecting `--no-daemon` explain themselves instead of reporting only the generic activation message. Fixes SDK-992 Fixes SDK-990 --- bt-daemon/src/codex_hooks/config.rs | 10 ++-- bt-daemon/src/codex_hooks/mod.rs | 26 +++++++-- bt-daemon/src/codex_hooks/stderr.rs | 90 +++++++++++++++++++++++++++++ bt-daemon/src/codex_hooks/tests.rs | 51 ++++++++++++++++ 4 files changed, 167 insertions(+), 10 deletions(-) create mode 100644 bt-daemon/src/codex_hooks/stderr.rs diff --git a/bt-daemon/src/codex_hooks/config.rs b/bt-daemon/src/codex_hooks/config.rs index c3d5b48f..4d17a9ca 100644 --- a/bt-daemon/src/codex_hooks/config.rs +++ b/bt-daemon/src/codex_hooks/config.rs @@ -1,15 +1,17 @@ use serde::Deserialize; -use std::collections::BTreeMap; +use serde_json::Value; #[derive(Deserialize)] pub(super) struct Config { + // Codex feature values are not all booleans (e.g. `network_proxy: null`), + // so only the hook toggles are interpreted and everything else is ignored. #[serde(default)] - pub(super) features: BTreeMap, + features: Value, } impl Config { pub(super) fn hooks_enabled(&self) -> bool { - self.features.get("hooks") != Some(&false) - && self.features.get("codex_hooks") != Some(&false) + let disabled = |key| self.features.get(key) == Some(&Value::Bool(false)); + !disabled("hooks") && !disabled("codex_hooks") } } diff --git a/bt-daemon/src/codex_hooks/mod.rs b/bt-daemon/src/codex_hooks/mod.rs index 432d2fb5..d48b63a7 100644 --- a/bt-daemon/src/codex_hooks/mod.rs +++ b/bt-daemon/src/codex_hooks/mod.rs @@ -38,12 +38,14 @@ mod plugin; mod plugin_list; mod plugin_marketplace; mod response; +mod stderr; mod transport; mod trust_state; use config_read::ConfigRead; use hooks_list::HooksList; use plugin_list::PluginList; +use stderr::StderrTail; use transport::request; use trust_state::TrustState; @@ -57,10 +59,11 @@ pub(crate) async fn activate() -> anyhow::Result<()> { .kill_on_drop(true) .stdin(Stdio::piped()) .stdout(Stdio::piped()) - .stderr(Stdio::null()); + .stderr(Stdio::piped()); let mut child = command .spawn() .context("start Codex to activate tracing hooks")?; + let stderr = StderrTail::capture(&mut child); let result = tokio::time::timeout(TIMEOUT, async { let mut stdin = child.stdin.take().context("Codex stdin unavailable")?; @@ -136,8 +139,17 @@ pub(crate) async fn activate() -> anyhow::Result<()> { .await; let _ = child.kill().await; match result { - Ok(result) => result.context("Codex plugin installed, but hook activation failed"), - Err(_) => Err(anyhow!("Codex hook activation timed out after 5 seconds")), + // Inline the cause chain: callers may print only the top-level message. + Ok(result) => stderr.attach(result).await.map_err(|error| { + anyhow!("Codex plugin installed, but hook activation failed: {error:#}") + }), + Err(_) => { + stderr + .attach(Err(anyhow!( + "Codex hook activation timed out after 5 seconds" + ))) + .await + } } } @@ -159,10 +171,11 @@ pub(crate) async fn run_trust_override( .kill_on_drop(true) .stdin(Stdio::piped()) .stdout(Stdio::piped()) - .stderr(Stdio::null()); + .stderr(Stdio::piped()); let mut child = command .spawn() .context("start Codex to prepare managed hook trust")?; + let stderr = StderrTail::capture(&mut child); let result = tokio::time::timeout(TIMEOUT, async { let mut stdin = child.stdin.take().context("Codex stdin unavailable")?; @@ -185,12 +198,13 @@ pub(crate) async fn run_trust_override( }) .await; let _ = child.kill().await; - match result { + let result = match result { Ok(result) => result, Err(_) => Err(anyhow!( "Codex managed hook trust inspection timed out after 5 seconds" )), - } + }; + stderr.attach(result).await } /// Validate the complete installed file, including the other platform's command, diff --git a/bt-daemon/src/codex_hooks/stderr.rs b/bt-daemon/src/codex_hooks/stderr.rs new file mode 100644 index 00000000..aec6d91d --- /dev/null +++ b/bt-daemon/src/codex_hooks/stderr.rs @@ -0,0 +1,90 @@ +//! Keep the tail of Codex's stderr so probe failures can explain themselves, +//! e.g. an older Codex rejecting `--no-daemon` and exiting before replying. + +use anyhow::anyhow; +use std::time::Duration; +use tokio::io::{AsyncRead, AsyncReadExt}; +use tokio::task::JoinHandle; + +const TAIL_BYTES: usize = 4 * 1024; +const DRAIN_TIMEOUT: Duration = Duration::from_millis(500); + +pub(super) struct StderrTail(Option>>); + +impl StderrTail { + /// Drain the pipe continuously so Codex never blocks on a full stderr + /// buffer, retaining only the last `TAIL_BYTES`. + pub(super) fn capture(child: &mut tokio::process::Child) -> Self { + Self(child.stderr.take().map(|stderr| tokio::spawn(tail(stderr)))) + } + + /// Call after the child is killed so the pipe reaches EOF. The bounded + /// wait covers descendants that may still hold the pipe open. + pub(super) async fn attach(self, result: anyhow::Result) -> anyhow::Result { + let Err(error) = result else { + if let Some(task) = self.0 { + task.abort(); + } + return result; + }; + let Some(mut task) = self.0 else { + return Err(error); + }; + let bytes = match tokio::time::timeout(DRAIN_TIMEOUT, &mut task).await { + Ok(Ok(bytes)) => bytes, + _ => { + task.abort(); + return Err(error); + } + }; + Err(with_stderr(error, &bytes)) + } +} + +async fn tail(mut stderr: impl AsyncRead + Unpin) -> Vec { + let mut kept = Vec::new(); + let mut chunk = [0; 1024]; + while let Ok(read @ 1..) = stderr.read(&mut chunk).await { + kept.extend_from_slice(&chunk[..read]); + if kept.len() > TAIL_BYTES { + kept.drain(..kept.len() - TAIL_BYTES); + } + } + kept +} + +fn with_stderr(error: anyhow::Error, bytes: &[u8]) -> anyhow::Error { + let text = String::from_utf8_lossy(bytes); + let text = text.trim(); + if text.is_empty() { + return error; + } + anyhow!("{error:#}\nCodex stderr:\n{text}") +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn tail_keeps_only_the_last_bytes() { + let input = [b"x".repeat(TAIL_BYTES * 3), b"end".to_vec()].concat(); + let kept = tail(input.as_slice()).await; + assert_eq!(kept.len(), TAIL_BYTES); + assert!(kept.ends_with(b"end")); + } + + #[test] + fn stderr_is_appended_only_when_present() { + let error = with_stderr( + anyhow!("Codex closed the probe stream"), + b"error: unexpected argument '--no-daemon' found\n", + ); + assert_eq!( + error.to_string(), + "Codex closed the probe stream\nCodex stderr:\nerror: unexpected argument '--no-daemon' found" + ); + let error = with_stderr(anyhow!("Codex closed the probe stream"), b" \n"); + assert_eq!(error.to_string(), "Codex closed the probe stream"); + } +} diff --git a/bt-daemon/src/codex_hooks/tests.rs b/bt-daemon/src/codex_hooks/tests.rs index 0ecc412b..484483cd 100644 --- a/bt-daemon/src/codex_hooks/tests.rs +++ b/bt-daemon/src/codex_hooks/tests.rs @@ -53,3 +53,54 @@ async fn rpc_ignores_notifications_and_reports_unsupported_methods() { "hooks/list" ); } + +#[test] +fn config_read_accepts_non_boolean_feature_values() { + let read: ConfigRead = serde_json::from_value(json!({ + "config": {"features": {"network_proxy": null, "other": {"nested": 1}, "hooks": true}} + })) + .unwrap(); + assert!(read.config.hooks_enabled()); + for features in [json!(null), json!({})] { + let read: ConfigRead = + serde_json::from_value(json!({"config": {"features": features}})).unwrap(); + assert!(read.config.hooks_enabled()); + } + let read: ConfigRead = serde_json::from_value(json!({"config": {}})).unwrap(); + assert!(read.config.hooks_enabled()); +} + +#[test] +fn config_read_respects_disabled_hook_features() { + for key in ["hooks", "codex_hooks"] { + let read: ConfigRead = serde_json::from_value(json!({ + "config": {"features": {"network_proxy": null, key: false}} + })) + .unwrap(); + assert!(!read.config.hooks_enabled(), "{key}"); + } +} + +#[cfg(unix)] +#[tokio::test] +async fn probe_failures_include_codex_stderr() { + use std::os::unix::fs::PermissionsExt; + let dir = tempfile::tempdir().unwrap(); + let codex = dir.path().join("codex"); + std::fs::write( + &codex, + "#!/bin/sh\necho \"error: unexpected argument '--no-daemon' found\" >&2\nexit 2\n", + ) + .unwrap(); + std::fs::set_permissions(&codex, std::fs::Permissions::from_mode(0o755)).unwrap(); + let error = run_trust_override(codex.as_os_str(), dir.path(), &[], "unused") + .await + .unwrap_err() + .to_string(); + // The transport error races Codex's exit (closed stream vs broken pipe); + // either way the stderr explanation must be present. + assert!( + error.contains("unexpected argument '--no-daemon' found"), + "{error}" + ); +} From 106f9a7d7910fc508b7f56413ac1a13ddfad257e Mon Sep 17 00:00:00 2001 From: Abhijeet Prasad Date: Wed, 25 Nov 2026 11:04:26 -0500 Subject: [PATCH 2/4] Model Codex hook feature toggles as typed fields and consolidate tests Per AGENTS.md, known config fields must not be read from serde_json::Value. Unrelated feature entries are skipped by Serde instead. --- bt-daemon/src/codex_hooks/config.rs | 20 +++++++++----- bt-daemon/src/codex_hooks/stderr.rs | 14 ---------- bt-daemon/src/codex_hooks/tests.rs | 43 ++++++++++++++--------------- 3 files changed, 33 insertions(+), 44 deletions(-) diff --git a/bt-daemon/src/codex_hooks/config.rs b/bt-daemon/src/codex_hooks/config.rs index 4d17a9ca..6ac06279 100644 --- a/bt-daemon/src/codex_hooks/config.rs +++ b/bt-daemon/src/codex_hooks/config.rs @@ -1,17 +1,23 @@ use serde::Deserialize; -use serde_json::Value; #[derive(Deserialize)] pub(super) struct Config { - // Codex feature values are not all booleans (e.g. `network_proxy: null`), - // so only the hook toggles are interpreted and everything else is ignored. - #[serde(default)] - features: Value, + features: Option, +} + +/// Only the hook toggles are modeled. Serde skips every other feature entry, +/// whose values are not all booleans (Codex 0.172.0 reports +/// `network_proxy: null`). +#[derive(Deserialize)] +struct Features { + hooks: Option, + codex_hooks: Option, } impl Config { pub(super) fn hooks_enabled(&self) -> bool { - let disabled = |key| self.features.get(key) == Some(&Value::Bool(false)); - !disabled("hooks") && !disabled("codex_hooks") + self.features.as_ref().is_none_or(|features| { + features.hooks != Some(false) && features.codex_hooks != Some(false) + }) } } diff --git a/bt-daemon/src/codex_hooks/stderr.rs b/bt-daemon/src/codex_hooks/stderr.rs index aec6d91d..2939bf7a 100644 --- a/bt-daemon/src/codex_hooks/stderr.rs +++ b/bt-daemon/src/codex_hooks/stderr.rs @@ -73,18 +73,4 @@ mod tests { assert_eq!(kept.len(), TAIL_BYTES); assert!(kept.ends_with(b"end")); } - - #[test] - fn stderr_is_appended_only_when_present() { - let error = with_stderr( - anyhow!("Codex closed the probe stream"), - b"error: unexpected argument '--no-daemon' found\n", - ); - assert_eq!( - error.to_string(), - "Codex closed the probe stream\nCodex stderr:\nerror: unexpected argument '--no-daemon' found" - ); - let error = with_stderr(anyhow!("Codex closed the probe stream"), b" \n"); - assert_eq!(error.to_string(), "Codex closed the probe stream"); - } } diff --git a/bt-daemon/src/codex_hooks/tests.rs b/bt-daemon/src/codex_hooks/tests.rs index 484483cd..a76426c5 100644 --- a/bt-daemon/src/codex_hooks/tests.rs +++ b/bt-daemon/src/codex_hooks/tests.rs @@ -55,29 +55,26 @@ async fn rpc_ignores_notifications_and_reports_unsupported_methods() { } #[test] -fn config_read_accepts_non_boolean_feature_values() { - let read: ConfigRead = serde_json::from_value(json!({ - "config": {"features": {"network_proxy": null, "other": {"nested": 1}, "hooks": true}} - })) - .unwrap(); - assert!(read.config.hooks_enabled()); - for features in [json!(null), json!({})] { - let read: ConfigRead = - serde_json::from_value(json!({"config": {"features": features}})).unwrap(); - assert!(read.config.hooks_enabled()); - } - let read: ConfigRead = serde_json::from_value(json!({"config": {}})).unwrap(); - assert!(read.config.hooks_enabled()); -} - -#[test] -fn config_read_respects_disabled_hook_features() { - for key in ["hooks", "codex_hooks"] { - let read: ConfigRead = serde_json::from_value(json!({ - "config": {"features": {"network_proxy": null, key: false}} - })) - .unwrap(); - assert!(!read.config.hooks_enabled(), "{key}"); +fn config_read_ignores_unrelated_features_and_honors_hook_toggles() { + // Codex 0.172.0 reports `network_proxy: null` even for a default config. + for (config, enabled) in [ + ( + json!({"features": {"network_proxy": null, "other": {"nested": 1}}}), + true, + ), + (json!({"features": null}), true), + (json!({}), true), + ( + json!({"features": {"network_proxy": null, "hooks": false}}), + false, + ), + ( + json!({"features": {"network_proxy": null, "codex_hooks": false}}), + false, + ), + ] { + let read: ConfigRead = serde_json::from_value(json!({"config": config})).unwrap(); + assert_eq!(read.config.hooks_enabled(), enabled, "{config}"); } } From b59865a1bbb082dccf7e454d7f12a934fd790cbc Mon Sep 17 00:00:00 2001 From: Abhijeet Prasad Date: Wed, 25 Nov 2026 11:17:08 -0500 Subject: [PATCH 3/4] Add a real-Codex hook activation contract test to CI Hook activation (`bt trace install/update codex`) was never exercised against a real Codex, so Codex 0.172.0's `features.network_proxy = null` reached users. The new ignored test installs the plugin into an isolated CODEX_HOME and requires full activation; CI runs it against the latest Codex on Linux, macOS, and Windows. It fails on main with the SDK-992 error. Also record the lesson in AGENTS.md (model only the agent-owned fields we read) and the add-coding-agent-setup skill (surface agent errors; add a real-agent contract test for setup protocols). --- .../skills/add-coding-agent-setup/SKILL.md | 9 +++++ .github/workflows/ci.yml | 6 ++++ AGENTS.md | 6 ++++ bt-daemon/src/codex_hooks/mod.rs | 9 +++-- bt-daemon/src/codex_hooks/tests.rs | 33 +++++++++++++++++++ bt-daemon/tests/support/README.md | 9 +++++ 6 files changed, 70 insertions(+), 2 deletions(-) diff --git a/.agents/skills/add-coding-agent-setup/SKILL.md b/.agents/skills/add-coding-agent-setup/SKILL.md index c315a75a..a5648d1b 100644 --- a/.agents/skills/add-coding-agent-setup/SKILL.md +++ b/.agents/skills/add-coding-agent-setup/SKILL.md @@ -22,9 +22,18 @@ considering setup complete. - Keep generated hook definitions stable when the agent uses definition-based trust, and preserve the agent's normal review boundary. - Provide a reversible disable or uninstall path. +- When setup talks to the agent's own API or protocol (for example Codex's + app-server), report the underlying error and the agent's stderr, not only a + generic setup failure. ## Verify completion Test setup in an isolated home and configuration tree, including first install, repeat setup, route changes, existing unrelated configuration, disablement, missing dependencies, and a real agent launch using the installed adapter. + +If setup calls the agent's API or protocol, add a credential-free contract test +that runs that setup path against the real agent in an isolated home, and run it +in CI against the latest agent release. Agent releases can break setup without +any change on our side. See +`codex_hooks::tests::activation_succeeds_against_real_codex`. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index fdcf90e5..88cf73de 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -440,6 +440,12 @@ jobs: run: cargo build --manifest-path bt-daemon/Cargo.toml --all-features --locked - name: Test daemon run: cargo test --manifest-path bt-daemon/Cargo.toml --all-features --locked + # `bt trace install/update codex` activation against the latest Codex, + # in an isolated CODEX_HOME. Needs no credentials. + - name: Check Codex hook activation contract + env: + CODEX_BIN: ${{ runner.temp }}/coding-agents/node_modules/.bin/codex${{ matrix.agent_suffix }} + run: cargo test --manifest-path bt-daemon/Cargo.toml --all-features --locked --lib -- --ignored --exact codex_hooks::tests::activation_succeeds_against_real_codex - name: Test coding-agent integrations with deterministic inference env: BT_AGENT_INFERENCE_MODE: mock diff --git a/AGENTS.md b/AGENTS.md index 32b6cc20..12665c03 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -53,6 +53,12 @@ that flexibility; do not use an opaque JSON fallback for a known schema merely to avoid modeling it. Preserve native format variants and unknown extensions explicitly when introducing shared types. +For responses and configuration owned by an external agent, model only the +fields we read, as optional typed fields, and let Serde skip the rest. Never +decode an agent-owned open-ended collection into a closed type such as +`BTreeMap`: one new value shape in an agent release then fails the +whole response (Codex 0.172.0 added `features.network_proxy = null`). + Put shared schema interpretation, validated lookup, lossless edits, and common projections on the type that owns those rules. Keep filesystem, credential, process, and event-ordering policy in the services that coordinate them. Organize diff --git a/bt-daemon/src/codex_hooks/mod.rs b/bt-daemon/src/codex_hooks/mod.rs index d48b63a7..5a79ade1 100644 --- a/bt-daemon/src/codex_hooks/mod.rs +++ b/bt-daemon/src/codex_hooks/mod.rs @@ -50,9 +50,14 @@ use transport::request; use trust_state::TrustState; pub(crate) async fn activate() -> anyhow::Result<()> { + activate_with(crate::subprocess::background_command("codex")).await +} + +/// Takes the Codex command so the real-Codex contract test can isolate +/// `CODEX_HOME` and select `CODEX_BIN`. +async fn activate_with(command: std::process::Command) -> anyhow::Result<()> { let cwd = std::env::current_dir()?; - let mut command: tokio::process::Command = - crate::subprocess::background_command("codex").into(); + let mut command: tokio::process::Command = command.into(); command .args(["--no-daemon", "app-server", "--stdio"]) .current_dir(&cwd) diff --git a/bt-daemon/src/codex_hooks/tests.rs b/bt-daemon/src/codex_hooks/tests.rs index a76426c5..44beb604 100644 --- a/bt-daemon/src/codex_hooks/tests.rs +++ b/bt-daemon/src/codex_hooks/tests.rs @@ -101,3 +101,36 @@ async fn probe_failures_include_codex_stderr() { "{error}" ); } + +/// Contract test against a real Codex binary: setup must fully activate the +/// packaged hooks in an isolated home. This exercises every app-server call +/// setup makes, so protocol drift (e.g. Codex 0.172.0 reporting +/// `features.network_proxy = null`) fails CI instead of user setups. +#[tokio::test] +#[ignore = "requires the Codex CLI (CODEX_BIN or codex on PATH)"] +async fn activation_succeeds_against_real_codex() { + let program = std::env::var_os("CODEX_BIN").unwrap_or_else(|| "codex".into()); + let home = tempfile::tempdir().unwrap(); + let codex = || { + let mut command = crate::subprocess::background_command(&program); + command.env("CODEX_HOME", home.path()); + command + }; + let marketplace = Path::new(env!("CARGO_MANIFEST_DIR")) + .parent() + .unwrap() + .join("src/plugins/codex/content"); + let marketplace = marketplace.to_str().unwrap(); + for args in [ + ["plugin", "marketplace", "add", marketplace].as_slice(), + &["plugin", "add", PLUGIN], + ] { + let output = codex().args(args).output().unwrap(); + assert!( + output.status.success(), + "codex {args:?}: {}", + String::from_utf8_lossy(&output.stderr) + ); + } + activate_with(codex()).await.unwrap(); +} diff --git a/bt-daemon/tests/support/README.md b/bt-daemon/tests/support/README.md index d26838c2..320c5169 100644 --- a/bt-daemon/tests/support/README.md +++ b/bt-daemon/tests/support/README.md @@ -24,6 +24,15 @@ executables. To run one agent, add a test-name filter before `--` (for example, `codex`). The ordinary Rust suite covers translators and daemon behavior without installing agents. +`bt trace install/update codex` hook activation has a separate real-Codex +contract test in the library tests. It installs the plugin into an isolated +`CODEX_HOME` and needs no credentials: + +```bash +cargo test --manifest-path bt-daemon/Cargo.toml --all-features --locked --lib \ + -- --ignored --exact codex_hooks::tests::activation_succeeds_against_real_codex +``` + ## Test layers - `server` binds an Axum router to an ephemeral address and manages its lifetime. From f3d2b7ac5f6010b390965f4da5aa98cbe0bbcedb Mon Sep 17 00:00:00 2001 From: Abhijeet Prasad Date: Wed, 25 Nov 2026 11:18:22 -0500 Subject: [PATCH 4/4] Make the agent-owned schema rule in AGENTS.md agent-neutral --- AGENTS.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 12665c03..2a80ec41 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -56,8 +56,8 @@ explicitly when introducing shared types. For responses and configuration owned by an external agent, model only the fields we read, as optional typed fields, and let Serde skip the rest. Never decode an agent-owned open-ended collection into a closed type such as -`BTreeMap`: one new value shape in an agent release then fails the -whole response (Codex 0.172.0 added `features.network_proxy = null`). +`BTreeMap`: a single new key or value type in an agent release, +such as a `null`, then fails the whole response. Put shared schema interpretation, validated lookup, lossless edits, and common projections on the type that owns those rules. Keep filesystem, credential,