Skip to content
Merged
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
9 changes: 9 additions & 0 deletions .agents/skills/add-coding-agent-setup/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
6 changes: 6 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 6 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<String, bool>`: 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,
process, and event-ordering policy in the services that coordinate them. Organize
Expand Down
18 changes: 13 additions & 5 deletions bt-daemon/src/codex_hooks/config.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,23 @@
use serde::Deserialize;
use std::collections::BTreeMap;

#[derive(Deserialize)]
pub(super) struct Config {
#[serde(default)]
pub(super) features: BTreeMap<String, bool>,
features: Option<Features>,
}

/// 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<bool>,
codex_hooks: Option<bool>,
}

impl Config {
pub(super) fn hooks_enabled(&self) -> bool {
self.features.get("hooks") != Some(&false)
&& self.features.get("codex_hooks") != Some(&false)
self.features.as_ref().is_none_or(|features| {
features.hooks != Some(false) && features.codex_hooks != Some(false)
})
}
}
35 changes: 27 additions & 8 deletions bt-daemon/src/codex_hooks/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,29 +38,37 @@ 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;

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)
.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")?;
Expand Down Expand Up @@ -136,8 +144,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
}
}
}

Expand All @@ -159,10 +176,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")?;
Expand All @@ -185,12 +203,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,
Expand Down
76 changes: 76 additions & 0 deletions bt-daemon/src/codex_hooks/stderr.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
//! 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<JoinHandle<Vec<u8>>>);

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<T>(self, result: anyhow::Result<T>) -> anyhow::Result<T> {
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<u8> {
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"));
}
}
81 changes: 81 additions & 0 deletions bt-daemon/src/codex_hooks/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,3 +53,84 @@ async fn rpc_ignores_notifications_and_reports_unsupported_methods() {
"hooks/list"
);
}

#[test]
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}");
}
}

#[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}"
);
}

/// 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();
}
9 changes: 9 additions & 0 deletions bt-daemon/tests/support/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Loading