Trust the bundled Memory session hook without saved hashes (#62112)

## Why

The bundled Memory hook needs to supply context at startup and after compaction without requiring saved hook trust.

## What changed

Recognize the exact bundled Memory `SessionStart` declaration as a built-in hook: the `^(startup|compact)$` matcher, `codex_apps` server, `codex_dream_memory.get_mec` tool, and empty input. Carry the expected app connector identity through discovery for dispatch checks, and hide this built-in hook from hook listings while preserving other plugin hooks.

## Testing

Add coverage for exact declaration matching, hook listings without an Apps connection, and a scenario snapshot verifying memory context injection at startup and after compaction without saved trust.

GitOrigin-RevId: edc0e8ffa955227328345f46afecc2a868c0be49
This commit is contained in:
nvogt-oai
2026-11-17 21:40:36 +00:00
committed by copyberry
parent 8fca6ffb92
commit 39a7b53fa4
8 changed files with 305 additions and 11 deletions
@@ -970,15 +970,24 @@ async fn hooks_list_shows_discovered_plugin_mcp_tool_hook() -> Result<()> {
Ok(())
}
#[test_case::test_case("browser", "node_repl"; "node_repl")]
#[test_case::test_case("unified-computer-use", "cua_repl"; "cua_repl")]
#[test_case::test_case("browser", "node_repl", "turn_ended", HookEventName::Stop, None; "node_repl")]
#[test_case::test_case("unified-computer-use", "cua_repl", "turn_ended", HookEventName::Stop, None; "cua_repl")]
#[test_case::test_case("codex-dream-memory", "codex_apps", "codex_dream_memory.get_mec", HookEventName::SessionStart, Some("^(startup|compact)$"); "memory_without_apps_connection")]
#[tokio::test]
async fn hooks_list_hides_builtin_cleanup_and_preserves_other_plugin_hooks(
plugin_name: &str,
server: &str,
tool: &str,
event_name: HookEventName,
matcher: Option<&str>,
) -> Result<()> {
let codex_home = TempDir::new()?;
let cwd = TempDir::new()?;
let (event_key, event_wire) = match event_name {
HookEventName::Stop => ("stop", "Stop"),
HookEventName::SessionStart => ("session_start", "SessionStart"),
_ => unreachable!("test event"),
};
let plugin_id = format!("{plugin_name}@openai-bundled");
let plugin_root = codex_home
.path()
@@ -993,8 +1002,8 @@ async fn hooks_list_hides_builtin_cleanup_and_preserves_other_plugin_hooks(
std::fs::write(
plugin_root.join("hooks/hooks.json"),
serde_json::to_vec(&serde_json::json!({
"hooks": { "Stop": [{ "hooks": [
{ "type": "mcp_tool", "server": server, "tool": "turn_ended" },
"hooks": { (event_wire): [{ "matcher": matcher, "hooks": [
{ "type": "mcp_tool", "server": server, "tool": tool },
{ "type": "command", "command": ordinary_command, "timeout": 5 },
] }] },
}))?,
@@ -1009,7 +1018,7 @@ hooks = true
[plugins."{plugin_id}"]
enabled = true
[hooks.state."{plugin_id}:hooks/hooks.json:stop:0:1"]
[hooks.state."{plugin_id}:hooks/hooks.json:{event_key}:0:1"]
enabled = false
"#
),
@@ -1036,13 +1045,13 @@ enabled = false
vec![HooksListEntry {
cwd: cwd.path().to_path_buf(),
hooks: vec![HookMetadata {
key: format!("{plugin_id}:hooks/hooks.json:stop:0:1"),
event_name: HookEventName::Stop,
key: format!("{plugin_id}:hooks/hooks.json:{event_key}:0:1"),
event_name,
handler: HookHandlerMetadata::Command {
command: ordinary_command.to_string(),
r#async: false,
},
matcher: None,
matcher: matcher.map(str::to_string),
timeout_sec: 5,
status_message: None,
additional_context_limit: None,
+3
View File
@@ -1,5 +1,8 @@
//! Multi-turn Astra scenarios snapshot the model-visible request history of shipped features.
#[path = "scenarios_bundled_app_hooks.rs"]
mod bundled_app_hooks;
#[path = "scenarios_turn_input_agent_message.rs"]
mod turn_input_agent_message;
@@ -0,0 +1,130 @@
#![cfg(test)]
//! The bundled Memory hook injects context at startup and after compaction without saved trust.
use super::*;
use core_test_support::apps_test_server::AppsTestServer;
use core_test_support::apps_test_server::recorded_apps_tool_calls;
use pretty_assertions::assert_eq;
use std::sync::Mutex;
use wiremock::Mock;
use wiremock::Request;
use wiremock::ResponseTemplate;
use wiremock::matchers::body_partial_json;
use wiremock::matchers::method;
use wiremock::matchers::path;
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn bundled_memory_hook_injects_context() -> Result<()> {
skip_if_no_network!(Ok(()));
let connector_id = "connector_openai_codex_dream_memory";
let server = start_mock_server().await;
let apps = AppsTestServer::mount_with_tools(&server, Arc::new(Mutex::new(vec![json!({
"name": "codex_dream_memory.get_mec",
"description": "Read memory context.",
"inputSchema": { "type": "object", "properties": {} },
"annotations": { "readOnlyHint": true },
"_meta": {
"connector_id": connector_id,
"connector_name": "Memory",
"ui": { "visibility": ["app"] },
"_codex_apps": {
"resource_uri": format!("connector://{connector_id}/tools/codex_dream_memory.get_mec"),
"contains_mcp_source": true,
"connector_id": connector_id,
},
},
})]))).await?;
Mock::given(method("POST"))
.and(path("/api/codex/ps/mcp"))
.and(body_partial_json(json!({ "method": "tools/call" })))
.respond_with(|request: &Request| {
let request: serde_json::Value = serde_json::from_slice(&request.body).unwrap();
ResponseTemplate::new(/*s*/ 200).set_body_json(json!({
"jsonrpc": "2.0", "id": request["id"],
"result": { "content": [{ "type": "text", "text": json!({
"hookSpecificOutput": {
"hookEventName": "SessionStart", "additionalContext": "The user prefers concise answers.",
},
}).to_string() }] },
}))
})
.with_priority(/*p*/ 1)
.mount(&server).await;
let home = Arc::new(TempDir::new()?);
let root = home
.path()
.join("plugins/cache/openai-bundled/codex-dream-memory/local");
fs::create_dir_all(root.join(".codex-plugin"))?;
fs::write(
root.join(".codex-plugin/plugin.json"),
serde_json::to_vec(&json!({
"name": "codex-dream-memory",
"hooks": { "hooks": { "SessionStart": [{
"matcher": "^(startup|compact)$",
"hooks": [{ "type": "mcp_tool", "server": "codex_apps", "tool": "codex_dream_memory.get_mec" }],
}] } },
}))?,
)?;
fs::write(
root.join(".app.json"),
serde_json::to_vec(&json!({
"apps": { "memory": { "id": "connector_openai_codex_dream_memory" } },
}))?,
)?;
let plugin_config = "[features]\napps = true\nplugins = true\nhooks = true\n[plugins.\"codex-dream-memory@openai-bundled\"]\nenabled = true\n[apps.connector_openai_codex_dream_memory]\n";
fs::write(home.path().join("config.toml"), plugin_config)?;
let mut builder = test_codex()
.with_home(home)
.with_model("gpt-5.5")
.with_auth(CodexAuth::create_dummy_chatgpt_auth_for_testing())
.with_config(move |config| {
configure_scenario_catalog(config);
config.chatgpt_base_url = apps.chatgpt_base_url;
for feature in [Feature::Apps, Feature::Plugins, Feature::CodexHooks] {
config.features.enable(feature).unwrap();
}
config
.features
.disable(Feature::ExecutorCapabilityDiscovery)
.unwrap();
// Exercise local compaction using the ordinary mock Responses endpoint.
config.model_provider.name = "OpenAI (test)".into();
});
let test = builder.build_with_auto_env(&server).await?;
assert!(!test.config.bypass_hook_trust);
let responses = mount_sse_sequence(
&server,
(0..3)
.map(|index| {
sse(vec![
ev_assistant_message(&format!("message-{index}"), "Done."),
ev_completed(&format!("response-{index}")),
])
})
.collect(),
)
.await;
test.submit_text_turn("Remember my preferences.").await?;
assert_eq!(recorded_apps_tool_calls(&server).await.len(), 1);
test.codex.submit(Op::Compact).await?;
wait_for_event(&test.codex, |event| {
matches!(event, EventMsg::TurnComplete(_))
})
.await;
test.submit_text_turn("Continue after compaction.").await?;
let calls = recorded_apps_tool_calls(&server).await;
assert_eq!(calls.len(), 2);
for call in calls {
assert_eq!(call["params"]["arguments"], json!({}));
assert_eq!(call["params"]["name"], "codex_dream_memory.get_mec");
}
insta::assert_snapshot!(
"bundled_memory_hook_context",
context_snapshot::format_request_history_snapshot(
"A bundled App-only hook injects memory at startup and after compaction without saved trust.",
&responses.requests(),
&ContextSnapshotOptions::default().rewrite_known_segments(),
)
);
Ok(())
}
@@ -0,0 +1,69 @@
---
source: core/tests/suite/scenarios_bundled_app_hooks.rs
assertion_line: 151
expression: "context_snapshot::format_request_history_snapshot(\"A bundled App-only hook injects memory at startup and after compaction without saved trust.\",\n&responses.requests(),\n&ContextSnapshotOptions::default().rewrite_known_segments(),)"
---
Scenario: A bundled App-only hook injects memory at startup and after compaction without saved trust.
## Window 1
-- request 1 (turn) --
00:message/developer:
<MODEL_INSTRUCTIONS>
01:message/developer[3]:
[01] <PERMISSIONS_INSTRUCTIONS>
[02] <PLUGINS_INSTRUCTIONS>
[03] <tools>
Deferred tool namespaces:
- multi_agent_v1: Tools for spawning and managing sub-agents.
</tools>
02:message/user:
<ENVIRONMENT_CONTEXT>
03:message/developer:
The user prefers concise answers.
04:message/user:
Remember my preferences.
## Window 2 (after request 1: settings changed (parallel_tool_calls, tools))
-- request 2 (compaction) --
00:message/developer:
<MODEL_INSTRUCTIONS>
01:message/developer[3]:
[01] <PERMISSIONS_INSTRUCTIONS>
[02] <PLUGINS_INSTRUCTIONS>
[03] <tools>
Deferred tool namespaces:
- multi_agent_v1: Tools for spawning and managing sub-agents.
</tools>
02:message/user:
<ENVIRONMENT_CONTEXT>
03:message/developer:
The user prefers concise answers.
04:message/user:
Remember my preferences.
05:message/assistant:
Done.
06:message/user:
<SUMMARIZATION_PROMPT>
## Window 3 (after request 2: input diverged at item 03, settings changed (parallel_tool_calls, tools))
-- request 3 (turn) --
00:message/developer:
<MODEL_INSTRUCTIONS>
01:message/developer[3]:
[01] <PERMISSIONS_INSTRUCTIONS>
[02] <PLUGINS_INSTRUCTIONS>
[03] <tools>
Deferred tool namespaces:
- multi_agent_v1: Tools for spawning and managing sub-agents.
</tools>
02:message/user:
<ENVIRONMENT_CONTEXT>
03:message/user:
Remember my preferences.
04:message/user:
<COMPACTION_SUMMARY>
Done.
05:message/developer:
The user prefers concise answers.
06:message/user:
Continue after compaction.
+11 -1
View File
@@ -17,6 +17,7 @@ use codex_config::RequirementSource;
use codex_config::TomlValue;
use codex_config::version_for_toml;
use codex_plugin::PluginHookSource;
use codex_plugin::bundled_hook_app_connector_id;
use codex_plugin::is_allowlisted_bundled_cleanup_hook;
use codex_protocol::protocol::HookEventName;
use codex_utils_absolute_path::AbsolutePathBuf;
@@ -648,6 +649,14 @@ fn append_matcher_groups(
}
};
for (handler_index, handler) in group.hooks.iter().cloned().enumerate() {
let expected_app_connector_id = source.plugin_id.as_deref().and_then(|plugin_id| {
bundled_hook_app_connector_id(
plugin_id,
event_name,
group.matcher.as_deref(),
&handler,
)
});
let normalized = match handler {
HookHandlerConfig::Command {
command,
@@ -770,7 +779,7 @@ fn append_matcher_groups(
NormalizedHandler {
config,
kind: ConfiguredHandlerKind::McpTool {
expected_app_connector_id: None,
expected_app_connector_id,
server,
tool,
input,
@@ -820,6 +829,7 @@ fn append_matcher_groups(
/*app_connector_id*/ None,
)
});
let builtin = builtin || expected_app_connector_id.is_some();
let plugin_content_hash = match source.plugin_content_hash {
Some(Ok(hash)) => Some(hash.as_str()),
Some(Err(err)) if !builtin && !source.bypass_hook_trust => {
+46
View File
@@ -1826,6 +1826,52 @@ fn bundled_cleanup_hooks_are_trusted_without_saved_hashes() {
}
}
#[test]
fn bundled_app_hook_trust_requires_exact_declaration() {
for (matcher, input, trusted) in [
("^(startup|compact)$", serde_json::json!({}), true),
(".*", serde_json::json!({}), false),
(
"^(startup|compact)$",
serde_json::json!({"untrusted": true}),
false,
),
] {
let temp = tempdir().expect("plugin root");
let mut source = bundled_cleanup_source(
"codex-dream-memory@openai-bundled",
"codex_apps",
"SessionStart",
);
source.plugin_root = AbsolutePathBuf::try_from(temp.path()).unwrap();
source.hooks = serde_json::from_value(serde_json::json!({
"SessionStart": [{ "matcher": matcher, "hooks": [{
"type": "mcp_tool", "server": "codex_apps", "tool": "codex_dream_memory.get_mec", "input": input,
}] }],
})).unwrap();
let discovered = super::discovery::discover_handlers(
/*config_layer_stack*/ None,
vec![source],
Vec::new(),
/*bypass_hook_trust*/ false,
DiscoveryMode::Listing,
);
let expected = if trusted {
HookTrustStatus::Trusted
} else {
HookTrustStatus::Untrusted
};
assert_eq!(
(
discovered.handlers.len(),
discovered.hook_entries[0].trust_status,
discovered.hook_entries[0].builtin
),
(usize::from(trusted), expected, trusted)
);
}
}
#[test]
fn bundled_cleanup_trust_does_not_extend_to_other_handlers() {
let temp = tempdir().expect("create plugin directory");
+28 -2
View File
@@ -1,5 +1,5 @@
//! Temporary cleanup-hook allowlist shared by local and executor plugin discovery.
//! This narrowly authorizes known MCP cleanup calls; it does not verify plugin signatures.
//! Temporary bundled-hook exceptions. App session hooks require connector and policy checks
//! at dispatch; cleanup hooks retain their existing trust rules. This does not verify signatures.
use codex_config::HookHandlerConfig;
use codex_protocol::protocol::HookEventName;
@@ -111,6 +111,32 @@ const ALLOWLISTED_BUNDLED_HOOKS: &[BundledHook] = &[
},
];
/// Recognizes the bundled SessionStart declaration without starting Apps discovery.
/// The caller must check this connector's identity and approval policy at dispatch.
pub fn bundled_hook_app_connector_id(
plugin_id: &str,
event: HookEventName,
matcher: Option<&str>,
handler: &HookHandlerConfig,
) -> Option<&'static str> {
let HookHandlerConfig::McpTool {
server,
tool,
input,
..
} = handler
else {
return None;
};
(plugin_id == "codex-dream-memory@openai-bundled"
&& event == HookEventName::SessionStart
&& matcher == Some("^(startup|compact)$")
&& server == "codex_apps"
&& tool == "codex_dream_memory.get_mec"
&& input.is_empty())
.then_some("connector_openai_codex_dream_memory")
}
/// Matches a temporary unsigned cleanup exception. App targets additionally require the
/// connector identity for this handler's server and tool from the caller's enabled tool
/// catalog; callers without that catalog must pass `None`.
+1
View File
@@ -10,6 +10,7 @@ pub mod manifest;
use codex_core_plugin_common::plugin_id;
mod provider;
pub use bundled_hooks::bundled_hook_app_connector_id;
pub use bundled_hooks::is_allowlisted_bundled_cleanup_hook;
use codex_config::HookEventsToml;
use codex_utils_absolute_path::AbsolutePathBuf;