From 42e253e6c9c538b29675b83ad65e4871208f8460 Mon Sep 17 00:00:00 2001 From: tomi Date: Wed, 18 Nov 2026 00:06:50 +0100 Subject: [PATCH 001/118] fix(mcp): fail closed on unsupported Playwright isolated contexts --- docs/ARCHITECTURE.md | 26 ++++ src/bridge.rs | 192 +++++++++++++++++++++++- src/upstream_control.rs | 314 +++++++++++++++++++++++++++++++++++++++- 3 files changed, 522 insertions(+), 10 deletions(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index d78e42ef..3d91af0c 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -1125,6 +1125,32 @@ The catalogue is a startup snapshot. Dynamic `tools/list_changed` notifications are not used to mutate the downstream fixed surface; restart the process to rematerialize an upstream catalogue. +**Playwright browser-context capability boundary.** A `browser_tabs` call with +`action: "new"` and a non-default `isolatedContext` requires a real browser-level +connection. An upstream launched with `--extension` (or +`PLAYWRIGHT_MCP_EXTENSION=true`) only attaches to existing tabs, so Codexify +rejects the isolated request **before upstream dispatch**, whether invoked +through direct, gateway or catalog exposure. An ordinary new/default-context +tab is unaffected. Browser-level Playwright may create isolated contexts; a CDP +endpoint may or may not have browser-level permission. If CDP reports the exact +`Target.createBrowserContext` `-32000 Not allowed` error, Codexify explains +the missing capability and does not retry or substitute the extension. + +A connected extension is **not** a fallback for an unavailable browser-level +backend. These are separate upstreams with distinct session identities; routing +one tab-creation call to another upstream would not route subsequent navigation, +selection or cleanup there. Backend and tab ownership must remain stable for +the entire workflow. Playwright's index-based global tab selection is not +per-agent ownership enforcement; callers sharing one backend must still prevent +cross-agent tab interference until stable target identity is integrated upstream. + +MCP initialization is a startup snapshot as well: a `playwright` server that +misses `startupTimeoutSec` is omitted from the downstream catalogue, even if +`playwright-extension` succeeds. Investigate its startup diagnostics and set +a bounded per-upstream `startupTimeoutSec` appropriate for the machine before +restarting Codexify during a safe maintenance window. Never restart an active +browser or resubmit an external action just to repair a missing MCP tool. + ### 7.3 Direct compatibility mode (`"mode": "direct"`) Each selected upstream tool becomes a `BridgedTool` named `__` diff --git a/src/bridge.rs b/src/bridge.rs index 68bdcef4..3cb158c1 100644 --- a/src/bridge.rs +++ b/src/bridge.rs @@ -274,6 +274,12 @@ pub(crate) async fn forward_tool_call( context: UpstreamCallContext<'_>, ) -> ToolResult { let UpstreamCallContext { resources, control } = context; + // This preflight is shared by direct, gateway and catalog MCP exposure. + // Never send an isolation request to a browser extension as a fallback. + if let Err(error) = control.check_browser_context_request(tool, ¶ms) { + return ToolResult::error(format!("Upstream MCP server '{server}': {error}")); + } + let isolated_requested = control.isolated_tab_requested(tool, ¶ms); let timeout = tool_timeout.unwrap_or(Duration::from_secs(60)); let deadline = tokio::time::Instant::now() + timeout; let token = cancellation.cloned().unwrap_or_default(); @@ -307,10 +313,34 @@ pub(crate) async fn forward_tool_call( }); match result { - Ok(result) => map_call_result(result, peer, server, tool_timeout, resources), - Err(error) => ToolResult::error(format!( - "Upstream MCP server '{server}' failed to run '{tool}': {error}" - )), + Ok(result) => { + if isolated_requested && result.is_error == Some(true) { + let message = result + .content + .iter() + .filter_map(|block| match block { + ContentBlock::Text(text) => Some(text.text.as_str()), + _ => None, + }) + .collect::>() + .join("\n"); + if let Some(error) = control.browser_context_refusal(isolated_requested, &message) { + return ToolResult::error(format!( + "Upstream MCP server '{server}' failed to run '{tool}': {error}" + )); + } + } + map_call_result(result, peer, server, tool_timeout, resources) + } + Err(error) => { + let detail = error.to_string(); + let detail = control + .browser_context_refusal(isolated_requested, &detail) + .unwrap_or(detail); + ToolResult::error(format!( + "Upstream MCP server '{server}' failed to run '{tool}': {detail}" + )) + } } } @@ -542,9 +572,10 @@ pub async fn connect_upstreams(config: &AppConfig) -> Bridge { match connect_one(server_name, spec, config).await { Ok((service, upstream_tools, tool_timeout)) => { let peer = service.peer().clone(); - let control = Arc::new(crate::upstream_control::UpstreamControl::new( - spec.request_limits.clone(), - )); + let control = Arc::new( + crate::upstream_control::UpstreamControl::new(spec.request_limits.clone()) + .for_server(server_name, spec), + ); upstreams.insert(server_name.clone(), control.clone()); monitors.push(monitor_upstream(peer.clone(), control.clone())); let count = upstream_tools.len(); @@ -604,6 +635,18 @@ pub async fn connect_upstreams(config: &AppConfig) -> Bridge { "Call the `{original_name}` tool on the `{server_name}` MCP server." ) }); + // Warn before a model chooses extension-backed tabs + // for a workflow requiring genuine browser contexts. + let description = if original_name == "browser_tabs" + && control.browser_context_capability() + == Some("existing-tabs-only") + { + format!( + "{description} This Playwright extension backend supports existing tabs only; isolatedContext requires a browser-level Playwright backend. No automatic cross-backend fallback is performed." + ) + } else { + description + }; tools.push(Box::new(BridgedTool { name: leaked, original_name, @@ -1322,6 +1365,12 @@ mod tests { if request.name.as_ref() == "slow" { tokio::time::sleep(Duration::from_secs(1)).await; } + if request.name.as_ref() == "browser_tabs" && text == "cdp_refused" { + return Ok(CallToolResult::error(vec![ContentBlock::text( + r#"Protocol error (Target.createBrowserContext): {"code":-32000,"message":"Not allowed"}"#, + )]) + .into()); + } Ok(CallToolResult::success(vec![ContentBlock::text(text)]).into()) } } @@ -1352,6 +1401,135 @@ mod tests { (format!("http://{address}/mcp"), task) } + #[tokio::test] + async fn playwright_capability_is_enforced_at_real_mcp_forwarding_boundary() { + // The test server echoes a marker for any browser_tabs request. If an + // extension-only isolated request reaches it, the test will fail. + let (url, server_task) = spawn_http_upstream().await; + let mut spec = McpServerSpec { + url: Some(url), + transport: Some("http".into()), + ..Default::default() + }; + spec.http_headers + .insert("authorization".into(), "Bearer remote-token".into()); + spec.http_headers + .insert("x-static".into(), "static-value".into()); + spec.http_headers.insert("x-env".into(), "env-value".into()); + let config = crate::config::default_config(std::env::temp_dir()); + let (service, _, _) = connect_one_with_env("playwright-test", &spec, &config, &|_| None) + .await + .unwrap(); + let resources = BridgedResourceStore::new(config.artifact_egress.clone()); + + let extension_spec = McpServerSpec { + command: Some("node".into()), + args: vec!["@playwright/mcp".into(), "--extension".into()], + ..Default::default() + }; + let full_spec = McpServerSpec { + command: Some("node".into()), + args: vec!["@playwright/mcp".into()], + ..Default::default() + }; + let cdp_spec = McpServerSpec { + command: Some("node".into()), + args: vec!["@playwright/mcp".into(), "--cdp-endpoint=chrome".into()], + ..Default::default() + }; + let extension_control = crate::upstream_control::UpstreamControl::default() + .for_server("playwright-extension", &extension_spec); + let full_control = crate::upstream_control::UpstreamControl::default() + .for_server("playwright", &full_spec); + let cdp_control = + crate::upstream_control::UpstreamControl::default().for_server("playwright", &cdp_spec); + let tab_request = |name: &str, context: &str| { + CallToolRequestParams::new("browser_tabs").with_arguments( + json!({ + "action": "new", + "isolatedContext": context, + "url": "https://example.invalid/local-fixture", + "text": name, + }) + .as_object() + .unwrap() + .clone(), + ) + }; + + let blocked = forward_tool_call( + service.peer(), + tab_request("never-dispatch", "lane06_grants_funding"), + "playwright-extension", + "browser_tabs", + None, + None, + UpstreamCallContext { + resources: &resources, + control: &extension_control, + }, + ) + .await; + assert!(blocked.is_error); + assert!(blocked.joined_text().contains("No request was dispatched")); + assert!(!blocked.joined_text().contains("never-dispatch")); + + let capable = forward_tool_call( + service.peer(), + tab_request("capable-backend-called", "lane06_grants_funding"), + "playwright", + "browser_tabs", + None, + None, + UpstreamCallContext { + resources: &resources, + control: &full_control, + }, + ) + .await; + assert!(!capable.is_error); + assert_eq!(capable.joined_text(), "capable-backend-called"); + + let refused = forward_tool_call( + service.peer(), + tab_request("cdp_refused", "lane07_funded_events"), + "playwright", + "browser_tabs", + None, + None, + UpstreamCallContext { + resources: &resources, + control: &cdp_control, + }, + ) + .await; + assert!(refused.is_error); + assert!(refused.joined_text().contains("CDP -32000 Not allowed")); + assert!( + refused + .joined_text() + .contains("No isolated context was confirmed") + ); + + // No isolation requested: ordinary existing-tab operation still works. + let nonisolated = forward_tool_call( + service.peer(), + tab_request("ordinary-tab", "default"), + "playwright-extension", + "browser_tabs", + None, + None, + UpstreamCallContext { + resources: &resources, + control: &extension_control, + }, + ) + .await; + assert!(!nonisolated.is_error); + assert_eq!(nonisolated.joined_text(), "ordinary-tab"); + server_task.abort(); + } + #[derive(Clone)] struct ResourceTestMcp; diff --git a/src/upstream_control.rs b/src/upstream_control.rs index f1bf211a..5466c097 100644 --- a/src/upstream_control.rs +++ b/src/upstream_control.rs @@ -1,5 +1,6 @@ //! Per-connection admission and failure containment; never retries tool calls. -use crate::types::McpRequestLimits; +use crate::types::{McpRequestLimits, McpServerSpec}; +use rmcp::model::CallToolRequestParams; use serde_json::{Value, json}; use std::sync::Mutex; use std::time::Duration; @@ -7,6 +8,58 @@ use tokio::sync::{Semaphore, SemaphorePermit}; use tokio::time::Instant; use tokio_util::sync::CancellationToken; +// Capability is tied to a configured upstream, never inferred from a tab name. +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] +enum PlaywrightBackendMode { + #[default] + Other, + Browser, + Cdp, + Extension, +} + +impl PlaywrightBackendMode { + fn from_spec(name: &str, spec: &McpServerSpec) -> Self { + let playwright = name.to_ascii_lowercase().contains("playwright") + || spec + .args + .iter() + .any(|arg| arg.to_ascii_lowercase().contains("playwright")) + || spec + .command + .as_deref() + .is_some_and(|command| command.to_ascii_lowercase().contains("playwright")); + if !playwright { + return Self::Other; + } + let extension_env = spec + .env + .get("PLAYWRIGHT_MCP_EXTENSION") + .is_some_and(|value| { + matches!(value.to_ascii_lowercase().as_str(), "1" | "true" | "yes") + }); + if spec + .args + .iter() + .any(|arg| arg == "--extension" || arg == "--extension=true") + || extension_env + || name.eq_ignore_ascii_case("playwright-extension") + || name.eq_ignore_ascii_case("playwright_extension") + { + Self::Extension + } else if spec + .args + .iter() + .any(|arg| arg == "--cdp-endpoint" || arg.starts_with("--cdp-endpoint=")) + || spec.env.contains_key("PLAYWRIGHT_MCP_CDP_ENDPOINT") + { + Self::Cdp + } else { + Self::Browser + } + } +} + #[derive(Default)] struct State { failures: u32, @@ -17,6 +70,7 @@ struct State { pub(crate) struct UpstreamControl { limits: McpRequestLimits, + playwright_mode: PlaywrightBackendMode, active: Semaphore, pending: Semaphore, state: Mutex, @@ -55,10 +109,79 @@ impl UpstreamControl { active: Semaphore::new(limits.max_concurrent_requests), pending: Semaphore::new(limits.max_concurrent_requests + limits.max_pending_requests), limits, + playwright_mode: PlaywrightBackendMode::Other, state: Mutex::new(State::default()), unavailable: tokio::sync::watch::channel(false).0, } } + /// Keep capability stable for this upstream connection and all exposure modes. + pub(crate) fn for_server(mut self, name: &str, spec: &McpServerSpec) -> Self { + self.playwright_mode = PlaywrightBackendMode::from_spec(name, spec); + self + } + + /// Advertise only what the connection mode can establish, not what a + /// similar tool on another upstream may be able to do. + pub(crate) fn browser_context_capability(&self) -> Option<&'static str> { + match self.playwright_mode { + PlaywrightBackendMode::Other => None, + PlaywrightBackendMode::Browser => Some("browser-level"), + PlaywrightBackendMode::Cdp => Some("cdp-permission-dependent"), + PlaywrightBackendMode::Extension => Some("existing-tabs-only"), + } + } + + pub(crate) fn isolated_tab_requested( + &self, + tool: &str, + params: &CallToolRequestParams, + ) -> bool { + self.playwright_mode != PlaywrightBackendMode::Other + && tool == "browser_tabs" + && params.arguments.as_ref().is_some_and(|args| { + args.get("action").and_then(Value::as_str) == Some("new") + && args + .get("isolatedContext") + .and_then(Value::as_str) + .is_some_and(|name| !name.is_empty() && name != "default") + }) + } + + /// An extension is attached to existing tabs; it cannot provide real + /// BrowserContexts. No attempt or fallback is safe for an isolation request. + pub(crate) fn check_browser_context_request( + &self, + tool: &str, + params: &CallToolRequestParams, + ) -> Result<(), String> { + if self.isolated_tab_requested(tool, params) + && self.playwright_mode == PlaywrightBackendMode::Extension + { + return Err( + "Playwright extension/existing-tab mode cannot create a genuinely isolated browser context (Target.createBrowserContext requires browser-level access). No request was dispatched. Use a connected browser-level Playwright MCP backend for browser_tabs(new, isolatedContext), then keep subsequent tab operations on that backend. If it is unavailable, repair its startup; do not fall back to shared extension tabs." + .into(), + ); + } + Ok(()) + } + + /// Some CDP endpoints are page-scoped; translate the exact refusal but + /// do not assume a context was created or automatically retry any tool. + pub(crate) fn browser_context_refusal( + &self, + isolated_requested: bool, + message: &str, + ) -> Option { + (isolated_requested + && message.contains("Target.createBrowserContext") + && message.contains("-32000") + && message.contains("Not allowed")) + .then(|| { + "CDP -32000 Not allowed: this Playwright/CDP session lacks browser-level Target.createBrowserContext permission. No isolated context was confirmed. Do not reuse an extension tab or assume creation succeeded; connect a browser-level Playwright backend, verify session identity and existing resources before retrying." + .into() + }) + } + pub(crate) async fn wait_unavailable(&self) { let mut receiver = self.unavailable.subscribe(); loop { @@ -128,10 +251,14 @@ impl UpstreamControl { .saturating_sub(self.active.available_permits()); let admitted = (self.limits.max_concurrent_requests + self.limits.max_pending_requests) .saturating_sub(self.pending.available_permits()); - json!({"state": if state.probe_active {"probing"} else if state.open_until.is_some() {"unresponsive"} else if state.failures > 0 {"degraded"} else {"connected"}, + let mut snapshot = json!({"state": if state.probe_active {"probing"} else if state.open_until.is_some() {"unresponsive"} else if state.failures > 0 {"degraded"} else {"connected"}, "activeRequests":active,"queuedRequests":admitted.saturating_sub(active),"consecutiveFailures":state.failures, "retryAfterMs":state.open_until.map(|until| until.saturating_duration_since(Instant::now()).as_millis() as u64).unwrap_or(0), - "lastOutcome":state.last_outcome}) + "lastOutcome":state.last_outcome}); + if let Some(capability) = self.browser_context_capability() { + snapshot["browserContextCapability"] = json!(capability); + } + snapshot } } @@ -181,6 +308,187 @@ impl Drop for Admission<'_> { } } +#[cfg(test)] +mod browser_context_tests { + use super::*; + use serde_json::json; + + #[test] + fn exposed_capability_matches_configured_backend() { + let full = UpstreamControl::default().for_server( + "playwright", + &McpServerSpec { + command: Some("node".into()), + args: vec!["@playwright/mcp".into()], + ..Default::default() + }, + ); + let extension = UpstreamControl::default().for_server( + "playwright-extension", + &McpServerSpec { + command: Some("node".into()), + args: vec!["@playwright/mcp".into(), "--extension".into()], + ..Default::default() + }, + ); + assert_eq!(full.snapshot()["browserContextCapability"], "browser-level"); + assert_eq!( + extension.snapshot()["browserContextCapability"], + "existing-tabs-only" + ); + assert!( + UpstreamControl::default() + .snapshot() + .get("browserContextCapability") + .is_none() + ); + } + + fn spec(args: &[&str]) -> McpServerSpec { + McpServerSpec { + command: Some("node".into()), + args: args.iter().map(|arg| (*arg).to_string()).collect(), + ..Default::default() + } + } + + fn request(action: &str, context: Option<&str>) -> CallToolRequestParams { + let mut arguments = json!({ "action": action, "url": "https://example.invalid/form" }); + if let Some(context) = context { + arguments["isolatedContext"] = json!(context); + } + CallToolRequestParams::new("browser_tabs") + .with_arguments(arguments.as_object().unwrap().clone()) + } + + #[test] + fn extension_mode_fails_before_isolated_creation() { + let control = UpstreamControl::default().for_server( + "playwright-extension", + &spec(&["playwright/mcp.js", "--extension"]), + ); + let request = request("new", Some("lane06_grants_funding")); + assert!(control.isolated_tab_requested("browser_tabs", &request)); + let error = control + .check_browser_context_request("browser_tabs", &request) + .unwrap_err(); + assert!(error.contains("No request was dispatched")); + assert!(error.contains("cannot create a genuinely isolated")); + } + + #[test] + fn extension_env_and_renamed_server_also_fail_closed() { + let mut settings = spec(&["playwright/mcp.js"]); + settings + .env + .insert("PLAYWRIGHT_MCP_EXTENSION".into(), "true".into()); + let control = UpstreamControl::default().for_server("my_browser", &settings); + assert!( + control + .check_browser_context_request("browser_tabs", &request("new", Some("lane01"))) + .is_err() + ); + settings + .env + .insert("PLAYWRIGHT_MCP_EXTENSION".into(), "false".into()); + let control = UpstreamControl::default().for_server("my_browser", &settings); + assert!( + control + .check_browser_context_request("browser_tabs", &request("new", Some("lane01"))) + .is_ok() + ); + } + + #[test] + fn normal_extension_tab_operations_remain_compatible() { + let control = UpstreamControl::default().for_server( + "playwright-extension", + &spec(&["playwright/mcp.js", "--extension"]), + ); + for request in [ + request("list", Some("lane06")), + request("new", None), + request("new", Some("default")), + request("select", Some("lane06")), + ] { + assert!( + control + .check_browser_context_request("browser_tabs", &request) + .is_ok() + ); + } + assert!( + control + .check_browser_context_request("browser_navigate", &request("new", Some("lane06"))) + .is_ok() + ); + } + + #[test] + fn browser_and_cdp_backend_allow_capable_context_attempts() { + for settings in [ + spec(&["playwright/mcp.js"]), + spec(&["playwright/mcp.js", "--cdp-endpoint=http://127.0.0.1:9222"]), + ] { + let control = UpstreamControl::default().for_server("playwright", &settings); + assert!( + control + .check_browser_context_request( + "browser_tabs", + &request("new", Some("lane06_grants_funding")) + ) + .is_ok() + ); + } + } + + #[test] + fn cdp_minus_32000_is_precise_but_unrelated_errors_stay_untouched() { + let control = UpstreamControl::default().for_server( + "playwright", + &spec(&["playwright/mcp.js", "--cdp-endpoint=chrome"]), + ); + let error = r#"Protocol error (Target.createBrowserContext): {"code":-32000,"message":"Not allowed"}"#; + assert!( + control + .browser_context_refusal(true, error) + .unwrap() + .contains("No isolated context was confirmed") + ); + assert!(control.browser_context_refusal(false, error).is_none()); + assert!( + control + .browser_context_refusal( + true, + "Protocol error -32000: Not allowed for Page.navigate" + ) + .is_none() + ); + } + + #[test] + fn unrelated_mcp_backend_and_disconnect_cannot_silently_switch_modes() { + let ordinary = UpstreamControl::default() + .for_server("other-mcp", &spec(&["unrelated-server.js", "--extension"])); + assert!( + ordinary + .check_browser_context_request("browser_tabs", &request("new", Some("lane06"))) + .is_ok() + ); + let extension = UpstreamControl::default().for_server( + "playwright_extension", + &spec(&["playwright/mcp.js", "--extension"]), + ); + extension.health_result(false); + extension.health_result(true); + assert!( + extension + .check_browser_context_request("browser_tabs", &request("new", Some("lane06"))) + .is_err() + ); + } +} + #[cfg(test)] mod tests { use super::*; From e16ac4af1274c4b3fe63c6afc793a7f8473ae2fe Mon Sep 17 00:00:00 2001 From: tomi Date: Wed, 18 Nov 2026 00:57:24 +0100 Subject: [PATCH 002/118] fix(mcp): detect Playwright extension mode in JSON config --- docs/ARCHITECTURE.md | 11 ++- src/upstream_control.rs | 183 ++++++++++++++++++++++++++++++++++++---- 2 files changed, 175 insertions(+), 19 deletions(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 3d91af0c..a535a97e 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -1127,10 +1127,13 @@ rematerialize an upstream catalogue. **Playwright browser-context capability boundary.** A `browser_tabs` call with `action: "new"` and a non-default `isolatedContext` requires a real browser-level -connection. An upstream launched with `--extension` (or -`PLAYWRIGHT_MCP_EXTENSION=true`) only attaches to existing tabs, so Codexify -rejects the isolated request **before upstream dispatch**, whether invoked -through direct, gateway or catalog exposure. An ordinary new/default-context +connection. An upstream launched with `--extension`, `PLAYWRIGHT_MCP_EXTENSION=true`, +or `extension: true` in its Playwright JSON config only attaches to existing tabs, +so Codexify rejects the isolated request **before upstream dispatch**, whether +invoked through direct, gateway or catalog exposure. If an explicitly supplied +Playwright JSON configuration cannot be read or parsed, isolated-context +creation also fails closed instead of assuming the backend has browser-level +permissions. An ordinary new/default-context tab is unaffected. Browser-level Playwright may create isolated contexts; a CDP endpoint may or may not have browser-level permission. If CDP reports the exact `Target.createBrowserContext` `-32000 Not allowed` error, Codexify explains diff --git a/src/upstream_control.rs b/src/upstream_control.rs index 5466c097..816abc78 100644 --- a/src/upstream_control.rs +++ b/src/upstream_control.rs @@ -16,9 +16,42 @@ enum PlaywrightBackendMode { Browser, Cdp, Extension, + Unverified, } impl PlaywrightBackendMode { + // Playwright accepts --config and PLAYWRIGHT_MCP_CONFIG as well as + // command-line flags. A hidden extension configuration must not be + // mistaken for a browser-level backend. + fn config_document(spec: &McpServerSpec) -> Option> { + let path = spec + .args + .iter() + .enumerate() + .filter_map(|(index, arg)| { + if arg == "--config" { + Some(spec.args.get(index + 1).map_or("", String::as_str)) + } else { + arg.strip_prefix("--config=") + } + }) + .last() + .map(str::to_owned) + .or_else(|| spec.env.get("PLAYWRIGHT_MCP_CONFIG").cloned()) + .or_else(|| std::env::var("PLAYWRIGHT_MCP_CONFIG").ok())?; + + let mut path = std::path::PathBuf::from(path); + if path.is_relative() { + if let Some(cwd) = spec.cwd.as_ref() { + path = std::path::Path::new(cwd).join(path); + } + } + let parsed = std::fs::read_to_string(path) + .ok() + .and_then(|source| serde_json::from_str::(&source).ok()); + Some(parsed) + } + fn from_spec(name: &str, spec: &McpServerSpec) -> Self { let playwright = name.to_ascii_lowercase().contains("playwright") || spec @@ -32,31 +65,52 @@ impl PlaywrightBackendMode { if !playwright { return Self::Other; } - let extension_env = spec + + let configured = Self::config_document(spec); + let read_config = configured.as_ref().and_then(Option::as_ref); + + let cli_extension = spec.args.iter().rev().find_map(|arg| match arg.as_str() { + "--extension" | "--extension=true" => Some(true), + "--extension=false" => Some(false), + _ => None, + }); + let env_extension = spec .env .get("PLAYWRIGHT_MCP_EXTENSION") - .is_some_and(|value| { - matches!(value.to_ascii_lowercase().as_str(), "1" | "true" | "yes") + .cloned() + .or_else(|| std::env::var("PLAYWRIGHT_MCP_EXTENSION").ok()) + .and_then(|value| match value.to_ascii_lowercase().as_str() { + "1" | "true" | "yes" => Some(true), + "0" | "false" | "no" => Some(false), + _ => None, }); - if spec - .args - .iter() - .any(|arg| arg == "--extension" || arg == "--extension=true") - || extension_env + let config_extension = read_config + .and_then(|value| value.get("extension")) + .and_then(Value::as_bool); + if cli_extension.or(env_extension).or(config_extension) == Some(true) || name.eq_ignore_ascii_case("playwright-extension") || name.eq_ignore_ascii_case("playwright_extension") { - Self::Extension - } else if spec + return Self::Extension; + } + + // Failure to read an explicitly configured backend leaves its + // permissions unknown. Do not dispatch real isolation requests. + if configured.as_ref().is_some_and(Option::is_none) { + return Self::Unverified; + } + + let cdp = spec .args .iter() .any(|arg| arg == "--cdp-endpoint" || arg.starts_with("--cdp-endpoint=")) || spec.env.contains_key("PLAYWRIGHT_MCP_CDP_ENDPOINT") - { - Self::Cdp - } else { - Self::Browser - } + || std::env::var_os("PLAYWRIGHT_MCP_CDP_ENDPOINT").is_some() + || read_config + .and_then(|value| value.pointer("/browser/cdpEndpoint")) + .and_then(Value::as_str) + .is_some_and(|url| !url.is_empty()); + if cdp { Self::Cdp } else { Self::Browser } } } @@ -128,6 +182,7 @@ impl UpstreamControl { PlaywrightBackendMode::Browser => Some("browser-level"), PlaywrightBackendMode::Cdp => Some("cdp-permission-dependent"), PlaywrightBackendMode::Extension => Some("existing-tabs-only"), + PlaywrightBackendMode::Unverified => Some("unverified-config"), } } @@ -154,6 +209,13 @@ impl UpstreamControl { tool: &str, params: &CallToolRequestParams, ) -> Result<(), String> { + if self.isolated_tab_requested(tool, params) + && self.playwright_mode == PlaywrightBackendMode::Unverified + { + return Err( + "Playwright config file is missing, invalid or unreadable, so browser-context capabilities cannot be verified. No request was dispatched. Restore the configured MCP file before creating an isolated browser context.".into() + ); + } if self.isolated_tab_requested(tool, params) && self.playwright_mode == PlaywrightBackendMode::Extension { @@ -424,6 +486,97 @@ mod browser_context_tests { ); } + #[test] + fn playwright_json_extension_mode_cannot_bypass_guard() { + let temp = tempfile::tempdir().unwrap(); + let file = temp.path().join("playwright.json"); + std::fs::write(&file, r#"{"extension":true}"#).unwrap(); + let config_name = file.to_str().unwrap(); + let settings = spec(&["@playwright/mcp", "--config", config_name]); + let control = UpstreamControl::default().for_server("playwright", &settings); + assert_eq!( + control.browser_context_capability(), + Some("existing-tabs-only") + ); + assert!( + control + .check_browser_context_request("browser_tabs", &request("new", Some("lane06"))) + .unwrap_err() + .contains("No request was dispatched") + ); + + std::fs::write( + &file, + r#"{"extension":false,"browser":{"cdpEndpoint":"chrome"}}"#, + ) + .unwrap(); + let control = UpstreamControl::default().for_server("playwright", &settings); + assert_eq!( + control.browser_context_capability(), + Some("cdp-permission-dependent") + ); + + std::fs::write(&file, r#"{"extension":true}"#).unwrap(); + let mut overriding = settings.clone(); + overriding + .env + .insert("PLAYWRIGHT_MCP_EXTENSION".into(), "false".into()); + let control = UpstreamControl::default().for_server("playwright", &overriding); + assert_eq!(control.browser_context_capability(), Some("browser-level")); + } + + #[test] + fn missing_or_invalid_json_config_fails_closed_without_blocking_default_tab() { + let temp = tempfile::tempdir().unwrap(); + let file = temp.path().join("config.json"); + let mut settings = spec(&["@playwright/mcp", "--config"]); + settings.args.push(file.to_string_lossy().into_owned()); + let control = UpstreamControl::default().for_server("playwright", &settings); + assert_eq!( + control.snapshot()["browserContextCapability"], + "unverified-config" + ); + assert!( + control + .check_browser_context_request("browser_tabs", &request("new", Some("lane06"))) + .unwrap_err() + .contains("No request was dispatched") + ); + assert!( + control + .check_browser_context_request("browser_tabs", &request("new", None)) + .is_ok() + ); + + std::fs::write(&file, "not json").unwrap(); + let control = UpstreamControl::default().for_server("playwright", &settings); + assert_eq!( + control.snapshot()["browserContextCapability"], + "unverified-config" + ); + + std::fs::write(&file, r#"{"extension":true}"#).unwrap(); + settings.args.push("--extension=false".into()); + let control = UpstreamControl::default().for_server("playwright", &settings); + assert_eq!( + control.snapshot()["browserContextCapability"], + "browser-level" + ); + } + + #[test] + fn playwright_config_relative_to_upstream_cwd_is_resolved() { + let temp = tempfile::tempdir().unwrap(); + std::fs::write(temp.path().join("playwright.json"), r#"{"extension":true}"#).unwrap(); + let mut settings = spec(&["@playwright/mcp", "--config=playwright.json"]); + settings.cwd = Some(temp.path().to_string_lossy().into_owned()); + let control = UpstreamControl::default().for_server("playwright", &settings); + assert_eq!( + control.snapshot()["browserContextCapability"], + "existing-tabs-only" + ); + } + #[test] fn browser_and_cdp_backend_allow_capable_context_attempts() { for settings in [ From 4b3d3ee3938eb63b06739378c14fe60fda2826bb Mon Sep 17 00:00:00 2001 From: tomi Date: Wed, 18 Nov 2026 01:09:38 +0100 Subject: [PATCH 003/118] fix(mcp): satisfy strict Clippy lint for config parser --- src/upstream_control.rs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/upstream_control.rs b/src/upstream_control.rs index 816abc78..f95f350d 100644 --- a/src/upstream_control.rs +++ b/src/upstream_control.rs @@ -35,16 +35,16 @@ impl PlaywrightBackendMode { arg.strip_prefix("--config=") } }) - .last() + .next_back() .map(str::to_owned) .or_else(|| spec.env.get("PLAYWRIGHT_MCP_CONFIG").cloned()) .or_else(|| std::env::var("PLAYWRIGHT_MCP_CONFIG").ok())?; let mut path = std::path::PathBuf::from(path); - if path.is_relative() { - if let Some(cwd) = spec.cwd.as_ref() { - path = std::path::Path::new(cwd).join(path); - } + if path.is_relative() + && let Some(cwd) = spec.cwd.as_ref() + { + path = std::path::Path::new(cwd).join(path); } let parsed = std::fs::read_to_string(path) .ok() From 68be301c067ae48e0a4536c104c41f4d0d470703 Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Wed, 18 Nov 2026 05:06:38 +0100 Subject: [PATCH 004/118] fix(single-lane): harden durable Windows goal writes on clean v2.4 base --- .github/workflows/single-lane-v240-ci.yml | 74 ++++++++++++++++++++ docs/SINGLE_LANE_V240_RECOVERY.md | 41 ++++++++++++ src/agent_automation/store.rs | 82 ++++++++++++++++++++++- src/project_clone.rs | 12 +++- 4 files changed, 206 insertions(+), 3 deletions(-) create mode 100644 .github/workflows/single-lane-v240-ci.yml create mode 100644 docs/SINGLE_LANE_V240_RECOVERY.md diff --git a/.github/workflows/single-lane-v240-ci.yml b/.github/workflows/single-lane-v240-ci.yml new file mode 100644 index 00000000..8b1efbc5 --- /dev/null +++ b/.github/workflows/single-lane-v240-ci.yml @@ -0,0 +1,74 @@ +name: Single-lane v2.4 validation (no deployment) + +on: + push: + branches: [fix/single-lane-v240-stable-20261118] + workflow_dispatch: + +permissions: + contents: read + +jobs: + native-windows: + name: Verify single-lane native and durable goal state + runs-on: windows-latest + timeout-minutes: 120 + defaults: + run: + shell: pwsh + env: + CARGO_BUILD_JOBS: '2' + CARGO_INCREMENTAL: '0' + CARGO_PROFILE_DEV_DEBUG: line-tables-only + CARGO_PROFILE_TEST_DEBUG: line-tables-only + steps: + - uses: actions/checkout@v5 + with: + fetch-depth: 2 + - uses: dtolnay/rust-toolchain@stable + with: + components: rustfmt, clippy + - uses: Swatinem/rust-cache@v2 + - name: Bound changes to durability and Windows tests + run: | + $ErrorActionPreference = 'Stop' + $allowed = @('src/agent_automation/store.rs','src/project_clone.rs','.github/workflows/single-lane-v240-ci.yml','docs/SINGLE_LANE_V240_RECOVERY.md') + $changed = @(git diff --name-only HEAD^ HEAD) + if ($LASTEXITCODE -ne 0) { throw 'Failed to inspect commit scope' } + foreach ($file in $changed) { + if ($file -notin $allowed) { throw "Unexpected changed file: $file" } + } + git diff --check HEAD^ HEAD + if ($LASTEXITCODE -ne 0) { throw 'Whitespace errors' } + rustfmt --check --edition 2024 --config skip_children=true src/agent_automation/store.rs src/project_clone.rs + if ($LASTEXITCODE -ne 0) { throw 'Rustfmt check failed' } + - name: Validate native source and test compilation + run: | + cargo check --locked --all-targets -j 2 + if ($LASTEXITCODE -ne 0) { throw 'Cargo check failed' } + - name: Verify Windows locked file and canonical path regressions + run: | + cargo test --locked --lib windows_state_publication_tests -j 2 -- --nocapture + if ($LASTEXITCODE -ne 0) { throw 'State publication test failed' } + cargo test --locked --lib rejects_ambiguous_matching_checkouts -j 2 -- --nocapture + if ($LASTEXITCODE -ne 0) { throw 'Windows path test failed' } + cargo test --locked --lib browser_action_lanes_default_to_one_and_are_bounded -j 2 + if ($LASTEXITCODE -ne 0) { throw 'Single browser lane default test failed' } + - name: Run full Rust library regression suite + run: | + cargo test --locked --lib -j 2 + if ($LASTEXITCODE -ne 0) { throw 'Full library tests failed' } + - name: Build official-v2.4-based native candidate without installing + run: | + cargo build --locked --release --bin codexify -j 2 + if ($LASTEXITCODE -ne 0) { throw 'Native build failed' } + & .\target\release\codexify.exe --version + if ($LASTEXITCODE -ne 0) { throw 'Binary version smoke failed' } + Get-FileHash .\target\release\codexify.exe -Algorithm SHA256 | Format-List | Out-String | Write-Output + - name: Retain reviewed native candidate for one day + uses: actions/upload-artifact@v4 + with: + name: codexify-v240-minimal-single-lane-windows + path: target/release/codexify.exe + if-no-files-found: error + retention-days: 1 diff --git a/docs/SINGLE_LANE_V240_RECOVERY.md b/docs/SINGLE_LANE_V240_RECOVERY.md new file mode 100644 index 00000000..8784fad5 --- /dev/null +++ b/docs/SINGLE_LANE_V240_RECOVERY.md @@ -0,0 +1,41 @@ +# Minimal v2.4 single-lane recovery candidate + +This branch starts from the official Codexify v2.4.0 source commit +`b14eacde810531a451535ee546ca7e07c65c5a1d`. It intentionally does **not** import the experimental two-browser +integration, global primary-goal pin, second companion/watchdog, or private +profile logic. + +The native v2.4 scheduler defaults to one browser action page and protects +dispatch with a one-permit semaphore. Other saved goals remain durable and +eligible in their existing queue; no second browser process or goal pin is +needed to serialize actions. + +## Changes + +- Preserve state publication through short Windows sharing locks: if a + read-only no-op comparison is blocked by a genuine Win32 sharing violation, + let the existing bounded atomic-replacement retry handle the lock. Other + file-read errors still fail closed. +- Test transient/persistent sharing violations with old state preserved. +- Make an existing ambiguous Git checkout test compare canonicalized paths + on Windows, without changing real checkout selection. +- Run targeted and full library tests on Windows and stage a native binary, + without performing a service installation. + +## Production cutover gates + +1. Verify the current authenticated primary companion and native service are + healthy, and confirm exactly one configured browser action lane. +2. Preserve the existing service binary, version-matched browser runtime, + config and all original goal/journal/action receipt files. +3. Verify there is no actively dispatched or uncertain accepted browser Send, + and no unverified terminal/renewal handoff in the intended maintenance + interval. A queued action is not proof of being safely idle. +4. Use only the official version-matched browser companion; never install the + older two-browser candidate or restart another agent's Chrome profile. +5. Upgrade via a guarded verified native service procedure, run doctor, + confirm authenticated browser health, and verify read-only goal continuity + before resuming admissions. Roll back executable/runtime if health fails, + without rewriting goal journals or replaying accepted Sends. + +**No production change is authorized or executed by this branch.** diff --git a/src/agent_automation/store.rs b/src/agent_automation/store.rs index cf167745..89940548 100644 --- a/src/agent_automation/store.rs +++ b/src/agent_automation/store.rs @@ -4193,7 +4193,36 @@ fn persist_private_record(path: &Path, record: &impl Serialize) -> Result<(), St // atomic replacement and sync_all for identical bytes. Comparing the // serialized record also preserves migrations and ignores runtime-only // fields rather than confusing them with durable changes. - if read_private_record(path)?.as_deref() == Some(bytes.as_slice()) { + // An exclusive Windows reader can temporarily prevent the no-op comparison. + // In that specific case, preserve validation and let the atomic publisher's + // bounded sharing-violation retry decide whether replacement is safe. + let unchanged = match read_private_record(path) { + Ok(existing) => existing.as_deref() == Some(bytes.as_slice()), + Err(read_error) => { + #[cfg(windows)] + { + use std::os::windows::fs::OpenOptionsExt; + let mut options = OpenOptions::new(); + options.read(true); + options.custom_flags( + windows_sys::Win32::Storage::FileSystem::FILE_FLAG_OPEN_REPARSE_POINT, + ); + if matches!( + options.open(path).err().and_then(|error| error.raw_os_error()), + Some(32 | 33) + ) { + false + } else { + return Err(read_error); + } + } + #[cfg(not(windows))] + { + return Err(read_error); + } + } + }; + if unchanged { return Ok(()); } let mut temporary = tempfile::NamedTempFile::new_in(parent) @@ -5034,3 +5063,54 @@ mod schema_rollover_tests { } } } + +#[cfg(all(test, windows))] +mod windows_state_publication_tests { + use super::*; + use std::os::windows::fs::OpenOptionsExt; + + #[test] + fn transient_sharing_violation_does_not_lose_automation_state() { + let root = tempfile::tempdir().unwrap(); + let path = root.path().join("state.json"); + persist_private_record(&path, &serde_json::json!({"version":1})).unwrap(); + + // Another Windows process can briefly open the old destination without + // FILE_SHARE_DELETE (e.g. antivirus or a file indexer). The new atomic + // replacement must preserve its temporary file until that handle exits. + let held = std::fs::OpenOptions::new() + .read(true) + .share_mode(0) + .open(&path) + .unwrap(); + let target = path.clone(); + let publisher = std::thread::spawn(move || { + persist_private_record(&target, &serde_json::json!({"version":2})) + }); + std::thread::sleep(std::time::Duration::from_millis(80)); + drop(held); + publisher.join().unwrap().unwrap(); + let value: serde_json::Value = + serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + assert_eq!(value["version"], 2); + } + + #[test] + fn persistent_sharing_violation_fails_without_overwriting_state() { + let root = tempfile::tempdir().unwrap(); + let path = root.path().join("state.json"); + persist_private_record(&path, &serde_json::json!({"version":1})).unwrap(); + let held = std::fs::OpenOptions::new() + .read(true) + .share_mode(0) + .open(&path) + .unwrap(); + let error = persist_private_record(&path, &serde_json::json!({"version":2})) + .expect_err("permanent destination lock must remain a hard error"); + assert!(error.contains("Could not publish agent automation state")); + drop(held); + let value: serde_json::Value = + serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + assert_eq!(value["version"], 1); + } +} diff --git a/src/project_clone.rs b/src/project_clone.rs index c300d57b..ffb0de57 100644 --- a/src/project_clone.rs +++ b/src/project_clone.rs @@ -2390,8 +2390,16 @@ mod tests { .await .unwrap_err(); assert!(error.contains("Multiple local checkouts match"), "{error}"); - assert!(error.contains(first.to_string_lossy().as_ref()), "{error}"); - assert!(error.contains(second.to_string_lossy().as_ref()), "{error}"); + let canonical_first = fs::canonicalize(&first).unwrap(); + let canonical_second = fs::canonicalize(&second).unwrap(); + assert!( + error.contains(canonical_first.to_string_lossy().as_ref()), + "{error}" + ); + assert!( + error.contains(canonical_second.to_string_lossy().as_ref()), + "{error}" + ); } #[tokio::test] From 554cd71cbecbbf611cac88f9c4949edeb3c62778 Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Wed, 18 Nov 2026 05:08:31 +0100 Subject: [PATCH 005/118] style(single-lane): satisfy Rustfmt in guarded Windows persistence --- src/agent_automation/store.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/agent_automation/store.rs b/src/agent_automation/store.rs index 89940548..6bf9ef57 100644 --- a/src/agent_automation/store.rs +++ b/src/agent_automation/store.rs @@ -4208,7 +4208,10 @@ fn persist_private_record(path: &Path, record: &impl Serialize) -> Result<(), St windows_sys::Win32::Storage::FileSystem::FILE_FLAG_OPEN_REPARSE_POINT, ); if matches!( - options.open(path).err().and_then(|error| error.raw_os_error()), + options + .open(path) + .err() + .and_then(|error| error.raw_os_error()), Some(32 | 33) ) { false From a91ced30b503374ec67c898f1dc5e834dca576b9 Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Wed, 18 Nov 2026 05:18:28 +0100 Subject: [PATCH 006/118] ci(single-lane): use supported help command for executable smoke check --- .github/workflows/single-lane-v240-ci.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/single-lane-v240-ci.yml b/.github/workflows/single-lane-v240-ci.yml index 8b1efbc5..f2469a27 100644 --- a/.github/workflows/single-lane-v240-ci.yml +++ b/.github/workflows/single-lane-v240-ci.yml @@ -62,8 +62,8 @@ jobs: run: | cargo build --locked --release --bin codexify -j 2 if ($LASTEXITCODE -ne 0) { throw 'Native build failed' } - & .\target\release\codexify.exe --version - if ($LASTEXITCODE -ne 0) { throw 'Binary version smoke failed' } + & .\target\release\codexify.exe --help | Select-Object -First 5 + if ($LASTEXITCODE -ne 0) { throw 'Binary help smoke failed' } Get-FileHash .\target\release\codexify.exe -Algorithm SHA256 | Format-List | Out-String | Write-Output - name: Retain reviewed native candidate for one day uses: actions/upload-artifact@v4 From 126b886adf51d1126776c33a9b7c26053359397b Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Wed, 18 Nov 2026 05:30:39 +0100 Subject: [PATCH 007/118] fix(windows): bound self-update status reads across atomic rename gaps --- .github/workflows/single-lane-v240-ci.yml | 6 +++-- docs/SINGLE_LANE_V240_RECOVERY.md | 2 ++ src/self_update.rs | 29 +++++++++++++++++++++++ 3 files changed, 35 insertions(+), 2 deletions(-) diff --git a/.github/workflows/single-lane-v240-ci.yml b/.github/workflows/single-lane-v240-ci.yml index f2469a27..e3047c85 100644 --- a/.github/workflows/single-lane-v240-ci.yml +++ b/.github/workflows/single-lane-v240-ci.yml @@ -32,7 +32,7 @@ jobs: - name: Bound changes to durability and Windows tests run: | $ErrorActionPreference = 'Stop' - $allowed = @('src/agent_automation/store.rs','src/project_clone.rs','.github/workflows/single-lane-v240-ci.yml','docs/SINGLE_LANE_V240_RECOVERY.md') + $allowed = @('src/agent_automation/store.rs','src/project_clone.rs','src/self_update.rs','.github/workflows/single-lane-v240-ci.yml','docs/SINGLE_LANE_V240_RECOVERY.md') $changed = @(git diff --name-only HEAD^ HEAD) if ($LASTEXITCODE -ne 0) { throw 'Failed to inspect commit scope' } foreach ($file in $changed) { @@ -40,7 +40,7 @@ jobs: } git diff --check HEAD^ HEAD if ($LASTEXITCODE -ne 0) { throw 'Whitespace errors' } - rustfmt --check --edition 2024 --config skip_children=true src/agent_automation/store.rs src/project_clone.rs + rustfmt --check --edition 2024 --config skip_children=true src/agent_automation/store.rs src/project_clone.rs src/self_update.rs if ($LASTEXITCODE -ne 0) { throw 'Rustfmt check failed' } - name: Validate native source and test compilation run: | @@ -52,6 +52,8 @@ jobs: if ($LASTEXITCODE -ne 0) { throw 'State publication test failed' } cargo test --locked --lib rejects_ambiguous_matching_checkouts -j 2 -- --nocapture if ($LASTEXITCODE -ne 0) { throw 'Windows path test failed' } + cargo test --locked --lib windows_worker_reports_start_and_completes_a_unicode_file_update -j 2 -- --nocapture + if ($LASTEXITCODE -ne 0) { throw 'Windows status publication test failed' } cargo test --locked --lib browser_action_lanes_default_to_one_and_are_bounded -j 2 if ($LASTEXITCODE -ne 0) { throw 'Single browser lane default test failed' } - name: Run full Rust library regression suite diff --git a/docs/SINGLE_LANE_V240_RECOVERY.md b/docs/SINGLE_LANE_V240_RECOVERY.md index 8784fad5..512dfc95 100644 --- a/docs/SINGLE_LANE_V240_RECOVERY.md +++ b/docs/SINGLE_LANE_V240_RECOVERY.md @@ -19,6 +19,8 @@ needed to serialize actions. - Test transient/persistent sharing violations with old state preserved. - Make an existing ambiguous Git checkout test compare canonicalized paths on Windows, without changing real checkout selection. +- Retry a brief Windows status-file rename gap during self-update reads, + bounded to missing-file or sharing-violation errors. - Run targeted and full library tests on Windows and stage a native binary, without performing a service installation. diff --git a/src/self_update.rs b/src/self_update.rs index 1bee6fec..f20d26ff 100644 --- a/src/self_update.rs +++ b/src/self_update.rs @@ -624,6 +624,35 @@ fn write_status_record_to(status_dir: &Path, record: &UpdateStatusRecord) -> any fn read_status_record_from( status_dir: &Path, update_id: &str, +) -> anyhow::Result { + // An atomic status replacement can briefly hide its target on Windows. + // Retry only missing-file or sharing-violation errors, without changing + // the durable record or hiding a persistent failure. + #[cfg(windows)] + { + for _ in 0..6 { + match read_status_record_once(status_dir, update_id) { + Ok(record) => return Ok(record), + Err(error) + if error + .downcast_ref::() + .is_some_and(|io| { + io.kind() == std::io::ErrorKind::NotFound + || matches!(io.raw_os_error(), Some(32 | 33)) + }) => + { + std::thread::sleep(Duration::from_millis(20)); + } + Err(error) => return Err(error), + } + } + } + read_status_record_once(status_dir, update_id) +} + +fn read_status_record_once( + status_dir: &Path, + update_id: &str, ) -> anyhow::Result { if !valid_update_id(update_id) { bail!("invalid update id"); From 3c16f1351dc443dc619c524ed209e8474c4bcaee Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Wed, 18 Nov 2026 05:39:14 +0100 Subject: [PATCH 008/118] style(windows): format bounded updater status retry --- src/self_update.rs | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/src/self_update.rs b/src/self_update.rs index f20d26ff..2349dc4f 100644 --- a/src/self_update.rs +++ b/src/self_update.rs @@ -634,12 +634,10 @@ fn read_status_record_from( match read_status_record_once(status_dir, update_id) { Ok(record) => return Ok(record), Err(error) - if error - .downcast_ref::() - .is_some_and(|io| { - io.kind() == std::io::ErrorKind::NotFound - || matches!(io.raw_os_error(), Some(32 | 33)) - }) => + if error.downcast_ref::().is_some_and(|io| { + io.kind() == std::io::ErrorKind::NotFound + || matches!(io.raw_os_error(), Some(32 | 33)) + }) => { std::thread::sleep(Duration::from_millis(20)); } From be9ce3705705d9686bfd6dac3c26275bd7911b20 Mon Sep 17 00:00:00 2001 From: tomi Date: Wed, 18 Nov 2026 05:47:30 +0100 Subject: [PATCH 009/118] fix(goal): wake blocked input waits after owner goal activation --- src/owner_chat.rs | 147 ++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 142 insertions(+), 5 deletions(-) diff --git a/src/owner_chat.rs b/src/owner_chat.rs index 9d4268f3..1bd8fa8a 100644 --- a/src/owner_chat.rs +++ b/src/owner_chat.rs @@ -1990,16 +1990,63 @@ async fn chat_send( crate::markdown_chat::now_ms(), ) .map_err(internal_error)?; - if receipt.updated_active_goal { + // A blocked goal can leave its agent in chat_await. Activating a new + // goal must deliver that changed intent to the waiting agent; merely + // notifying the offline supervisor cannot interrupt an input wait. + let wake_input_wait = if !receipt.updated_active_goal + && matches!( + receipt.kind, + crate::agent_automation::OwnerGoalCommandKind::Set + | crate::agent_automation::OwnerGoalCommandKind::Run + ) + && let Some(goal) = receipt + .goal + .as_ref() + .filter(|goal| goal.status == crate::agent_automation::GoalStatus::Active) + { + // An idempotent retry may repair a lost notice, but an old + // request must never wake a later, different goal revision. + let current = context.store.load(&context.task).map_err(internal_error)?; + current.goal.as_ref().is_some_and(|saved| { + saved.revision == goal.revision + && saved.status == crate::agent_automation::GoalStatus::Active + }) && (context + .chat + .queue_input_required() + .await + .map_err(internal_error)? + || context + .chat + .offline_activity() + .await + .map_err(internal_error)? + .agent_waiting_until_ms + .is_some_and(|until| until > crate::markdown_chat::now_ms())) + } else { + false + }; + if receipt.updated_active_goal || wake_input_wait { let goal = receipt.goal.as_ref().expect("updated active goal receipt"); let notification_id = format!( "goal-update-{:x}", Sha256::digest(body.request_id.as_bytes()) ); - context.chat.append_user(notification_id, format!( - "The goal has changed (revision {}). The new goal is:\n\n{}\n\nCall `goal_read` for the current revision and continue toward the updated goal.", - goal.revision, goal.markdown, - )).await.map_err(internal_error)?; + let notice = if receipt.updated_active_goal { + format!( + "The goal has changed (revision {}). The new goal is:\n\n{}\n\nCall `goal_read` for the current revision and continue toward the updated goal.", + goal.revision, goal.markdown, + ) + } else { + format!( + "The owner activated goal revision {} while this chat was waiting for input. The new active goal is:\n\n{}\n\nCall `goal_read` and continue the new goal; do not remain in the previous blocked goal's input wait.", + goal.revision, goal.markdown, + ) + }; + context + .chat + .append_user(notification_id, notice) + .await + .map_err(internal_error)?; } if !receipt.replayed && matches!( @@ -3991,6 +4038,8 @@ mod tests { config.markdown_chat.automation.enabled = true; config.markdown_chat.automation.connector_name = "Codexify".into(); config.memory.dir = Some(temp.path().join("state").display().to_string()); + let goal_store = + crate::agent_automation::AgentAutomationStore::for_config(&config).unwrap(); let identity = ConversationIdentity::from_openai_session("owner-goal-api").unwrap(); let chats = Arc::new(MarkdownChatStore::default()); let chat = chats @@ -4361,6 +4410,94 @@ mod tests { .unwrap(); assert!(listed["chats"][0]["goalStatus"].is_null()); assert!(listed["chats"][0]["goal"].is_null()); + + // A blocked goal's chat_await must not keep a newly activated goal + // waiting forever. The notification is a local owner wake, not a + // browser Send or a fabricated turn-renewal receipt. + let blocked: Value = client + .post(format!("{base}/api/chats/{id}/send")) + .bearer_auth("test-token") + .json(&json!({ + "request_id": "goal-before-input-wait", + "message": "/goal set Old goal awaiting owner input" + })) + .send() + .await + .unwrap() + .json() + .await + .unwrap(); + let blocked_revision = blocked["_meta"][CHAT_WIDGET_META]["goal"]["revision"] + .as_u64() + .unwrap(); + goal_store + .finish_goal( + &identity, + blocked_revision, + crate::agent_automation::GoalFinish::Blocked { + reason: "Owner input required".into(), + }, + crate::markdown_chat::now_ms(), + ) + .unwrap(); + // Drain earlier fixture messages so the new waiter really blocks. + let _ = chat.read(true).await.unwrap(); + assert!( + !chat.queue_input_required().await.unwrap(), + "the old input wait should be observable through runtime state alone" + ); + let waiter = chat.clone(); + let waiting = tokio::spawn(async move { + waiter + .wait( + std::time::Duration::from_secs(5), + tokio_util::sync::CancellationToken::new(), + ) + .await + .unwrap() + }); + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + assert!( + chat.offline_activity() + .await + .unwrap() + .agent_waiting_until_ms + .is_some(), + "the old chat_await must be active before a new goal is set" + ); + let activate = || { + client + .post(format!("{base}/api/chats/{id}/send")) + .bearer_auth("test-token") + .json(&json!({ + "request_id": "replace-blocked-input-goal", + "message": "/goal set Continue autonomous work after blocked input wait" + })) + .send() + }; + let replacement: Value = activate().await.unwrap().json().await.unwrap(); + assert_eq!( + replacement["_meta"][CHAT_WIDGET_META]["goal"]["revision"], + blocked_revision + 1 + ); + assert_eq!( + replacement["_meta"][CHAT_WIDGET_META]["goal"]["status"], + "active" + ); + let wake = tokio::time::timeout(std::time::Duration::from_secs(7), waiting) + .await + .unwrap() + .unwrap(); + let crate::markdown_chat::WaitOutcome::Message(delivered) = wake else { + panic!("new active goal did not wake the old blocked input wait"); + }; + assert!(delivered.text.contains("The owner activated goal revision")); + assert!(delivered.text.contains("Continue autonomous work")); + chat.queue_reply_received().await.unwrap(); + assert!(!chat.queue_input_required().await.unwrap()); + let replay: Value = activate().await.unwrap().json().await.unwrap(); + assert_eq!(replay["_meta"][CHAT_WIDGET_META]["replayed"], true); + assert!(chat.unread_snapshot().await.unwrap().messages.is_empty()); task.abort(); } From 47db8001e18070d3e0f074a6c567d623510e7d99 Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Wed, 18 Nov 2026 05:48:18 +0100 Subject: [PATCH 010/118] ci(goal): validate blocked-wait wake parity on clean v2.4 single lane --- .github/workflows/single-lane-v240-ci.yml | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/.github/workflows/single-lane-v240-ci.yml b/.github/workflows/single-lane-v240-ci.yml index e3047c85..58c0f018 100644 --- a/.github/workflows/single-lane-v240-ci.yml +++ b/.github/workflows/single-lane-v240-ci.yml @@ -2,7 +2,7 @@ name: Single-lane v2.4 validation (no deployment) on: push: - branches: [fix/single-lane-v240-stable-20261118] + branches: [fix/single-lane-v240-stable-20261118, fix/single-lane-v240-goal-parity-20261118] workflow_dispatch: permissions: @@ -32,7 +32,7 @@ jobs: - name: Bound changes to durability and Windows tests run: | $ErrorActionPreference = 'Stop' - $allowed = @('src/agent_automation/store.rs','src/project_clone.rs','src/self_update.rs','.github/workflows/single-lane-v240-ci.yml','docs/SINGLE_LANE_V240_RECOVERY.md') + $allowed = @('src/agent_automation/store.rs','src/project_clone.rs','src/self_update.rs','src/owner_chat.rs','.github/workflows/single-lane-v240-ci.yml','docs/SINGLE_LANE_V240_RECOVERY.md') $changed = @(git diff --name-only HEAD^ HEAD) if ($LASTEXITCODE -ne 0) { throw 'Failed to inspect commit scope' } foreach ($file in $changed) { @@ -40,7 +40,7 @@ jobs: } git diff --check HEAD^ HEAD if ($LASTEXITCODE -ne 0) { throw 'Whitespace errors' } - rustfmt --check --edition 2024 --config skip_children=true src/agent_automation/store.rs src/project_clone.rs src/self_update.rs + rustfmt --check --edition 2024 --config skip_children=true src/agent_automation/store.rs src/project_clone.rs src/self_update.rs src/owner_chat.rs if ($LASTEXITCODE -ne 0) { throw 'Rustfmt check failed' } - name: Validate native source and test compilation run: | @@ -54,6 +54,8 @@ jobs: if ($LASTEXITCODE -ne 0) { throw 'Windows path test failed' } cargo test --locked --lib windows_worker_reports_start_and_completes_a_unicode_file_update -j 2 -- --nocapture if ($LASTEXITCODE -ne 0) { throw 'Windows status publication test failed' } + cargo test --locked --lib owner_goal_commands_are_authenticated_idempotent_local_and_visible_in_state -j 2 -- --nocapture + if ($LASTEXITCODE -ne 0) { throw 'Goal activation wake test failed' } cargo test --locked --lib browser_action_lanes_default_to_one_and_are_bounded -j 2 if ($LASTEXITCODE -ne 0) { throw 'Single browser lane default test failed' } - name: Run full Rust library regression suite From f034dcd2f64ad6ffdaadee2db447238b362bc0cf Mon Sep 17 00:00:00 2001 From: tomi Date: Wed, 18 Nov 2026 05:54:20 +0100 Subject: [PATCH 011/118] fix(goal): preserve terminal handoff receipts on the single-lane v2.4 base --- .github/workflows/single-lane-v240-ci.yml | 6 +- src/agent_automation/store.rs | 47 +++- src/agent_automation/supervisor.rs | 10 + src/agent_automation/turn_renewal.rs | 326 +++++++++++++++++++++- 4 files changed, 383 insertions(+), 6 deletions(-) diff --git a/.github/workflows/single-lane-v240-ci.yml b/.github/workflows/single-lane-v240-ci.yml index 58c0f018..d2d2e36e 100644 --- a/.github/workflows/single-lane-v240-ci.yml +++ b/.github/workflows/single-lane-v240-ci.yml @@ -32,7 +32,7 @@ jobs: - name: Bound changes to durability and Windows tests run: | $ErrorActionPreference = 'Stop' - $allowed = @('src/agent_automation/store.rs','src/project_clone.rs','src/self_update.rs','src/owner_chat.rs','.github/workflows/single-lane-v240-ci.yml','docs/SINGLE_LANE_V240_RECOVERY.md') + $allowed = @('src/agent_automation/store.rs','src/project_clone.rs','src/self_update.rs','src/owner_chat.rs','src/agent_automation/supervisor.rs','src/agent_automation/turn_renewal.rs','.github/workflows/single-lane-v240-ci.yml','docs/SINGLE_LANE_V240_RECOVERY.md') $changed = @(git diff --name-only HEAD^ HEAD) if ($LASTEXITCODE -ne 0) { throw 'Failed to inspect commit scope' } foreach ($file in $changed) { @@ -40,7 +40,7 @@ jobs: } git diff --check HEAD^ HEAD if ($LASTEXITCODE -ne 0) { throw 'Whitespace errors' } - rustfmt --check --edition 2024 --config skip_children=true src/agent_automation/store.rs src/project_clone.rs src/self_update.rs src/owner_chat.rs + rustfmt --check --edition 2024 --config skip_children=true src/agent_automation/store.rs src/project_clone.rs src/self_update.rs src/owner_chat.rs src/agent_automation/supervisor.rs src/agent_automation/turn_renewal.rs if ($LASTEXITCODE -ne 0) { throw 'Rustfmt check failed' } - name: Validate native source and test compilation run: | @@ -56,6 +56,8 @@ jobs: if ($LASTEXITCODE -ne 0) { throw 'Windows status publication test failed' } cargo test --locked --lib owner_goal_commands_are_authenticated_idempotent_local_and_visible_in_state -j 2 -- --nocapture if ($LASTEXITCODE -ne 0) { throw 'Goal activation wake test failed' } + cargo test --locked --lib completed_goal_renewal_tests -j 2 -- --nocapture + if (0 -ne 0) { throw 'Terminal handoff retirement regression failed' } cargo test --locked --lib browser_action_lanes_default_to_one_and_are_bounded -j 2 if ($LASTEXITCODE -ne 0) { throw 'Single browser lane default test failed' } - name: Run full Rust library regression suite diff --git a/src/agent_automation/store.rs b/src/agent_automation/store.rs index 6bf9ef57..71e4554a 100644 --- a/src/agent_automation/store.rs +++ b/src/agent_automation/store.rs @@ -339,6 +339,8 @@ pub struct AutomationTaskState { offline_response_grace_ms: u64, #[serde(skip_serializing_if = "super::turn_renewal::TurnRenewalState::is_empty")] pub turn_renewal: super::turn_renewal::TurnRenewalState, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub retired_terminal_handoffs: Vec, #[serde(default)] owner_goal_requests: Vec, } @@ -363,6 +365,7 @@ impl Default for AutomationTaskState { retry_timings: RetryTimings::default(), offline_response_grace_ms: 0, turn_renewal: Default::default(), + retired_terminal_handoffs: Vec::new(), owner_goal_requests: Vec::new(), } } @@ -1190,6 +1193,16 @@ impl AgentAutomationStore { ) -> Result { validate_goal_markdown(markdown)?; self.mutate(task, |state| { + let previous_handoff_retired = if state.goal.as_ref().is_some_and(|goal| { + matches!(goal.status, GoalStatus::Completed | GoalStatus::Blocked | GoalStatus::Error) + }) && state.turn_renewal.handoff.is_some() { + if !super::turn_renewal::retire_obsolete_terminal_handoff(state, now_ms) { + return Err("A previous goal still has an unverified or active handoff; preserve its Send and resolve it before replacing the goal".into()); + } + true + } else { + false + }; let revision = state.goal.as_ref().map_or(Ok(1), |goal| { goal.revision .checked_add(1) @@ -1217,7 +1230,7 @@ impl AgentAutomationStore { state.agents.latest_report = None; state.agents.report_at_ms = None; state.goal_wake = GoalWakeState::default(); - if state.action.goal_revision.is_some() { + if previous_handoff_retired || state.action.goal_revision.is_some() { state.action = AutomationActionState::default(); } Ok(goal) @@ -1463,6 +1476,16 @@ impl AgentAutomationStore { let mut updated_active_goal = false; let (kind, goal) = match command { OwnerGoalCommand::Set { markdown } => { + let previous_handoff_retired = if state.goal.as_ref().is_some_and(|goal| { + matches!(goal.status, GoalStatus::Completed | GoalStatus::Blocked | GoalStatus::Error) + }) && state.turn_renewal.handoff.is_some() { + if !super::turn_renewal::retire_obsolete_terminal_handoff(state, now_ms) { + return Err("A previous goal still has an unverified or active handoff; preserve its Send and resolve it before replacing the goal".into()); + } + true + } else { + false + }; let revision = state.goal.as_ref().map_or(Ok(1), |goal| { goal.revision .checked_add(1) @@ -1510,7 +1533,7 @@ impl AgentAutomationStore { && !state.action.automatic_retry_in_progress && !state.action.automatic_retry_paused && state.suspended_retry.is_none(); - if (!preserve_action && state.action.goal_revision.is_some()) || superseded_unsent_goal { + if (!preserve_action && state.action.goal_revision.is_some()) || superseded_unsent_goal || previous_handoff_retired { state.action = AutomationActionState::default(); } (OwnerGoalCommandKind::Set, Some(goal)) @@ -4361,6 +4384,26 @@ fn validate_state(state: &AutomationTaskState) -> Result<(), String> { } validate_action(&state.action)?; validate_goal_wake(&state.goal_wake)?; + if state.retired_terminal_handoffs.len() > super::turn_renewal::MAX_RETIRED_TERMINAL_HANDOFFS { + return Err("Agent automation retired handoff history is too large".into()); + } + for retired in &state.retired_terminal_handoffs { + let Some(handoff) = retired.renewal.handoff.as_ref() else { + return Err("Retired handoff is missing its original receipt".into()); + }; + if !matches!( + retired.goal_status, + GoalStatus::Completed | GoalStatus::Blocked | GoalStatus::Error + ) || handoff.report_complete + || handoff.requested_at_ms <= retired.goal_finished_at_ms + || retired.retired_at_ms < handoff.requested_at_ms + || retired.action.send_accepted != Some(true) + || retired.action.status != AutomationActionStatus::Idle + { + return Err("Retired terminal-goal handoff history is invalid".into()); + } + validate_action(&retired.action)?; + } if let Some(previous) = &state.suspended_retry { validate_action(&previous.action)?; validate_goal_wake(&previous.goal_wake)?; diff --git a/src/agent_automation/supervisor.rs b/src/agent_automation/supervisor.rs index 077a9cda..8d61e5a7 100644 --- a/src/agent_automation/supervisor.rs +++ b/src/agent_automation/supervisor.rs @@ -2307,6 +2307,16 @@ impl AgentAutomationSupervisor { )? { state = task.store.load(&task.task)?; } + // A terminal goal cannot produce a new model handoff. Archive a + // mistakenly requested post-finish renewal as unverified evidence, + // rather than blocking the slot or pretending its final was sent. + if super::turn_renewal::can_retire_obsolete_terminal_handoff(&state) + && task + .store + .retire_finished_goal_handoff(&task.task, now_ms)? + { + state = task.store.load(&task.task)?; + } task.store.notify_state(&task.chat, &state).await; let renewal_config = task.store.turn_renewal_settings()?; let renewal_enabled = state.turn_renewal.send.as_ref().is_some_and(|send| { diff --git a/src/agent_automation/turn_renewal.rs b/src/agent_automation/turn_renewal.rs index 60d3b1f6..f5a0872f 100644 --- a/src/agent_automation/turn_renewal.rs +++ b/src/agent_automation/turn_renewal.rs @@ -137,6 +137,81 @@ pub struct TurnHandoff { pub requested_at_ms: u64, pub report_complete: bool, } + +/// A renewal requested after an already finished goal is not another task +/// continuation. Keep its exact unverified receipt rather than claim that a +/// final handoff was delivered or quietly discard the accepted Send. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields, rename_all = "camelCase")] +pub struct RetiredTerminalHandoff { + pub goal_revision: u64, + pub goal_status: GoalStatus, + pub goal_finished_at_ms: u64, + pub retired_at_ms: u64, + pub renewal: TurnRenewalState, + pub action: super::AutomationActionState, +} + +pub(super) const MAX_RETIRED_TERMINAL_HANDOFFS: usize = 16; + +/// Check an already loaded snapshot without acquiring a write lock or +/// republishing automation.json on every scheduler tick. +pub(super) fn can_retire_obsolete_terminal_handoff(state: &super::AutomationTaskState) -> bool { + let Some(goal) = state.goal.as_ref() else { + return false; + }; + if !matches!( + goal.status, + GoalStatus::Completed | GoalStatus::Blocked | GoalStatus::Error + ) { + return false; + } + let Some(finished_at_ms) = goal.finished_at_ms else { + return false; + }; + let Some(handoff) = state.turn_renewal.handoff.as_ref() else { + return false; + }; + if handoff.report_complete + || handoff.requested_at_ms <= finished_at_ms + || state.action.send_accepted != Some(true) + || state.action.status != AutomationActionStatus::Idle + { + return false; + } + true +} + +pub(super) fn retire_obsolete_terminal_handoff( + state: &mut super::AutomationTaskState, + now_ms: u64, +) -> bool { + if !can_retire_obsolete_terminal_handoff(state) { + return false; + } + let goal = state + .goal + .as_ref() + .expect("eligibility requires terminal goal"); + let finished_at_ms = goal + .finished_at_ms + .expect("eligibility requires finish time"); + state + .retired_terminal_handoffs + .push(RetiredTerminalHandoff { + goal_revision: goal.revision, + goal_status: goal.status, + goal_finished_at_ms: finished_at_ms, + retired_at_ms: now_ms, + renewal: state.turn_renewal.clone(), + action: state.action.clone(), + }); + if state.retired_terminal_handoffs.len() > MAX_RETIRED_TERMINAL_HANDOFFS { + state.retired_terminal_handoffs.remove(0); + } + state.turn_renewal = TurnRenewalState::default(); + true +} impl TurnRenewalState { pub fn is_empty(&self) -> bool { self.send.is_none() && self.handoff.is_none() && self.resume_wait_until_ms.is_none() @@ -144,6 +219,58 @@ impl TurnRenewalState { } impl AgentAutomationStore { + pub(crate) fn retire_finished_goal_handoff( + &self, + task: &ConversationIdentity, + now_ms: u64, + ) -> Result { + // mutate() always persists state. Do not call it for an ineligible + // task; recheck eligibility under its lock to handle concurrent state. + if !can_retire_obsolete_terminal_handoff(&self.load(task)?) { + return Ok(false); + } + self.mutate(task, |state| { + Ok(retire_obsolete_terminal_handoff(state, now_ms)) + }) + } + + pub(super) fn mark_unverified_handoff_stalled( + &self, + task: &ConversationIdentity, + expected: &super::AutomationTaskState, + now_ms: u64, + ) -> Result { + self.mutate(task, |state| { + if state.action != expected.action + || state.turn_renewal.handoff != expected.turn_renewal.handoff + || state.action.kind != Some(AutomationActionKind::TurnRenewal) + || state.action.send_accepted != Some(true) + || !matches!( + state.action.status, + AutomationActionStatus::Idle + | AutomationActionStatus::Navigating + | AutomationActionStatus::Sending + | AutomationActionStatus::Generating + ) + || state.turn_renewal.handoff.as_ref().is_none_or(|handoff| { + handoff.report_complete + || now_ms.saturating_sub(handoff.requested_at_ms) < 30 * 60_000 + }) + || (state.action.status != AutomationActionStatus::Idle + && state + .action + .updated_at_ms + .is_none_or(|at| now_ms.saturating_sub(at) < 32 * 60_000)) + { + return Ok(false); + } + // This is an observation failure, not an unsent user message. + // Preserve the accepted Send, action ID, and its original clock. + state.action.status = AutomationActionStatus::Stalled; + state.action.last_error = Some(UNVERIFIED_HANDOFF_WARNING.into()); + Ok(true) + }) + } pub fn turn_renewal_settings(&self) -> Result { crate::global_settings::turn_renewal_settings( self.settings_path.as_deref(), @@ -336,8 +463,13 @@ impl AgentAutomationStore { return Ok(None); } self.mutate(task, |state| { - if state.goal.as_ref().is_some_and(|goal| goal.status != GoalStatus::Active) { - clear_pending_renewal(state); + // Once a goal is terminal, no model continuation is possible. + // Non-goal chats (goal=None) still use ordinary timed renewal. + if state + .goal + .as_ref() + .is_some_and(|goal| goal.status != GoalStatus::Active) + { return Ok(None); } let Some(send) = &state.turn_renewal.send else {return Ok(None)}; @@ -539,6 +671,7 @@ impl AgentAutomationStore { #[cfg(test)] mod completed_goal_renewal_tests { + use super::super::{GoalFinish, OwnerGoalCommand}; use super::*; use crate::agent_automation::GoalFinish; @@ -655,4 +788,193 @@ mod completed_goal_renewal_tests { assert!(state.turn_renewal.is_empty()); } } + + fn finished_goal_with_post_finish_handoff() -> ( + tempfile::TempDir, + AgentAutomationStore, + ConversationIdentity, + ) { + let root = tempfile::tempdir().unwrap(); + let mut store = AgentAutomationStore::new(root.path().join("chats")).unwrap(); + store.renewal_config.enabled = true; + let task = + ConversationIdentity::from_openai_session("completed-goal-stale-handoff").unwrap(); + let goal = store.set_goal(&task, "Completed test goal", 100).unwrap(); + store.run_goal(&task, goal.revision, 150).unwrap(); + store + .finish_goal( + &task, + goal.revision, + GoalFinish::Completed { + summary: Some("Verified work completed".into()), + }, + 3_000, + ) + .unwrap(); + store + .mutate(&task, |state| { + state.pairing.generation = 1; + state.pairing.verified_owner_generation = Some(0); + state.pairing.verified_at_ms = Some(200); + state.pairing.canonical_url = + Some("https://chatgpt.com/c/completed-goal-stale-handoff".into()); + state.action.id = Some("accepted-completed-goal".into()); + state.action.kind = Some(AutomationActionKind::OfflineGoal); + state.action.goal_revision = Some(goal.revision); + state.action.status = AutomationActionStatus::Idle; + state.action.send_accepted = Some(true); + state.action.pairing_generation = Some(1); + state.turn_renewal.send = Some(TurnSend { + action_id: "accepted-completed-goal".into(), + at_ms: 250, + model: Some("gpt-6-astra".into()), + effort: Some("max".into()), + pairing_generation: 1, + owner_generation: 0, + }); + state.turn_renewal.handoff = Some(TurnHandoff { + id: "renew-completed-goal".into(), + requested_at_ms: 4_000, + report_complete: false, + }); + Ok(()) + }) + .unwrap(); + (root, store, task) + } + + #[test] + fn a_finished_goal_does_not_emit_another_turn_handoff() { + let (_root, store, task) = finished_goal_with_post_finish_handoff(); + let old = store.load(&task).unwrap(); + assert!( + store + .turn_renewal_notice(&task, 99 * 60_000) + .unwrap() + .is_none(), + "expired send time must not renew an already completed goal" + ); + let after = store.load(&task).unwrap(); + assert_eq!(after.action, old.action); + assert_eq!(after.turn_renewal, old.turn_renewal); + } + + #[test] + fn post_completion_handoff_is_archived_unverified_and_never_resends() { + let (_root, store, task) = finished_goal_with_post_finish_handoff(); + let old = store.load(&task).unwrap(); + assert!(can_retire_obsolete_terminal_handoff(&old)); + assert!(store.retire_finished_goal_handoff(&task, 6_000).unwrap()); + assert!(!store.retire_finished_goal_handoff(&task, 6_001).unwrap()); + let recovered = store.load(&task).unwrap(); + assert!(!can_retire_obsolete_terminal_handoff(&recovered)); + assert!(recovered.turn_renewal.is_empty()); + assert_eq!(recovered.goal, old.goal); + assert_eq!(recovered.action, old.action); + assert_eq!(recovered.retired_terminal_handoffs.len(), 1); + let receipt = &recovered.retired_terminal_handoffs[0]; + assert_eq!(receipt.renewal, old.turn_renewal); + assert_eq!(receipt.action, old.action); + assert_eq!(receipt.goal_revision, 1); + assert!(!receipt.renewal.handoff.as_ref().unwrap().report_complete); + let json = serde_json::to_string(&recovered).unwrap(); + let decoded: super::super::AutomationTaskState = serde_json::from_str(&json).unwrap(); + assert_eq!( + decoded.retired_terminal_handoffs, + recovered.retired_terminal_handoffs + ); + let next = store + .apply_owner_goal_command( + &task, + "new-verified-work", + OwnerGoalCommand::Set { + markdown: "New owner-approved work".into(), + }, + 7_000, + ) + .unwrap(); + assert_eq!(next.goal.unwrap().status, GoalStatus::Active); + assert_eq!( + store.load(&task).unwrap().retired_terminal_handoffs.len(), + 1 + ); + } + + #[test] + fn owner_replacement_archives_stale_terminal_handoff_atomically() { + let (_root, store, task) = finished_goal_with_post_finish_handoff(); + let receipt = store + .apply_owner_goal_command( + &task, + "supersede-stale-terminal", + OwnerGoalCommand::Set { + markdown: "Continue new owner goal".into(), + }, + 6_000, + ) + .unwrap(); + assert_eq!(receipt.goal.unwrap().revision, 2); + let after = store.load(&task).unwrap(); + assert!(after.turn_renewal.is_empty()); + assert_eq!(after.retired_terminal_handoffs.len(), 1); + assert_eq!( + after.retired_terminal_handoffs[0] + .renewal + .handoff + .as_ref() + .unwrap() + .id, + "renew-completed-goal" + ); + assert!( + !after.retired_terminal_handoffs[0] + .renewal + .handoff + .as_ref() + .unwrap() + .report_complete + ); + } + + #[test] + fn active_goal_and_pre_finish_handoffs_are_not_retired() { + let (_root, store, task) = finished_goal_with_post_finish_handoff(); + store + .mutate(&task, |state| { + state.goal.as_mut().unwrap().status = GoalStatus::Active; + state.goal.as_mut().unwrap().finished_at_ms = None; + state.goal.as_mut().unwrap().summary = None; + Ok(()) + }) + .unwrap(); + assert!(!can_retire_obsolete_terminal_handoff( + &store.load(&task).unwrap() + )); + let state_file = store.task_directory(&task).unwrap().join("automation.json"); + let before = std::fs::metadata(&state_file).unwrap().modified().unwrap(); + std::thread::sleep(std::time::Duration::from_millis(75)); + assert!(!store.retire_finished_goal_handoff(&task, 6_000).unwrap()); + assert_eq!( + before, + std::fs::metadata(&state_file).unwrap().modified().unwrap(), + "an ineligible scheduler tick must not republish automation state" + ); + store + .mutate(&task, |state| { + state.goal.as_mut().unwrap().status = GoalStatus::Completed; + state.goal.as_mut().unwrap().finished_at_ms = Some(3_000); + state.goal.as_mut().unwrap().summary = Some("Verified work completed".into()); + state.turn_renewal.handoff.as_mut().unwrap().requested_at_ms = 2_900; + Ok(()) + }) + .unwrap(); + assert!(!can_retire_obsolete_terminal_handoff( + &store.load(&task).unwrap() + )); + assert!(!store.retire_finished_goal_handoff(&task, 6_000).unwrap()); + assert_eq!( + store.load(&task).unwrap().retired_terminal_handoffs.len(), + 0 + ); + } } From 47ded8b0b1420e5e8d8417dbe92ad5405bde6d2e Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Wed, 18 Nov 2026 05:58:37 +0100 Subject: [PATCH 012/118] fix(goal): restore accepted-handoff warning and de-duplicate test imports --- src/agent_automation/turn_renewal.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/agent_automation/turn_renewal.rs b/src/agent_automation/turn_renewal.rs index f5a0872f..59f8c3ac 100644 --- a/src/agent_automation/turn_renewal.rs +++ b/src/agent_automation/turn_renewal.rs @@ -10,6 +10,7 @@ use sha2::{Digest, Sha256}; pub(super) const INCOMPLETE_HANDOFF_ERROR: &str = "Turn handoff report did not complete; recovering the active goal in a new turn from saved progress"; pub const NOTICE_FIELD: &str = "turn_renewal_required"; +pub(super) const UNVERIFIED_HANDOFF_WARNING: &str = "ChatGPT has not confirmed the final turn-renewal handoff after 30 minutes. The previous Send was accepted; Codexify did not click Retry or resend it."; pub const NOTICE_DESCRIPTION: &str = "Turn renewal overrides the ordinary non-terminal chat protocol: write the requested handoff as a normal final ChatGPT answer and end this turn. Codexify will continue automatically after that answer is complete."; pub(super) fn clear_pending_renewal(state: &mut AutomationTaskState) { @@ -671,7 +672,7 @@ impl AgentAutomationStore { #[cfg(test)] mod completed_goal_renewal_tests { - use super::super::{GoalFinish, OwnerGoalCommand}; + use super::super::OwnerGoalCommand; use super::*; use crate::agent_automation::GoalFinish; From c2706cdd7751d8aded76906407c8228017825fc6 Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Wed, 18 Nov 2026 07:03:50 +0100 Subject: [PATCH 013/118] fix(mcp): prevent server-bound upstream OAuth metadata from forcing God v5 relink --- src/bridge.rs | 264 +++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 261 insertions(+), 3 deletions(-) diff --git a/src/bridge.rs b/src/bridge.rs index 68bdcef4..93003acc 100644 --- a/src/bridge.rs +++ b/src/bridge.rs @@ -116,12 +116,100 @@ struct BridgedTool { annotations: Option, icons: Option>, meta: Option, + server_bound_upstream_auth: bool, peer: Peer, tool_timeout: Option, control: Arc, resources: Arc, } +/// Cloudflare and other remote MCPs can advertise their *own* OAuth requirements, +/// even when Codexify already authenticates upstream using a configured bearer token. +/// Forwarding those schemes as God v5 tool metadata causes ChatGPT to request OAuth +/// for the wrong application (which has no upstream-browser setup URL). +/// Keep other upstream metadata and do not alter tools without bound credentials. +fn forward_server_bound_tool_metadata( + meta: Option, + server_bound_auth: bool, +) -> Option { + let mut meta = meta?; + if server_bound_auth { + meta.0.remove("securitySchemes"); + } + (!meta.0.is_empty()).then_some(meta) +} + +/// Only display literal, bounded scope identifiers from an upstream challenge. +/// Never forward resource_metadata URLs or raw WWW-Authenticate values. +fn safe_declared_scope(challenge: &Value) -> Option { + let headers: Vec<&str> = match challenge { + Value::String(header) => vec![header], + Value::Array(values) => values.iter().filter_map(Value::as_str).collect(), + _ => return None, + }; + headers.into_iter().find_map(|header| { + let (_, remainder) = header.split_once("scope=\"")?; + let (scope, _) = remainder.split_once('"')?; + (!scope.is_empty() + && scope.len() <= 128 + && scope.chars().all(|ch| { + ch.is_ascii_alphanumeric() || matches!(ch, '_' | '-' | ':' | '.' | '/' | ' ') + })) + .then(|| scope.to_owned()) + }) +} + +/// An upstream OAuth challenge is not a valid OAuth challenge for Codexify's +/// already-authorized downstream MCP connection. Fail closed with a sanitized, +/// structured upstream diagnostic rather than a broken ChatGPT relink action. +fn sanitize_server_bound_auth_result( + mut result: ToolResult, + server_bound_auth: bool, +) -> ToolResult { + if !server_bound_auth { + return result; + } + let challenge = result + .meta + .as_mut() + .and_then(|meta| meta.0.remove("mcp/www_authenticate")); + let Some(challenge) = challenge else { + return result; + }; + + let challenge_code = challenge.to_string().to_ascii_lowercase(); + let code = if challenge_code.contains("insufficient_scope") { + "insufficient_scope" + } else if challenge_code.contains("invalid_token") { + "invalid_token" + } else { + "authorization_required" + }; + let required_scope = safe_declared_scope(&challenge); + let scope_note = required_scope + .as_ref() + .map(|scope| format!(" Required scope: {scope}.")) + .unwrap_or_default(); + + result.is_error = true; + result.structured_content = None; + result.content = vec![ToolContent::Text(format!( + "Upstream MCP authorization failed ({code}). Codexify already manages the \ + upstream credential; verify the existing server-side token and its read \ + permissions instead of using ChatGPT Connect.{scope_note}" + ))]; + let meta = result.meta.get_or_insert_with(MetaObject::new); + meta.0.insert( + "io.github.devnoname120/codexify/upstream_auth_error".into(), + json!({ + "code": code, + "credential_source": "server_bound", + "required_scope": required_scope + }), + ); + result +} + impl BridgedTool { async fn run(&self, args: Value, cancellation: Option<&CancellationToken>) -> ToolResult { let mut params = CallToolRequestParams::new(self.original_name.clone()); @@ -131,7 +219,7 @@ impl BridgedTool { params = params.with_arguments(obj.clone()); } - forward_tool_call( + let result = forward_tool_call( &self.peer, params, &self.server, @@ -143,7 +231,8 @@ impl BridgedTool { control: &self.control, }, ) - .await + .await; + sanitize_server_bound_auth_result(result, self.server_bound_upstream_auth) } } @@ -585,6 +674,8 @@ pub async fn connect_upstreams(config: &AppConfig) -> Bridge { ); } McpToolExposure::Direct => { + let server_bound_upstream_auth = spec.bearer_token_env_var.is_some() + || configures_authorization_header(spec); report.push(format!("{server_name} -> direct ({count} tool(s))")); let mut used: std::collections::HashSet = std::collections::HashSet::new(); @@ -616,7 +707,11 @@ pub async fn connect_upstreams(config: &AppConfig) -> Bridge { .map(|schema| Value::Object((*schema).clone())), annotations: tool.annotations, icons: tool.icons, - meta: tool.meta, + meta: forward_server_bound_tool_metadata( + tool.meta, + server_bound_upstream_auth, + ), + server_bound_upstream_auth, peer: peer.clone(), tool_timeout, control: control.clone(), @@ -1525,6 +1620,10 @@ mod tests { tool_meta .0 .insert("vendor".into(), Value::String("hex-rays".into())); + tool_meta.0.insert( + "securitySchemes".into(), + json!([{"type": "oauth2", "scopes": ["account:read"]}]), + ); tools.push( rmcp::model::Tool::new( "decompile_function", @@ -2395,6 +2494,165 @@ mod tests { let _ = second_server_task.await; } + #[test] + fn server_bound_oauth_metadata_is_not_misadvertised_as_chatgpt_access() { + let mut upstream = MetaObject::new(); + upstream.0.insert( + "securitySchemes".into(), + json!([{"type": "oauth2", "scopes": ["account:read"]}]), + ); + upstream + .0 + .insert("vendor".into(), Value::String("fixture".into())); + let existing = forward_server_bound_tool_metadata(Some(upstream.clone()), false).unwrap(); + assert!(existing.0.contains_key("securitySchemes")); + + let forwarded = forward_server_bound_tool_metadata(Some(upstream), true).unwrap(); + assert!(!forwarded.0.contains_key("securitySchemes")); + assert_eq!(forwarded.0.get("vendor"), Some(&json!("fixture"))); + } + + fn upstream_auth_fixture(challenge: &str) -> ToolResult { + let mut result = ToolResult::error("Upstream declined authorization"); + let mut meta = MetaObject::new(); + meta.0 + .insert("mcp/www_authenticate".into(), json!([challenge])); + result.meta = Some(meta); + result.structured_content = Some(json!({"untrusted": "private-fixture"})); + result + } + + #[test] + fn insufficient_scope_returns_specific_safe_error_without_consent_url() { + let result = sanitize_server_bound_auth_result( + upstream_auth_fixture( + "Bearer error=\"insufficient_scope\", scope=\"Account:Read\", \ + resource_metadata=\"https://auth.example.invalid/secret?token=do-not-log\"", + ), + true, + ); + assert!(result.is_error); + assert!(result.structured_content.is_none()); + assert!(!result + .meta + .as_ref() + .unwrap() + .0 + .contains_key("mcp/www_authenticate")); + let ToolContent::Text(message) = &result.content[0] else { + panic!("expected safe text diagnostic"); + }; + assert!(message.contains("insufficient_scope")); + assert!(message.contains("Account:Read")); + assert!(!message.contains("auth.example.invalid")); + assert!(!message.contains("do-not-log")); + assert_eq!( + result.meta.as_ref().unwrap().0 + ["io.github.devnoname120/codexify/upstream_auth_error"]["required_scope"], + json!("Account:Read") + ); + } + + #[test] + fn expired_upstream_grant_returns_recoverable_error_not_chatgpt_relink() { + let result = sanitize_server_bound_auth_result( + upstream_auth_fixture("Bearer error=\"invalid_token\""), + true, + ); + assert!(result.is_error); + let ToolContent::Text(message) = &result.content[0] else { + panic!("expected error"); + }; + assert!(message.contains("invalid_token")); + assert!(message.contains("existing server-side token")); + assert!(!message.contains("https://")); + } + + #[test] + fn malformed_upstream_consent_url_is_not_forwarded_to_downstream() { + let result = sanitize_server_bound_auth_result( + upstream_auth_fixture( + "Bearer error=\"invalid_token\", resource_metadata=\"javascript:alert(1)\"", + ), + true, + ); + let ToolContent::Text(message) = &result.content[0] else { + panic!("expected error"); + }; + assert!(!message.contains("javascript:")); + assert!(!message.contains("resource_metadata")); + assert!(!result.meta.unwrap().0.contains_key("mcp/www_authenticate")); + } + + #[test] + fn repeated_upstream_denial_stays_stable_without_oauth_prompt() { + let first = sanitize_server_bound_auth_result( + upstream_auth_fixture("Bearer error=\"invalid_token\""), + true, + ); + let second = sanitize_server_bound_auth_result(first, true); + assert!(second.is_error); + assert_eq!(second.content.len(), 1); + assert!(!second.meta.unwrap().0.contains_key("mcp/www_authenticate")); + } + + #[test] + fn unrelated_mcp_and_cloudflare_403_500_errors_are_not_rewritten() { + let unbound = sanitize_server_bound_auth_result( + upstream_auth_fixture("Bearer error=\"invalid_token\""), + false, + ); + assert!(unbound.meta.unwrap().0.contains_key("mcp/www_authenticate")); + + for code in [403, 500] { + let message = format!("Cloudflare HTTP {code} test fixture"); + let result = sanitize_server_bound_auth_result(ToolResult::error(&message), true); + let ToolContent::Text(actual) = &result.content[0] else { + panic!("expected original provider error"); + }; + assert_eq!(actual, &message); + } + } + + #[tokio::test] + async fn direct_mode_with_server_bound_auth_uses_existing_grant_without_oauth_meta() { + let (url, _calls, server_task) = spawn_catalog_upstream().await; + let mut config = crate::config::default_config(std::env::temp_dir()); + config.mcp_servers.insert( + "cloudflare-api".to_string(), + McpServerSpec { + url: Some(url), + mode: Some(McpToolExposure::Direct), + http_headers: HashMap::from([( + "Authorization".to_string(), + "Bearer fixture-token".to_string(), + )]), + ..Default::default() + }, + ); + let bridge = connect_upstreams(&config).await; + let tool = bridge + .tools + .iter() + .find(|tool| tool.name() == "cloudflare_api__decompile_function") + .expect("Cloudflare mock tool should be exposed"); + let meta = tool.meta().expect("unrelated upstream metadata retained"); + assert_eq!(meta.0.get("vendor"), Some(&json!("hex-rays"))); + assert!(!meta.0.contains_key("securitySchemes")); + assert_eq!(tool.annotations().unwrap().read_only_hint, Some(true)); + + let response = call_bridge_tool( + &bridge, + "cloudflare_api__decompile_function", + json!({"location": {"virtual_address": "0x01"}}), + ) + .await; + assert!(!response.is_error); + drop(bridge); + server_task.abort(); + let _ = server_task.await; + } + #[tokio::test] async fn explicit_direct_mode_retains_per_tool_exposure_and_metadata() { let (url, calls, server_task) = spawn_catalog_upstream().await; From a8e416950bdd89998e8ac41dd9f441056eda179f Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Wed, 18 Nov 2026 07:04:10 +0100 Subject: [PATCH 014/118] ci(mcp): exercise bounded upstream authorization and no-relink regressions --- .github/workflows/single-lane-v240-ci.yml | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/.github/workflows/single-lane-v240-ci.yml b/.github/workflows/single-lane-v240-ci.yml index d2d2e36e..779183a2 100644 --- a/.github/workflows/single-lane-v240-ci.yml +++ b/.github/workflows/single-lane-v240-ci.yml @@ -2,7 +2,7 @@ name: Single-lane v2.4 validation (no deployment) on: push: - branches: [fix/single-lane-v240-stable-20261118, fix/single-lane-v240-goal-parity-20261118] + branches: [fix/single-lane-v240-stable-20261118, fix/single-lane-v240-goal-parity-20261118, fix/godv5-cloudflare-oauth-meta-v240-20261118] workflow_dispatch: permissions: @@ -32,7 +32,7 @@ jobs: - name: Bound changes to durability and Windows tests run: | $ErrorActionPreference = 'Stop' - $allowed = @('src/agent_automation/store.rs','src/project_clone.rs','src/self_update.rs','src/owner_chat.rs','src/agent_automation/supervisor.rs','src/agent_automation/turn_renewal.rs','.github/workflows/single-lane-v240-ci.yml','docs/SINGLE_LANE_V240_RECOVERY.md') + $allowed = @('src/agent_automation/store.rs','src/project_clone.rs','src/self_update.rs','src/owner_chat.rs','src/agent_automation/supervisor.rs','src/agent_automation/turn_renewal.rs','src/bridge.rs','.github/workflows/single-lane-v240-ci.yml','docs/SINGLE_LANE_V240_RECOVERY.md') $changed = @(git diff --name-only HEAD^ HEAD) if ($LASTEXITCODE -ne 0) { throw 'Failed to inspect commit scope' } foreach ($file in $changed) { @@ -40,7 +40,7 @@ jobs: } git diff --check HEAD^ HEAD if ($LASTEXITCODE -ne 0) { throw 'Whitespace errors' } - rustfmt --check --edition 2024 --config skip_children=true src/agent_automation/store.rs src/project_clone.rs src/self_update.rs src/owner_chat.rs src/agent_automation/supervisor.rs src/agent_automation/turn_renewal.rs + rustfmt --check --edition 2024 --config skip_children=true src/agent_automation/store.rs src/project_clone.rs src/self_update.rs src/owner_chat.rs src/agent_automation/supervisor.rs src/agent_automation/turn_renewal.rs src/bridge.rs if ($LASTEXITCODE -ne 0) { throw 'Rustfmt check failed' } - name: Validate native source and test compilation run: | @@ -60,6 +60,10 @@ jobs: if (0 -ne 0) { throw 'Terminal handoff retirement regression failed' } cargo test --locked --lib browser_action_lanes_default_to_one_and_are_bounded -j 2 if ($LASTEXITCODE -ne 0) { throw 'Single browser lane default test failed' } + - name: Run MCP bridge authorization metadata regressions + run: | + cargo test --locked --lib bridge::tests:: -j 2 -- --nocapture + if ($LASTEXITCODE -ne 0) { throw 'MCP authorization bridge tests failed' } - name: Run full Rust library regression suite run: | cargo test --locked --lib -j 2 From 5f7b8f343bb3c30b0801c64eadcee88a5ccd699a Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Wed, 18 Nov 2026 07:09:18 +0100 Subject: [PATCH 015/118] style(mcp): format Cloudflare upstream OAuth boundary regression tests --- src/bridge.rs | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/src/bridge.rs b/src/bridge.rs index 93003acc..a49a433a 100644 --- a/src/bridge.rs +++ b/src/bridge.rs @@ -2533,12 +2533,14 @@ mod tests { ); assert!(result.is_error); assert!(result.structured_content.is_none()); - assert!(!result - .meta - .as_ref() - .unwrap() - .0 - .contains_key("mcp/www_authenticate")); + assert!( + !result + .meta + .as_ref() + .unwrap() + .0 + .contains_key("mcp/www_authenticate") + ); let ToolContent::Text(message) = &result.content[0] else { panic!("expected safe text diagnostic"); }; @@ -2547,8 +2549,8 @@ mod tests { assert!(!message.contains("auth.example.invalid")); assert!(!message.contains("do-not-log")); assert_eq!( - result.meta.as_ref().unwrap().0 - ["io.github.devnoname120/codexify/upstream_auth_error"]["required_scope"], + result.meta.as_ref().unwrap().0["io.github.devnoname120/codexify/upstream_auth_error"] + ["required_scope"], json!("Account:Read") ); } From 205a6ebe2cc0487c489a5d2b9a3ac8b3898dcad5 Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Wed, 18 Nov 2026 07:24:26 +0100 Subject: [PATCH 016/118] fix(mcp): prevent upstream Cloudflare whoami from impersonating God v5 profile --- src/bridge.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/bridge.rs b/src/bridge.rs index a49a433a..24fc64b6 100644 --- a/src/bridge.rs +++ b/src/bridge.rs @@ -134,7 +134,10 @@ fn forward_server_bound_tool_metadata( ) -> Option { let mut meta = meta?; if server_bound_auth { + // These belong to the upstream MCP's identity, not the Codexify app. + // A bridged Cloudflare profile tool is not the God v5 profile tool. meta.0.remove("securitySchemes"); + meta.0.remove("openai/profile"); } (!meta.0.is_empty()).then_some(meta) } @@ -1624,6 +1627,7 @@ mod tests { "securitySchemes".into(), json!([{"type": "oauth2", "scopes": ["account:read"]}]), ); + tool_meta.0.insert("openai/profile".into(), json!(true)); tools.push( rmcp::model::Tool::new( "decompile_function", @@ -2504,11 +2508,14 @@ mod tests { upstream .0 .insert("vendor".into(), Value::String("fixture".into())); + upstream.0.insert("openai/profile".into(), json!(true)); let existing = forward_server_bound_tool_metadata(Some(upstream.clone()), false).unwrap(); assert!(existing.0.contains_key("securitySchemes")); + assert_eq!(existing.0.get("openai/profile"), Some(&json!(true))); let forwarded = forward_server_bound_tool_metadata(Some(upstream), true).unwrap(); assert!(!forwarded.0.contains_key("securitySchemes")); + assert!(!forwarded.0.contains_key("openai/profile")); assert_eq!(forwarded.0.get("vendor"), Some(&json!("fixture"))); } @@ -2641,6 +2648,7 @@ mod tests { let meta = tool.meta().expect("unrelated upstream metadata retained"); assert_eq!(meta.0.get("vendor"), Some(&json!("hex-rays"))); assert!(!meta.0.contains_key("securitySchemes")); + assert!(!meta.0.contains_key("openai/profile")); assert_eq!(tool.annotations().unwrap().read_only_hint, Some(true)); let response = call_bridge_tool( From 51434f8473f816e644ae0a5c2456a1d3cba9c68a Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Wed, 18 Nov 2026 19:39:39 +0100 Subject: [PATCH 017/118] ci: check terminal-handoff regression exit status instead of constant false --- .github/workflows/single-lane-v240-ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/single-lane-v240-ci.yml b/.github/workflows/single-lane-v240-ci.yml index 779183a2..2b1cf66d 100644 --- a/.github/workflows/single-lane-v240-ci.yml +++ b/.github/workflows/single-lane-v240-ci.yml @@ -57,7 +57,7 @@ jobs: cargo test --locked --lib owner_goal_commands_are_authenticated_idempotent_local_and_visible_in_state -j 2 -- --nocapture if ($LASTEXITCODE -ne 0) { throw 'Goal activation wake test failed' } cargo test --locked --lib completed_goal_renewal_tests -j 2 -- --nocapture - if (0 -ne 0) { throw 'Terminal handoff retirement regression failed' } + if ($LASTEXITCODE -ne 0) { throw 'Terminal handoff retirement regression failed' } cargo test --locked --lib browser_action_lanes_default_to_one_and_are_bounded -j 2 if ($LASTEXITCODE -ne 0) { throw 'Single browser lane default test failed' } - name: Run MCP bridge authorization metadata regressions From 99f28ae76154e11421628325a60811e51448405d Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Wed, 18 Nov 2026 19:45:38 +0100 Subject: [PATCH 018/118] ci: validate entire upstream-to-custom delta instead of last commit only --- .github/workflows/single-lane-v240-ci.yml | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/.github/workflows/single-lane-v240-ci.yml b/.github/workflows/single-lane-v240-ci.yml index 2b1cf66d..3e006e5a 100644 --- a/.github/workflows/single-lane-v240-ci.yml +++ b/.github/workflows/single-lane-v240-ci.yml @@ -24,7 +24,7 @@ jobs: steps: - uses: actions/checkout@v5 with: - fetch-depth: 2 + fetch-depth: 0 - uses: dtolnay/rust-toolchain@stable with: components: rustfmt, clippy @@ -33,12 +33,15 @@ jobs: run: | $ErrorActionPreference = 'Stop' $allowed = @('src/agent_automation/store.rs','src/project_clone.rs','src/self_update.rs','src/owner_chat.rs','src/agent_automation/supervisor.rs','src/agent_automation/turn_renewal.rs','src/bridge.rs','.github/workflows/single-lane-v240-ci.yml','docs/SINGLE_LANE_V240_RECOVERY.md') - $changed = @(git diff --name-only HEAD^ HEAD) + $upstreamBase = 'b14eacde810531a451535ee546ca7e07c65c5a1d' + git merge-base --is-ancestor $upstreamBase HEAD + if ($LASTEXITCODE -ne 0) { throw 'Branch no longer descends from upstream v2.4.0; rebase required' } + $changed = @(git diff --name-only $upstreamBase HEAD) if ($LASTEXITCODE -ne 0) { throw 'Failed to inspect commit scope' } foreach ($file in $changed) { if ($file -notin $allowed) { throw "Unexpected changed file: $file" } } - git diff --check HEAD^ HEAD + git diff --check $upstreamBase HEAD if ($LASTEXITCODE -ne 0) { throw 'Whitespace errors' } rustfmt --check --edition 2024 --config skip_children=true src/agent_automation/store.rs src/project_clone.rs src/self_update.rs src/owner_chat.rs src/agent_automation/supervisor.rs src/agent_automation/turn_renewal.rs src/bridge.rs if ($LASTEXITCODE -ne 0) { throw 'Rustfmt check failed' } From 4b8349cc49515ef5ef152d8186c53daa554b5cba Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Wed, 18 Nov 2026 21:29:03 +0100 Subject: [PATCH 019/118] refactor(goal): drop unused handoff recovery code and simplify retirement predicate --- src/agent_automation/turn_renewal.rs | 46 ++-------------------------- 1 file changed, 2 insertions(+), 44 deletions(-) diff --git a/src/agent_automation/turn_renewal.rs b/src/agent_automation/turn_renewal.rs index 59f8c3ac..72b96ffb 100644 --- a/src/agent_automation/turn_renewal.rs +++ b/src/agent_automation/turn_renewal.rs @@ -10,7 +10,6 @@ use sha2::{Digest, Sha256}; pub(super) const INCOMPLETE_HANDOFF_ERROR: &str = "Turn handoff report did not complete; recovering the active goal in a new turn from saved progress"; pub const NOTICE_FIELD: &str = "turn_renewal_required"; -pub(super) const UNVERIFIED_HANDOFF_WARNING: &str = "ChatGPT has not confirmed the final turn-renewal handoff after 30 minutes. The previous Send was accepted; Codexify did not click Retry or resend it."; pub const NOTICE_DESCRIPTION: &str = "Turn renewal overrides the ordinary non-terminal chat protocol: write the requested handoff as a normal final ChatGPT answer and end this turn. Codexify will continue automatically after that answer is complete."; pub(super) fn clear_pending_renewal(state: &mut AutomationTaskState) { @@ -173,14 +172,10 @@ pub(super) fn can_retire_obsolete_terminal_handoff(state: &super::AutomationTask let Some(handoff) = state.turn_renewal.handoff.as_ref() else { return false; }; - if handoff.report_complete + !(handoff.report_complete || handoff.requested_at_ms <= finished_at_ms || state.action.send_accepted != Some(true) - || state.action.status != AutomationActionStatus::Idle - { - return false; - } - true + || state.action.status != AutomationActionStatus::Idle) } pub(super) fn retire_obsolete_terminal_handoff( @@ -235,43 +230,6 @@ impl AgentAutomationStore { }) } - pub(super) fn mark_unverified_handoff_stalled( - &self, - task: &ConversationIdentity, - expected: &super::AutomationTaskState, - now_ms: u64, - ) -> Result { - self.mutate(task, |state| { - if state.action != expected.action - || state.turn_renewal.handoff != expected.turn_renewal.handoff - || state.action.kind != Some(AutomationActionKind::TurnRenewal) - || state.action.send_accepted != Some(true) - || !matches!( - state.action.status, - AutomationActionStatus::Idle - | AutomationActionStatus::Navigating - | AutomationActionStatus::Sending - | AutomationActionStatus::Generating - ) - || state.turn_renewal.handoff.as_ref().is_none_or(|handoff| { - handoff.report_complete - || now_ms.saturating_sub(handoff.requested_at_ms) < 30 * 60_000 - }) - || (state.action.status != AutomationActionStatus::Idle - && state - .action - .updated_at_ms - .is_none_or(|at| now_ms.saturating_sub(at) < 32 * 60_000)) - { - return Ok(false); - } - // This is an observation failure, not an unsent user message. - // Preserve the accepted Send, action ID, and its original clock. - state.action.status = AutomationActionStatus::Stalled; - state.action.last_error = Some(UNVERIFIED_HANDOFF_WARNING.into()); - Ok(true) - }) - } pub fn turn_renewal_settings(&self) -> Result { crate::global_settings::turn_renewal_settings( self.settings_path.as_deref(), From 0b2864297a4a72164248cd137d31d4723e93b68f Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Wed, 18 Nov 2026 21:29:16 +0100 Subject: [PATCH 020/118] ci: enforce upstream Clippy -D warnings before native release artifact --- .github/workflows/single-lane-v240-ci.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.github/workflows/single-lane-v240-ci.yml b/.github/workflows/single-lane-v240-ci.yml index 3e006e5a..bcb762fd 100644 --- a/.github/workflows/single-lane-v240-ci.yml +++ b/.github/workflows/single-lane-v240-ci.yml @@ -49,6 +49,10 @@ jobs: run: | cargo check --locked --all-targets -j 2 if ($LASTEXITCODE -ne 0) { throw 'Cargo check failed' } + - name: Enforce upstream Clippy compatibility + run: | + cargo clippy --locked --all-targets -j 2 -- -D warnings + if ($LASTEXITCODE -ne 0) { throw 'Upstream Clippy strict check failed' } - name: Verify Windows locked file and canonical path regressions run: | cargo test --locked --lib windows_state_publication_tests -j 2 -- --nocapture From da8bbba6d42f03e4c6b70be68b1213badf6b5800 Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Wed, 18 Nov 2026 22:03:38 +0100 Subject: [PATCH 021/118] ci: compare Clippy regressions against pinned upstream baseline --- .github/workflows/single-lane-v240-ci.yml | 104 +++++++++++++++++++++- 1 file changed, 101 insertions(+), 3 deletions(-) diff --git a/.github/workflows/single-lane-v240-ci.yml b/.github/workflows/single-lane-v240-ci.yml index bcb762fd..0b9ea6bd 100644 --- a/.github/workflows/single-lane-v240-ci.yml +++ b/.github/workflows/single-lane-v240-ci.yml @@ -49,10 +49,108 @@ jobs: run: | cargo check --locked --all-targets -j 2 if ($LASTEXITCODE -ne 0) { throw 'Cargo check failed' } - - name: Enforce upstream Clippy compatibility + - name: Reject new Clippy findings relative to pinned upstream v2.4 run: | - cargo clippy --locked --all-targets -j 2 -- -D warnings - if ($LASTEXITCODE -ne 0) { throw 'Upstream Clippy strict check failed' } + $ErrorActionPreference = 'Stop' + $baselineSha = 'b14eacde810531a451535ee546ca7e07c65c5a1d' + $baselinePath = Join-Path $env:RUNNER_TEMP 'codexify-clippy-upstream-base' + if (Test-Path -LiteralPath $baselinePath) { throw 'Clippy baseline path is not empty' } + git worktree add --detach $baselinePath $baselineSha + if ($LASTEXITCODE -ne 0) { throw 'Failed to open the exact upstream baseline' } + # Share dependency builds without modifying the user's live checkout. + $env:CARGO_TARGET_DIR = Join-Path $env:GITHUB_WORKSPACE 'target' + $baseLog = Join-Path $env:RUNNER_TEMP 'clippy-upstream.jsonl' + $headLog = Join-Path $env:RUNNER_TEMP 'clippy-candidate.jsonl' + try { + Push-Location $baselinePath + try { + cargo clippy --locked --all-targets -j 2 --message-format=json -- -D warnings 1> $baseLog + $baseExit = $LASTEXITCODE + } finally { + Pop-Location + } + cargo clippy --locked --all-targets -j 2 --message-format=json -- -D warnings 1> $headLog + $headExit = $LASTEXITCODE + function Get-FindingCounts { + param([string]$LogPath) + $counts = @{} + foreach ($line in [System.IO.File]::ReadLines($LogPath)) { + if (-not $line.StartsWith('{')) { continue } + try { $entry = $line | ConvertFrom-Json -ErrorAction Stop } catch { continue } + if ($entry.reason -ne 'compiler-message') { continue } + $diagnostic = $entry.message + if ($diagnostic.level -notin @('error', 'warning')) { continue } + $primary = $diagnostic.spans | Where-Object { $_.is_primary } | Select-Object -First 1 + $file = if ($null -ne $primary) { [string]$primary.file_name } else { '' } + $file = $file -replace '\\', '/' + if ($file -match '((?:src|tests|examples)/.*) + - name: Verify Windows locked file and canonical path regressions + run: | + cargo test --locked --lib windows_state_publication_tests -j 2 -- --nocapture + if ($LASTEXITCODE -ne 0) { throw 'State publication test failed' } + cargo test --locked --lib rejects_ambiguous_matching_checkouts -j 2 -- --nocapture + if ($LASTEXITCODE -ne 0) { throw 'Windows path test failed' } + cargo test --locked --lib windows_worker_reports_start_and_completes_a_unicode_file_update -j 2 -- --nocapture + if ($LASTEXITCODE -ne 0) { throw 'Windows status publication test failed' } + cargo test --locked --lib owner_goal_commands_are_authenticated_idempotent_local_and_visible_in_state -j 2 -- --nocapture + if ($LASTEXITCODE -ne 0) { throw 'Goal activation wake test failed' } + cargo test --locked --lib completed_goal_renewal_tests -j 2 -- --nocapture + if ($LASTEXITCODE -ne 0) { throw 'Terminal handoff retirement regression failed' } + cargo test --locked --lib browser_action_lanes_default_to_one_and_are_bounded -j 2 + if ($LASTEXITCODE -ne 0) { throw 'Single browser lane default test failed' } + - name: Run MCP bridge authorization metadata regressions + run: | + cargo test --locked --lib bridge::tests:: -j 2 -- --nocapture + if ($LASTEXITCODE -ne 0) { throw 'MCP authorization bridge tests failed' } + - name: Run full Rust library regression suite + run: | + cargo test --locked --lib -j 2 + if ($LASTEXITCODE -ne 0) { throw 'Full library tests failed' } + - name: Build official-v2.4-based native candidate without installing + run: | + cargo build --locked --release --bin codexify -j 2 + if ($LASTEXITCODE -ne 0) { throw 'Native build failed' } + & .\target\release\codexify.exe --help | Select-Object -First 5 + if ($LASTEXITCODE -ne 0) { throw 'Binary help smoke failed' } + Get-FileHash .\target\release\codexify.exe -Algorithm SHA256 | Format-List | Out-String | Write-Output + - name: Retain reviewed native candidate for one day + uses: actions/upload-artifact@v4 + with: + name: codexify-v240-minimal-single-lane-windows + path: target/release/codexify.exe + if-no-files-found: error + retention-days: 1 +) { $file = $Matches[1] } + $code = if ($null -ne $diagnostic.code) { [string]$diagnostic.code.code } else { '' } + $key = "${file}|${code}|$($diagnostic.message)" + $counts[$key] = [int]$counts[$key] + 1 + } + return $counts + } + $upstream = Get-FindingCounts $baseLog + $candidate = Get-FindingCounts $headLog + if ($baseExit -ne 0 -and $upstream.Count -eq 0) { + throw 'Upstream Clippy failed without structured diagnostics; baseline is unusable' + } + if ($headExit -ne 0 -and $candidate.Count -eq 0) { + throw 'Candidate Clippy failed without structured diagnostics' + } + $regressions = @() + foreach ($finding in $candidate.GetEnumerator()) { + $increase = $finding.Value - [int]$upstream[$finding.Key] + if ($increase -gt 0) { $regressions += "$($finding.Key) (+$increase)" } + } + Write-Output "Pinned upstream Clippy diagnostics: $((@($upstream.Values) | Measure-Object -Sum).Sum)" + Write-Output "Candidate Clippy diagnostics: $((@($candidate.Values) | Measure-Object -Sum).Sum)" + if ($regressions.Count -gt 0) { + $regressions | Sort-Object | ForEach-Object { Write-Output "NEW: $_" } + throw 'Candidate introduced Clippy/compiler diagnostic regressions' + } + Write-Output 'No new Clippy diagnostics relative to pinned upstream. Existing upstream warnings remain tracked, not claimed resolved.' + } finally { + git worktree remove -- $baselinePath + if ($LASTEXITCODE -ne 0) { Write-Warning 'Ephemeral runner baseline worktree cleanup failed' } + } - name: Verify Windows locked file and canonical path regressions run: | cargo test --locked --lib windows_state_publication_tests -j 2 -- --nocapture From ef323c124f73396e5c3cdada6f471c4b2783d910 Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Wed, 18 Nov 2026 22:06:32 +0100 Subject: [PATCH 022/118] ci: correct baseline-aware Clippy workflow serialization --- .github/workflows/single-lane-v240-ci.yml | 52 +++-------------------- 1 file changed, 7 insertions(+), 45 deletions(-) diff --git a/.github/workflows/single-lane-v240-ci.yml b/.github/workflows/single-lane-v240-ci.yml index 0b9ea6bd..700fde4f 100644 --- a/.github/workflows/single-lane-v240-ci.yml +++ b/.github/workflows/single-lane-v240-ci.yml @@ -56,8 +56,7 @@ jobs: $baselinePath = Join-Path $env:RUNNER_TEMP 'codexify-clippy-upstream-base' if (Test-Path -LiteralPath $baselinePath) { throw 'Clippy baseline path is not empty' } git worktree add --detach $baselinePath $baselineSha - if ($LASTEXITCODE -ne 0) { throw 'Failed to open the exact upstream baseline' } - # Share dependency builds without modifying the user's live checkout. + if ($LASTEXITCODE -ne 0) { throw 'Failed to open pinned upstream baseline' } $env:CARGO_TARGET_DIR = Join-Path $env:GITHUB_WORKSPACE 'target' $baseLog = Join-Path $env:RUNNER_TEMP 'clippy-upstream.jsonl' $headLog = Join-Path $env:RUNNER_TEMP 'clippy-candidate.jsonl' @@ -83,44 +82,7 @@ jobs: $primary = $diagnostic.spans | Where-Object { $_.is_primary } | Select-Object -First 1 $file = if ($null -ne $primary) { [string]$primary.file_name } else { '' } $file = $file -replace '\\', '/' - if ($file -match '((?:src|tests|examples)/.*) - - name: Verify Windows locked file and canonical path regressions - run: | - cargo test --locked --lib windows_state_publication_tests -j 2 -- --nocapture - if ($LASTEXITCODE -ne 0) { throw 'State publication test failed' } - cargo test --locked --lib rejects_ambiguous_matching_checkouts -j 2 -- --nocapture - if ($LASTEXITCODE -ne 0) { throw 'Windows path test failed' } - cargo test --locked --lib windows_worker_reports_start_and_completes_a_unicode_file_update -j 2 -- --nocapture - if ($LASTEXITCODE -ne 0) { throw 'Windows status publication test failed' } - cargo test --locked --lib owner_goal_commands_are_authenticated_idempotent_local_and_visible_in_state -j 2 -- --nocapture - if ($LASTEXITCODE -ne 0) { throw 'Goal activation wake test failed' } - cargo test --locked --lib completed_goal_renewal_tests -j 2 -- --nocapture - if ($LASTEXITCODE -ne 0) { throw 'Terminal handoff retirement regression failed' } - cargo test --locked --lib browser_action_lanes_default_to_one_and_are_bounded -j 2 - if ($LASTEXITCODE -ne 0) { throw 'Single browser lane default test failed' } - - name: Run MCP bridge authorization metadata regressions - run: | - cargo test --locked --lib bridge::tests:: -j 2 -- --nocapture - if ($LASTEXITCODE -ne 0) { throw 'MCP authorization bridge tests failed' } - - name: Run full Rust library regression suite - run: | - cargo test --locked --lib -j 2 - if ($LASTEXITCODE -ne 0) { throw 'Full library tests failed' } - - name: Build official-v2.4-based native candidate without installing - run: | - cargo build --locked --release --bin codexify -j 2 - if ($LASTEXITCODE -ne 0) { throw 'Native build failed' } - & .\target\release\codexify.exe --help | Select-Object -First 5 - if ($LASTEXITCODE -ne 0) { throw 'Binary help smoke failed' } - Get-FileHash .\target\release\codexify.exe -Algorithm SHA256 | Format-List | Out-String | Write-Output - - name: Retain reviewed native candidate for one day - uses: actions/upload-artifact@v4 - with: - name: codexify-v240-minimal-single-lane-windows - path: target/release/codexify.exe - if-no-files-found: error - retention-days: 1 -) { $file = $Matches[1] } + if ($file -match '((?:src|tests|examples)/.*)$') { $file = $Matches[1] } $code = if ($null -ne $diagnostic.code) { [string]$diagnostic.code.code } else { '' } $key = "${file}|${code}|$($diagnostic.message)" $counts[$key] = [int]$counts[$key] + 1 @@ -130,7 +92,7 @@ jobs: $upstream = Get-FindingCounts $baseLog $candidate = Get-FindingCounts $headLog if ($baseExit -ne 0 -and $upstream.Count -eq 0) { - throw 'Upstream Clippy failed without structured diagnostics; baseline is unusable' + throw 'Upstream Clippy failed without structured diagnostics; baseline unusable' } if ($headExit -ne 0 -and $candidate.Count -eq 0) { throw 'Candidate Clippy failed without structured diagnostics' @@ -140,16 +102,16 @@ jobs: $increase = $finding.Value - [int]$upstream[$finding.Key] if ($increase -gt 0) { $regressions += "$($finding.Key) (+$increase)" } } - Write-Output "Pinned upstream Clippy diagnostics: $((@($upstream.Values) | Measure-Object -Sum).Sum)" - Write-Output "Candidate Clippy diagnostics: $((@($candidate.Values) | Measure-Object -Sum).Sum)" + Write-Output "Pinned upstream findings: $((@($upstream.Values) | Measure-Object -Sum).Sum)" + Write-Output "Candidate findings: $((@($candidate.Values) | Measure-Object -Sum).Sum)" if ($regressions.Count -gt 0) { $regressions | Sort-Object | ForEach-Object { Write-Output "NEW: $_" } throw 'Candidate introduced Clippy/compiler diagnostic regressions' } - Write-Output 'No new Clippy diagnostics relative to pinned upstream. Existing upstream warnings remain tracked, not claimed resolved.' + Write-Output 'No new Clippy diagnostics. Existing upstream warnings are tracked, not claimed resolved.' } finally { git worktree remove -- $baselinePath - if ($LASTEXITCODE -ne 0) { Write-Warning 'Ephemeral runner baseline worktree cleanup failed' } + if ($LASTEXITCODE -ne 0) { Write-Warning 'Ephemeral CI worktree cleanup failed' } } - name: Verify Windows locked file and canonical path regressions run: | From a394ad8f376160dc5336881d7ec7a21fab950a1f Mon Sep 17 00:00:00 2001 From: tomi Date: Thu, 19 Nov 2026 01:43:54 +0100 Subject: [PATCH 023/118] fix(mcp): isolate Playwright upstream sessions by durable chat owner --- src/bridge.rs | 125 ++++++++- src/codex_mcp.rs | 4 + src/config.rs | 1 + src/lib.rs | 1 + src/mcp_catalog.rs | 21 +- src/playwright_sessions.rs | 503 +++++++++++++++++++++++++++++++++++++ src/types.rs | 12 + src/upstream_control.rs | 12 +- 8 files changed, 664 insertions(+), 15 deletions(-) create mode 100644 src/playwright_sessions.rs diff --git a/src/bridge.rs b/src/bridge.rs index 3cb158c1..8347e7e5 100644 --- a/src/bridge.rs +++ b/src/bridge.rs @@ -32,7 +32,9 @@ use crate::bridged_resources::BridgedResourceStore; use crate::exec_sessions::SessionState; use crate::mcp_catalog::{CatalogSourceInput, build_catalog_tools}; use crate::process_env::scrub_untrusted_child_env; +use crate::project_bindings::ConversationIdentity; use crate::tool::{Tool, ToolBehavior, ToolCallIdentity, ToolRequestContext}; +use crate::types::McpSessionScope; use crate::types::{AppConfig, McpToolExposure, ToolContent, ToolResult}; mod stderr; @@ -123,7 +125,12 @@ struct BridgedTool { } impl BridgedTool { - async fn run(&self, args: Value, cancellation: Option<&CancellationToken>) -> ToolResult { + async fn run( + &self, + args: Value, + cancellation: Option<&CancellationToken>, + conversation: Option<&ConversationIdentity>, + ) -> ToolResult { let mut params = CallToolRequestParams::new(self.original_name.clone()); if let Some(obj) = args.as_object() && !obj.is_empty() @@ -141,6 +148,7 @@ impl BridgedTool { UpstreamCallContext { resources: &self.resources, control: &self.control, + conversation, }, ) .await @@ -245,7 +253,7 @@ impl Tool for BridgedTool { } async fn call(&self, args: Value, _config: &AppConfig, _session: &SessionState) -> ToolResult { - self.run(args, None).await + self.run(args, None, None).await } async fn call_with_context( @@ -255,13 +263,22 @@ impl Tool for BridgedTool { _session: &SessionState, context: &ToolRequestContext, ) -> ToolResult { - self.run(args, Some(&context.cancellation)).await + self.run( + args, + Some(&context.cancellation), + context + .task_conversation + .as_ref() + .or(context.conversation.as_ref()), + ) + .await } } pub(crate) struct UpstreamCallContext<'a> { pub(crate) resources: &'a BridgedResourceStore, pub(crate) control: &'a crate::upstream_control::UpstreamControl, + pub(crate) conversation: Option<&'a ConversationIdentity>, } pub(crate) async fn forward_tool_call( @@ -273,13 +290,51 @@ pub(crate) async fn forward_tool_call( cancellation: Option<&CancellationToken>, context: UpstreamCallContext<'_>, ) -> ToolResult { - let UpstreamCallContext { resources, control } = context; + let UpstreamCallContext { + resources, + control, + conversation, + } = context; // This preflight is shared by direct, gateway and catalog MCP exposure. // Never send an isolation request to a browser extension as a fallback. if let Err(error) = control.check_browser_context_request(tool, ¶ms) { return ToolResult::error(format!("Upstream MCP server '{server}': {error}")); } let isolated_requested = control.isolated_tab_requested(tool, ¶ms); + // A scoped Playwright source never falls back to the global peer when the + // downstream caller lacks an authoritative task identity. + let scoped_connection = match &control.scoped_playwright { + Some(pool) => { + let scoped_call = + tokio::time::timeout(Duration::from_secs(90), pool.acquire(conversation)); + let cancelled = cancellation.cloned().unwrap_or_default(); + let response = tokio::select! { + biased; + _ = cancelled.cancelled() => { + return ToolResult::error(format!( + "Upstream MCP server '{server}': owner request cancelled before browser dispatch" + )); + } + response = scoped_call => response, + }; + match response { + Ok(Ok(connection)) => Some(connection), + Ok(Err(error)) => { + return ToolResult::error(format!("Upstream MCP server '{server}': {error}")); + } + Err(_) => { + return ToolResult::error(format!( + "Upstream MCP server '{server}': per-chat browser startup timed out; no browser tool call dispatched" + )); + } + } + } + None => None, + }; + let (peer, control) = match &scoped_connection { + Some(connection) => (&connection.peer, connection.control.as_ref()), + None => (peer, control), + }; let timeout = tool_timeout.unwrap_or(Duration::from_secs(60)); let deadline = tokio::time::Instant::now() + timeout; let token = cancellation.cloned().unwrap_or_default(); @@ -569,12 +624,38 @@ pub async fn connect_upstreams(config: &AppConfig) -> Bridge { let sanitized = sanitize(server_name); let exposure = spec.exposure(); - match connect_one(server_name, spec, config).await { + // Validate per-chat ownership and prepare an isolated schema-discovery + // browser before launching any extension. Without the token, skip the + // provider entirely: no accidental manual approval dialog. + let scoped_pool = if spec.session_scope == McpSessionScope::PerChat { + match crate::playwright_sessions::ScopedPlaywrightPool::new(server_name, spec, config) { + Ok(pool) => Some(Arc::new(pool)), + Err(error) => { + report.push(format!("{server_name} -> FAILED: {error}")); + continue; + } + } + } else { + None + }; + let discovery = match &scoped_pool { + Some(pool) => match pool.discovery_spec() { + Ok(spec) => Some(spec), + Err(error) => { + report.push(format!("{server_name} -> FAILED: {error}")); + continue; + } + }, + None => None, + }; + let discovery_spec = discovery.as_ref().unwrap_or(spec); + match connect_one(server_name, discovery_spec, config).await { Ok((service, upstream_tools, tool_timeout)) => { let peer = service.peer().clone(); let control = Arc::new( crate::upstream_control::UpstreamControl::new(spec.request_limits.clone()) - .for_server(server_name, spec), + .for_server(server_name, spec) + .with_scoped_playwright(scoped_pool), ); upstreams.insert(server_name.clone(), control.clone()); monitors.push(monitor_upstream(peer.clone(), control.clone())); @@ -813,7 +894,12 @@ struct GatewayTool { } impl GatewayTool { - async fn run(&self, args: Value, cancellation: Option<&CancellationToken>) -> ToolResult { + async fn run( + &self, + args: Value, + cancellation: Option<&CancellationToken>, + conversation: Option<&ConversationIdentity>, + ) -> ToolResult { let Some(function) = args.get("function").and_then(|v| v.as_str()) else { return ToolResult::error("`function` is required (the name of the function to call)"); }; @@ -849,6 +935,7 @@ impl GatewayTool { UpstreamCallContext { resources: &self.resources, control: &self.control, + conversation, }, ) .await @@ -917,7 +1004,7 @@ impl Tool for GatewayTool { } async fn call(&self, args: Value, _config: &AppConfig, _session: &SessionState) -> ToolResult { - self.run(args, None).await + self.run(args, None, None).await } async fn call_with_context( @@ -927,12 +1014,20 @@ impl Tool for GatewayTool { _session: &SessionState, context: &ToolRequestContext, ) -> ToolResult { - self.run(args, Some(&context.cancellation)).await + self.run( + args, + Some(&context.cancellation), + context + .task_conversation + .as_ref() + .or(context.conversation.as_ref()), + ) + .await } } /// Launch and initialise one upstream, returning its running service and tools. -async fn connect_one( +pub(crate) async fn connect_one( server_name: &str, spec: &crate::types::McpServerSpec, config: &AppConfig, @@ -1155,7 +1250,7 @@ async fn connect_one_with_env( server_name: &str, spec: &crate::types::McpServerSpec, config: &AppConfig, - env_lookup: &dyn Fn(&str) -> Option, + env_lookup: &(dyn Fn(&str) -> Option + Send + Sync), ) -> Result< ( RunningService, @@ -1467,6 +1562,7 @@ mod tests { UpstreamCallContext { resources: &resources, control: &extension_control, + conversation: None, }, ) .await; @@ -1484,6 +1580,7 @@ mod tests { UpstreamCallContext { resources: &resources, control: &full_control, + conversation: None, }, ) .await; @@ -1500,6 +1597,7 @@ mod tests { UpstreamCallContext { resources: &resources, control: &cdp_control, + conversation: None, }, ) .await; @@ -1522,6 +1620,7 @@ mod tests { UpstreamCallContext { resources: &resources, control: &extension_control, + conversation: None, }, ) .await; @@ -2872,6 +2971,7 @@ mod tests { UpstreamCallContext { resources: &resources, control: &crate::upstream_control::UpstreamControl::default(), + conversation: None, }, ) .await; @@ -2889,6 +2989,7 @@ mod tests { UpstreamCallContext { resources: &resources, control: &crate::upstream_control::UpstreamControl::default(), + conversation: None, }, ) .await; @@ -2915,6 +3016,7 @@ mod tests { UpstreamCallContext { resources: &resources, control: &crate::upstream_control::UpstreamControl::default(), + conversation: None, }, ) .await; @@ -3001,6 +3103,7 @@ mod tests { UpstreamCallContext { resources: &resources, control: &control, + conversation: None, }, ); let fail = async { diff --git a/src/codex_mcp.rs b/src/codex_mcp.rs index adb4be65..0e06e3eb 100644 --- a/src/codex_mcp.rs +++ b/src/codex_mcp.rs @@ -355,6 +355,7 @@ fn codex_cli_server_to_spec( tools: server.enabled_tools, disabled_tools: server.disabled_tools, mode: None, + session_scope: Default::default(), provenance: McpServerProvenance::CodexCli, request_limits: crate::types::McpRequestLimits::default(), }); @@ -422,6 +423,7 @@ fn codex_cli_server_to_spec( tools: server.enabled_tools, disabled_tools: server.disabled_tools, mode: None, + session_scope: Default::default(), provenance: McpServerProvenance::CodexCli, request_limits: crate::types::McpRequestLimits::default(), }) @@ -626,6 +628,7 @@ fn parse_server( tools, disabled_tools, mode: None, + session_scope: Default::default(), provenance: McpServerProvenance::CodexConfig, request_limits: crate::types::McpRequestLimits::default(), }), @@ -675,6 +678,7 @@ fn parse_server( tools, disabled_tools, mode: None, + session_scope: Default::default(), provenance: McpServerProvenance::CodexConfig, request_limits: crate::types::McpRequestLimits::default(), }), diff --git a/src/config.rs b/src/config.rs index 000fcabe..47172b4d 100644 --- a/src/config.rs +++ b/src/config.rs @@ -2006,6 +2006,7 @@ mod tests { tools: Some(vec!["read".to_string()]), disabled_tools: Some(vec!["write".to_string()]), mode: None, + session_scope: Default::default(), provenance: crate::types::McpServerProvenance::CodexConfig, request_limits: crate::types::McpRequestLimits::default(), } diff --git a/src/lib.rs b/src/lib.rs index 0654d468..465a4fd0 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -44,6 +44,7 @@ pub mod openai_tunnel; pub mod output_budget; pub mod owner_chat; pub(crate) mod persist; +mod playwright_sessions; pub mod process_env; pub mod project_bindings; pub mod project_catalog; diff --git a/src/mcp_catalog.rs b/src/mcp_catalog.rs index 2144716f..c85bc69b 100644 --- a/src/mcp_catalog.rs +++ b/src/mcp_catalog.rs @@ -15,6 +15,7 @@ use tokio_util::sync::CancellationToken; use crate::bridge::{UpstreamCallContext, forward_tool_call}; use crate::bridged_resources::BridgedResourceStore; use crate::exec_sessions::SessionState; +use crate::project_bindings::ConversationIdentity; use crate::tool::{Tool, ToolBehavior, ToolCallIdentity, ToolRequestContext}; use crate::types::{AppConfig, McpServerProvenance, ToolResult}; @@ -1014,7 +1015,12 @@ struct McpCallToolTool { } impl McpCallToolTool { - async fn run(&self, args: Value, cancellation: Option<&CancellationToken>) -> ToolResult { + async fn run( + &self, + args: Value, + cancellation: Option<&CancellationToken>, + conversation: Option<&ConversationIdentity>, + ) -> ToolResult { let source_id = match required_string(&args, "source") { Ok(source) => source, Err(error) => return ToolResult::error(error), @@ -1057,6 +1063,7 @@ impl McpCallToolTool { UpstreamCallContext { resources: &self.resources, control: &source.control, + conversation, }, ) .await @@ -1134,7 +1141,7 @@ impl Tool for McpCallToolTool { } async fn call(&self, args: Value, _config: &AppConfig, _session: &SessionState) -> ToolResult { - self.run(args, None).await + self.run(args, None, None).await } async fn call_with_context( @@ -1144,7 +1151,15 @@ impl Tool for McpCallToolTool { _session: &SessionState, context: &ToolRequestContext, ) -> ToolResult { - self.run(args, Some(&context.cancellation)).await + self.run( + args, + Some(&context.cancellation), + context + .task_conversation + .as_ref() + .or(context.conversation.as_ref()), + ) + .await } } diff --git a/src/playwright_sessions.rs b/src/playwright_sessions.rs new file mode 100644 index 00000000..c0010255 --- /dev/null +++ b/src/playwright_sessions.rs @@ -0,0 +1,503 @@ +//! Per-ChatGPT-task Playwright MCP stdio connections. +//! A single upstream Playwright peer has mutable current-tab state. Never share +//! that peer across physical conversations or durable task continuations. +use std::collections::HashMap; +use std::path::PathBuf; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +use rmcp::RoleClient; +use rmcp::service::{Peer, RunningService}; +use tokio::sync::{Mutex as AsyncMutex, OnceCell, Semaphore}; + +use crate::bridge::connect_one; +use crate::project_bindings::ConversationIdentity; +use crate::types::{AppConfig, McpServerSpec, McpSessionScope}; +use crate::upstream_control::UpstreamControl; + +const MAX_LIVE_SESSIONS: usize = 16; +const MAX_PARALLEL_BROWSER_STARTS: usize = 3; +const IDLE_SESSION_TTL: Duration = Duration::from_secs(60 * 60); + +pub(crate) struct ScopedConnection { + // Hold the upstream process and transport alive for this conversation. + _service: RunningService, + pub(crate) peer: Peer, + pub(crate) control: Arc, +} + +struct SessionSlot { + connection: OnceCell>, + last_used: Mutex, +} + +impl SessionSlot { + fn new() -> Self { + Self { + connection: OnceCell::new(), + last_used: Mutex::new(Instant::now()), + } + } + + fn touch(&self) { + *self.last_used.lock().unwrap_or_else(|e| e.into_inner()) = Instant::now(); + } + + fn expired(&self) -> bool { + self.last_used + .lock() + .unwrap_or_else(|e| e.into_inner()) + .elapsed() + >= IDLE_SESSION_TTL + } +} + +pub(crate) struct ScopedPlaywrightPool { + server: String, + instance_port: u16, + config: AppConfig, + spec: McpServerSpec, + extension: bool, + profiles_root: PathBuf, + sessions: AsyncMutex>>, + startup_capacity: Semaphore, +} + +impl ScopedPlaywrightPool { + pub(crate) fn new( + server: &str, + spec: &McpServerSpec, + config: &AppConfig, + ) -> Result { + if spec.session_scope != McpSessionScope::PerChat { + return Err("per-chat Playwright requires sessionScope=per-chat".into()); + } + if spec.command.is_none() || spec.url.is_some() { + return Err("per-chat Playwright requires a local stdio MCP server".into()); + } + let playwright = server.to_ascii_lowercase().contains("playwright") + || spec + .args + .iter() + .any(|arg| arg.to_ascii_lowercase().contains("playwright")); + if !playwright { + return Err("sessionScope=per-chat is only supported for Playwright MCP".into()); + } + let extension = is_extension(server, spec); + for forbidden in [ + "--user-data-dir", + "--shared-browser-context", + "--cdp-endpoint", + "--endpoint", + "--storage-state", + "--isolated", + "--no-tab-group", + "--session-name", + "--profile-dir-name", + "--config", + ] { + if spec + .args + .iter() + .any(|arg| arg == forbidden || arg.starts_with(&format!("{forbidden}="))) + { + return Err(format!( + "per-chat Playwright must own its session lifecycle; remove {forbidden}" + )); + } + } + if spec + .env + .get("PLAYWRIGHT_MCP_NO_TAB_GROUP") + .is_some_and(|v| v == "1") + { + return Err("per-chat extension mode requires tab groups for ownership".into()); + } + if extension { + let profile = spec.env.get("PLAYWRIGHT_MCP_PROFILE_DIR_NAME"); + if profile.is_none_or(|name| name.is_empty() || name == "Default") { + return Err("per-chat extension mode requires an explicitly dedicated non-default Chrome profile (PLAYWRIGHT_MCP_PROFILE_DIR_NAME)".into()); + } + let configured_token = spec + .env + .get("PLAYWRIGHT_MCP_EXTENSION_TOKEN") + .is_some_and(|v| !v.trim().is_empty()); + let configured_file = spec + .env + .get("PLAYWRIGHT_MCP_EXTENSION_TOKEN_FILE") + .is_some_and(|v| !v.trim().is_empty()); + // Consent must be explicit in this dedicated MCP source, never an + // ambient token inherited from the interactive user session. + if !configured_token && !configured_file { + return Err("per-chat Playwright extension needs PLAYWRIGHT_MCP_EXTENSION_TOKEN or PLAYWRIGHT_MCP_EXTENSION_TOKEN_FILE for a dedicated browser profile; refusing manual approval prompts".into()); + } + if configured_token && configured_file { + return Err("configure only one Playwright extension token source".into()); + } + } + let root = std::env::var_os("USERPROFILE") + .or_else(|| std::env::var_os("HOME")) + .map(PathBuf::from) + .unwrap_or_else(|| config.work_dir.clone()) + .join(".codexify") + .join("playwright-agent-profiles"); + Ok(Self { + server: server.to_string(), + instance_port: config.port, + config: config.clone(), + spec: spec.clone(), + extension, + profiles_root: root, + sessions: AsyncMutex::new(HashMap::new()), + startup_capacity: Semaphore::new(MAX_PARALLEL_BROWSER_STARTS), + }) + } + + fn scoped_spec(&self, owner: &ConversationIdentity) -> Result { + let key = owner.stable_key(); + if key.len() != 64 || !key.bytes().all(|b| b.is_ascii_hexdigit()) { + return Err("invalid per-chat browser owner identity".into()); + } + let mut spec = self.spec.clone(); + if self.extension { + load_extension_token(&mut spec)?; + spec.env.insert( + "PLAYWRIGHT_MCP_SESSION_NAME".into(), + format!("Codexify-{}-{}", self.instance_port, &key[..12]), + ); + // The extension owns each client's tab group and token-based + // connections start on a new blank tab (never an existing tab). + spec.env + .insert("PLAYWRIGHT_MCP_NO_TAB_GROUP".into(), "0".into()); + spec.env + .insert("PLAYWRIGHT_MCP_BACKGROUND".into(), "1".into()); + } else { + let safe_server: String = self + .server + .chars() + .map(|c| { + if c.is_ascii_alphanumeric() || c == '-' { + c + } else { + '_' + } + }) + .collect(); + let profile = self + .profiles_root + .join(safe_server) + .join(self.instance_port.to_string()) + .join(key); + std::fs::create_dir_all(&profile) + .map_err(|e| format!("could not prepare per-chat browser profile: {e}"))?; + spec.args + .push(format!("--user-data-dir={}", profile.display())); + } + Ok(spec) + } + + /// An isolated catalog-discovery connection is only used to fetch schemas. + /// It must not attach to any real task or browser session. + pub(crate) fn discovery_spec(&self) -> Result { + let identity = ConversationIdentity::from_openai_session( + "codexify-playwright-catalog-discovery-not-a-user", + ) + .ok_or("could not create discovery owner")?; + self.scoped_spec(&identity) + } + + pub(crate) async fn acquire( + &self, + owner: Option<&ConversationIdentity>, + ) -> Result, String> { + let owner = owner.ok_or( + "per-chat Playwright needs a verified ChatGPT conversation/task identity; \ + refusing the shared global browser", + )?; + let key = owner.stable_key().to_owned(); + let slot = { + let mut sessions = self.sessions.lock().await; + // Never reclaim an in-use connection. This cap prevents unattended + // chats from spawning arbitrarily many Chromium processes. + sessions.retain(|_, entry| { + !entry.expired() + || Arc::strong_count(entry) > 1 + // A request may hold the connection but not its slot. + // Do not evict and respawn while that browser is in use. + || entry + .connection + .get() + .is_some_and(|connection| Arc::strong_count(connection) > 1) + }); + let slot = if let Some(entry) = sessions.get(&key) { + entry.clone() + } else { + if sessions.len() >= MAX_LIVE_SESSIONS { + return Err( + "per-chat Playwright capacity reached; wait for an idle session to \ + expire rather than sharing another agent's browser" + .into(), + ); + } + let entry = Arc::new(SessionSlot::new()); + sessions.insert(key, entry.clone()); + entry + }; + slot.touch(); + slot + }; + let connection = slot + .connection + .get_or_try_init(|| async { + let _start = self + .startup_capacity + .acquire() + .await + .map_err(|_| "per-chat browser startup limiter closed")?; + let scoped = self.scoped_spec(owner)?; + let (service, _tools, _timeout) = + connect_one(&self.server, &scoped, &self.config).await?; + let peer = service.peer().clone(); + let control = Arc::new( + UpstreamControl::new(scoped.request_limits.clone()) + .for_server(&self.server, &scoped), + ); + Ok::<_, String>(Arc::new(ScopedConnection { + _service: service, + peer, + control, + })) + }) + .await?; + Ok(connection.clone()) + } +} + +// Never log, store in the upstream catalog, or place in MCP metadata. +// The file is provisioned once with a user-only ACL by the optional setup +// script. Reading it at connection time also supports safe token rotation. +fn load_extension_token(spec: &mut McpServerSpec) -> Result<(), String> { + let token_file = spec.env.remove("PLAYWRIGHT_MCP_EXTENSION_TOKEN_FILE"); + if let Some(filename) = token_file { + if spec.env.contains_key("PLAYWRIGHT_MCP_EXTENSION_TOKEN") { + return Err("multiple Playwright extension token sources".into()); + } + let path = PathBuf::from(filename); + if !path.is_absolute() { + return Err("Playwright extension token file must be an absolute path".into()); + } + let metadata = std::fs::symlink_metadata(&path) + .map_err(|_| "Playwright extension token file could not be opened")?; + if !metadata.is_file() || metadata.file_type().is_symlink() || metadata.len() > 1024 { + return Err("Playwright extension token file must be a regular, small file".into()); + } + let source = std::fs::read_to_string(&path) + .map_err(|_| "Playwright extension token file could not be read")?; + let token = source.trim_end_matches(['\r', '\n']); + if !(16..=512).contains(&token.len()) + || !token + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') + { + return Err("Playwright extension token file has an invalid token format".into()); + } + spec.env + .insert("PLAYWRIGHT_MCP_EXTENSION_TOKEN".into(), token.into()); + } + Ok(()) +} + +fn is_extension(server: &str, spec: &McpServerSpec) -> bool { + server.to_ascii_lowercase().contains("extension") + || spec + .args + .iter() + .any(|arg| arg == "--extension" || arg == "--extension=true") + || spec + .env + .get("PLAYWRIGHT_MCP_EXTENSION") + .is_some_and(|value| value == "1" || value.eq_ignore_ascii_case("true")) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::types::McpSessionScope; + + fn stub_config() -> AppConfig { + crate::config::default_config(std::env::temp_dir()) + } + + fn spec(extension: bool) -> McpServerSpec { + let mut spec = McpServerSpec { + command: Some("node".into()), + args: vec!["@playwright/mcp".into()], + session_scope: McpSessionScope::PerChat, + ..Default::default() + }; + if extension { + spec.args.push("--extension".into()); + spec.env + .insert("PLAYWRIGHT_MCP_PROFILE_DIR_NAME".into(), "Codexify".into()); + spec.env.insert( + "PLAYWRIGHT_MCP_EXTENSION_TOKEN".into(), + "test-token-not-a-real-secret".into(), + ); + } + spec + } + + #[test] + fn distinct_conversations_receive_distinct_persistent_profiles() { + let pool = ScopedPlaywrightPool::new("playwright", &spec(false), &stub_config()).unwrap(); + let a = ConversationIdentity::from_openai_session("account-A-chat-A").unwrap(); + let b = ConversationIdentity::from_openai_session("account-A-chat-B").unwrap(); + let aa = pool.scoped_spec(&a).unwrap(); + let bb = pool.scoped_spec(&b).unwrap(); + assert_ne!(aa.args, bb.args); + assert_eq!(aa.args, pool.scoped_spec(&a).unwrap().args); + assert!( + aa.args + .iter() + .any(|arg| arg.starts_with("--user-data-dir=")) + ); + } + + #[test] + fn extension_is_grouped_per_client_without_overwriting_the_token() { + let config = stub_config(); + let pool = ScopedPlaywrightPool::new("playwright-extension", &spec(true), &config).unwrap(); + let a = ConversationIdentity::from_openai_session("chat-A").unwrap(); + let b = ConversationIdentity::from_openai_session("chat-B").unwrap(); + let aa = pool.scoped_spec(&a).unwrap(); + let bb = pool.scoped_spec(&b).unwrap(); + assert_ne!( + aa.env.get("PLAYWRIGHT_MCP_SESSION_NAME"), + bb.env.get("PLAYWRIGHT_MCP_SESSION_NAME") + ); + assert_eq!( + aa.env.get("PLAYWRIGHT_MCP_EXTENSION_TOKEN"), + bb.env.get("PLAYWRIGHT_MCP_EXTENSION_TOKEN") + ); + assert_eq!(aa.env.get("PLAYWRIGHT_MCP_BACKGROUND"), Some(&"1".into())); + assert!(!aa.args.iter().any(|a| a.starts_with("--user-data-dir="))); + } + + #[tokio::test] + async fn missing_owner_is_rejected_before_launching_any_browser() { + let pool = ScopedPlaywrightPool::new("playwright", &spec(false), &stub_config()).unwrap(); + let error = pool + .acquire(None) + .await + .err() + .expect("missing owner rejected"); + assert!(error.contains("refusing the shared global browser")); + assert_eq!(pool.sessions.lock().await.len(), 0); + } + + #[tokio::test] + async fn bounded_capacity_rejects_new_owner_without_reusing_another_session() { + let pool = ScopedPlaywrightPool::new("playwright", &spec(false), &stub_config()).unwrap(); + { + let mut sessions = pool.sessions.lock().await; + for index in 0..MAX_LIVE_SESSIONS { + sessions.insert(format!("{index:064x}"), Arc::new(SessionSlot::new())); + } + } + let new_owner = ConversationIdentity::from_openai_session("seventeenth-owner").unwrap(); + let error = pool + .acquire(Some(&new_owner)) + .await + .err() + .expect("limit enforced"); + assert!(error.contains("capacity reached")); + assert_eq!(pool.sessions.lock().await.len(), MAX_LIVE_SESSIONS); + } + + #[test] + fn extension_without_token_fails_closed_before_any_mcp_connection() { + let mut s = spec(true); + s.env.remove("PLAYWRIGHT_MCP_EXTENSION_TOKEN"); + s.env.remove("PLAYWRIGHT_MCP_EXTENSION_TOKEN_FILE"); + assert!(ScopedPlaywrightPool::new("playwright-extension", &s, &stub_config()).is_err()); + } + + #[test] + fn token_file_is_loaded_only_for_a_scoped_child_and_errors_are_secret_free() { + let mut s = spec(true); + s.env + .insert("PLAYWRIGHT_MCP_PROFILE_DIR_NAME".into(), "Codexify".into()); + s.env.remove("PLAYWRIGHT_MCP_EXTENSION_TOKEN"); + let file = std::env::temp_dir().join(format!( + "codexify-playwright-token-test-{}-{}.txt", + std::process::id(), + "f48a" + )); + assert!(!file.exists()); + std::fs::write(&file, "testtoken_with_123456789").unwrap(); + s.env.insert( + "PLAYWRIGHT_MCP_EXTENSION_TOKEN_FILE".into(), + file.display().to_string(), + ); + let pool = ScopedPlaywrightPool::new("playwright-extension", &s, &stub_config()).unwrap(); + let owner = ConversationIdentity::from_openai_session("chat-A").unwrap(); + let child = pool.scoped_spec(&owner).unwrap(); + assert_eq!( + child + .env + .get("PLAYWRIGHT_MCP_EXTENSION_TOKEN") + .map(String::as_str), + Some("testtoken_with_123456789") + ); + assert!( + !child + .env + .contains_key("PLAYWRIGHT_MCP_EXTENSION_TOKEN_FILE") + ); + assert!( + pool.spec + .env + .contains_key("PLAYWRIGHT_MCP_EXTENSION_TOKEN_FILE") + ); + std::fs::remove_file(&file).unwrap(); + let error = pool.scoped_spec(&owner).unwrap_err(); + assert!(!error.contains("testtoken_with")); + assert!(!error.contains(&file.display().to_string())); + } + + #[test] + fn per_chat_extension_must_select_a_dedicated_profile() { + let mut s = spec(true); + s.env.remove("PLAYWRIGHT_MCP_PROFILE_DIR_NAME"); + assert!(ScopedPlaywrightPool::new("playwright-extension", &s, &stub_config()).is_err()); + s.env + .insert("PLAYWRIGHT_MCP_PROFILE_DIR_NAME".into(), "Default".into()); + assert!(ScopedPlaywrightPool::new("playwright-extension", &s, &stub_config()).is_err()); + s.env + .insert("PLAYWRIGHT_MCP_PROFILE_DIR_NAME".into(), "Profile 3".into()); + assert!(ScopedPlaywrightPool::new("playwright-extension", &s, &stub_config()).is_ok()); + } + + #[test] + fn refuses_context_sharing_and_arbitrary_non_browser_sources() { + for flag in [ + "--shared-browser-context", + "--cdp-endpoint=ws://localhost:22", + ] { + let mut s = spec(false); + s.args.push(flag.into()); + assert!(ScopedPlaywrightPool::new("playwright", &s, &stub_config()).is_err()); + } + assert!( + ScopedPlaywrightPool::new( + "non-browser", + &McpServerSpec { + args: vec!["echo".into()], + ..spec(false) + }, + &stub_config() + ) + .is_err() + ); + } +} diff --git a/src/types.rs b/src/types.rs index b4938c8c..4cd997ca 100644 --- a/src/types.rs +++ b/src/types.rs @@ -556,6 +556,14 @@ impl McpServerProvenance { } } +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum McpSessionScope { + #[default] + Global, + PerChat, +} + /// One upstream MCP server to bridge, in the standard `mcpServers` shape. Its /// tools are discovered at startup and materialized according to the effective /// exposure mode. A `command` selects stdio; a `url` selects Codex-compatible @@ -626,6 +634,10 @@ pub struct McpServerSpec { /// catalog mode. #[serde(default)] pub mode: Option, + /// Explicit opt-in to a separate Playwright MCP process and browser + /// profile/tab group for each durable ChatGPT task. + #[serde(default)] + pub session_scope: McpSessionScope, /// Internal origin used only to select the backward-compatible default mode. #[serde(skip)] pub provenance: McpServerProvenance, diff --git a/src/upstream_control.rs b/src/upstream_control.rs index f95f350d..f392864a 100644 --- a/src/upstream_control.rs +++ b/src/upstream_control.rs @@ -2,7 +2,7 @@ use crate::types::{McpRequestLimits, McpServerSpec}; use rmcp::model::CallToolRequestParams; use serde_json::{Value, json}; -use std::sync::Mutex; +use std::sync::{Arc, Mutex}; use std::time::Duration; use tokio::sync::{Semaphore, SemaphorePermit}; use tokio::time::Instant; @@ -125,6 +125,7 @@ struct State { pub(crate) struct UpstreamControl { limits: McpRequestLimits, playwright_mode: PlaywrightBackendMode, + pub(crate) scoped_playwright: Option>, active: Semaphore, pending: Semaphore, state: Mutex, @@ -164,6 +165,7 @@ impl UpstreamControl { pending: Semaphore::new(limits.max_concurrent_requests + limits.max_pending_requests), limits, playwright_mode: PlaywrightBackendMode::Other, + scoped_playwright: None, state: Mutex::new(State::default()), unavailable: tokio::sync::watch::channel(false).0, } @@ -174,6 +176,14 @@ impl UpstreamControl { self } + pub(crate) fn with_scoped_playwright( + mut self, + pool: Option>, + ) -> Self { + self.scoped_playwright = pool; + self + } + /// Advertise only what the connection mode can establish, not what a /// similar tool on another upstream may be able to do. pub(crate) fn browser_context_capability(&self) -> Option<&'static str> { From cd4e483b38b31a0c75c658de7abb016cd58a2d77 Mon Sep 17 00:00:00 2001 From: tomi Date: Thu, 19 Nov 2026 01:44:09 +0100 Subject: [PATCH 024/118] docs(browser): document scoped Playwright and secure token enrollment --- docs/per-chat-playwright.md | 77 +++++++++++++++++ scripts/enroll-playwright-extension-token.ps1 | 82 +++++++++++++++++++ 2 files changed, 159 insertions(+) create mode 100644 docs/per-chat-playwright.md create mode 100644 scripts/enroll-playwright-extension-token.ps1 diff --git a/docs/per-chat-playwright.md b/docs/per-chat-playwright.md new file mode 100644 index 00000000..7d48c01f --- /dev/null +++ b/docs/per-chat-playwright.md @@ -0,0 +1,77 @@ +# Per-chat Playwright MCP isolation (source-only prototype) + +This implementation is opt-in and is NOT enabled by Codexify 2.3.29. +Do not enable new configuration fields until a compatible build is deployed. +Preserve custom automation settings including providerSendGatePath. + +## Root cause + +Previously Codexify opened one stdio upstream peer for each Playwright source at +server startup. Every ChatGPT task forwarded to the same upstream peer. Since +Playwright tracks a mutable current tab for each MCP connection, different +agents could interfere by selecting each other's tabs. + +The opt-in sessionScope: per-chat now creates a distinct Playwright MCP peer +per durable ChatGPT task identity. Without trusted task or conversation +identity, all calls fail closed instead of falling back to the global peer. + +## Managed-browser mode (stronger isolation) + +Use a local Playwright MCP source without --extension and set sessionScope to +per-chat. Codexify creates a distinct, persistent user-data-dir for each task: +%USERPROFILE%\.codexify\playwright-agent-profiles\\\ + +The service port is part of the namespace so multiple Codexify instances +on one machine never contend for the same task browser profile. +This does not reuse the personal Chrome profile. Memory usage grows with +the number of concurrently active Chrome processes. + +## Extension mode (tab-group isolation, weaker security) + +Use the official Playwright Extension only on a dedicated, non-default +automation-only Chrome profile. The extension has broad access to the whole +profile; different tab groups are not strong sandbox boundaries. + +It supports distinct MCP client session names/tab groups and can auto-authorize +using PLAYWRIGHT_MCP_EXTENSION_TOKEN. The token must never appear in Git, logs, +CI or messages. The optional enrollment script saves it as a user-only Windows +secret file, not in the live Codexify configuration. + +Read-only dry run: + powershell.exe -NoProfile -File scripts\enroll-playwright-extension-token.ps1 + +One-time enrollment (when ready to enable this feature): + powershell.exe -NoProfile -File scripts\enroll-playwright-extension-token.ps1 -Apply -DedicatedProfile "Profile 3" + +After deploying a compatible Codexify build, opt in ONLY the selected +mcpServers.playwright-extension entry with sessionScope: per-chat, and set +env.PLAYWRIGHT_MCP_EXTENSION_TOKEN_FILE to the absolute path printed by the +enrollment script. Preserve its existing extension args and profile settings. +Do not configure a second plaintext token at the same time. + +A distinct named group is allocated per task and background mode requested. +Playwright Extension 0.5.0+ is needed for the background feature; Chromium +158+ is recommended when true background startup without focus is essential. +Older Chromium may still show/focus a connection page. + +## Failure containment and capacity + +- Never use global browser fallback after a per-chat routing failure +- Never connect extension mode without an explicit dedicated profile and token +- Reject unsupported shared-browser-context and existing CDP endpoint flags +- Direct, gateway and catalog bridge calls all carry trusted caller identity +- Keep no more than 16 per-source sessions and at most 3 concurrent starts; + impose a 90-second cancellable startup deadline; release inactive sessions after + one hour, never deleting browser profile directories +- This feature does not modify native Codexify browser companion profiles, + production service, or saved browser Send receipts + +## Deployment gates + +1. Run Rust formatting, compile and focused isolation unit tests +2. Prove two synthetic task identities resolve to distinct MCP clients +3. Confirm that unknown identity fails before browser mutation +4. Exercise two disposable browser profiles on harmless local pages +5. Verify unchanged production config, including providerSendGatePath, + against the final v2.4 candidate before any service cutover +6. Never silently retry or replay already-accepted browser Send actions diff --git a/scripts/enroll-playwright-extension-token.ps1 b/scripts/enroll-playwright-extension-token.ps1 new file mode 100644 index 00000000..a9607535 --- /dev/null +++ b/scripts/enroll-playwright-extension-token.ps1 @@ -0,0 +1,82 @@ +# Enrol a token for a dedicated Playwright automation Chrome profile. +# Stores the token only in an ACL-restricted file outside the Git repository. +# Does not modify Codexify configuration or launch a browser. +param( + [switch]$Apply, + [switch]$Rotate, + [string]$DedicatedProfile = '' +) +$ErrorActionPreference='Stop' +$root=Join-Path $env:USERPROFILE '.codexify' +$configPath=Join-Path $root 'codexify.config.json' +$secretDir=Join-Path $root 'secrets\playwright-extension' +$secretPath=Join-Path $secretDir 'connection-token.txt' +if(-not (Test-Path -LiteralPath $configPath -PathType Leaf)){throw 'Codexify config missing'} +$config=Get-Content -LiteralPath $configPath -Raw|ConvertFrom-Json +$server=$config.mcpServers.'playwright-extension' +if(-not $server){throw 'playwright-extension source not configured'} +if(-not @($server.args|Where-Object {$_ -eq '--extension' -or $_ -eq '--extension=true'}).Count){throw 'Selected MCP source is not extension mode'} +$profile=[string]$server.env.PLAYWRIGHT_MCP_PROFILE_DIR_NAME +if(-not $profile -or $profile -eq 'Default'){throw 'A dedicated non-default Chrome profile must be explicitly configured'} +if($Apply -and $DedicatedProfile -ne $profile){throw 'Explicit -DedicatedProfile must match configured dedicated profile'} +if($Rotate -and -not $Apply){throw '-Rotate requires -Apply'} +Write-Output ('Dedicated Chrome profile: '+$profile) +Write-Output ('Enrolment already exists: '+[bool](Test-Path -LiteralPath $secretPath)) +if(-not $Apply){ + Write-Output 'DRY RUN ONLY. No secrets stored, no browser started, no configuration changes.' + Write-Output ('To opt in later: powershell.exe -NoProfile -File "'+$PSCommandPath+'" -Apply -DedicatedProfile "'+$profile+'"') + return +} +if((Test-Path -LiteralPath $secretPath) -and -not $Rotate){throw 'Token already stored; use -Rotate only when explicitly replacing it'} +if($Rotate -and -not (Test-Path -LiteralPath $secretPath)){throw 'Cannot rotate an absent token'} +$inputToken=Read-Host 'Paste the token from Playwright Extension in this DEDICATED profile' -AsSecureString +if(-not $inputToken){throw 'No token supplied'} +$ptr=[Runtime.InteropServices.Marshal]::SecureStringToBSTR($inputToken) +try { $token=[Runtime.InteropServices.Marshal]::PtrToStringBSTR($ptr) } +finally { [Runtime.InteropServices.Marshal]::ZeroFreeBSTR($ptr) } +if($token -notmatch '^[A-Za-z0-9_-]{16,512}$'){throw 'Unexpected Playwright token format; no file written'} +if(-not(Test-Path -LiteralPath $secretDir -PathType Container)){ + [void](New-Item -ItemType Directory -Path $secretDir -Force) +} +# Remove inherited ACLs and grant only the current Windows account plus +# SYSTEM and Administrators. Never widen access to Users or Everyone. +$identity=[Security.Principal.WindowsIdentity]::GetCurrent() +$account=New-Object Security.Principal.NTAccount($identity.Name) +$acl=New-Object Security.AccessControl.DirectorySecurity +$acl.SetAccessRuleProtection($true,$false) +$acl.SetOwner($account) +$inherit=[Security.AccessControl.InheritanceFlags]'ContainerInherit, ObjectInherit' +$prop=[Security.AccessControl.PropagationFlags]::None +$allow=[Security.AccessControl.AccessControlType]::Allow +foreach($who in @($account,(New-Object Security.Principal.SecurityIdentifier('S-1-5-18')),(New-Object Security.Principal.SecurityIdentifier('S-1-5-32-544')))){ + $rule=New-Object Security.AccessControl.FileSystemAccessRule($who,[Security.AccessControl.FileSystemRights]::FullControl,$inherit,$prop,$allow) + $acl.AddAccessRule($rule) +} +Set-Acl -LiteralPath $secretDir -AclObject $acl -ErrorAction Stop +$tmp=Join-Path $secretDir ('.connection-token-'+[Guid]::NewGuid().ToString('N')+'.pending') +$backup=$null +$committed=$false +try{ + [IO.File]::WriteAllText($tmp,$token,[Text.Encoding]::ASCII) + $token=$null + if((Get-Item -LiteralPath $tmp).Length -lt 16){throw 'Token staging failed'} + if($Rotate){ + $backup=Join-Path $secretDir ('old-token-'+[Guid]::NewGuid().ToString('N')+'.pending') + Move-Item -LiteralPath $secretPath -Destination $backup -ErrorAction Stop + } + Move-Item -LiteralPath $tmp -Destination $secretPath -ErrorAction Stop + $committed=$true +}finally{ + $token=$null + if(Test-Path -LiteralPath $tmp){Remove-Item -LiteralPath $tmp -Force} + if($backup -and (Test-Path -LiteralPath $backup)){ + if(-not $committed -and -not (Test-Path -LiteralPath $secretPath)){ + Move-Item -LiteralPath $backup -Destination $secretPath -ErrorAction Stop + }elseif($committed){ + Remove-Item -LiteralPath $backup -Force -ErrorAction Stop + } + } +} +Write-Output 'Token stored in Windows user-restricted directory. Token value not printed.' +Write-Output ('To use after deploying a COMPATIBLE Codexify candidate, set mcpServers.playwright-extension.sessionScope=per-chat and env.PLAYWRIGHT_MCP_EXTENSION_TOKEN_FILE to '+$secretPath) +Write-Output 'Existing live configuration and browser remain unchanged.' \ No newline at end of file From 3c7cd8d490b740618c2f7c2097b43db0daac0499 Mon Sep 17 00:00:00 2001 From: tomi Date: Thu, 19 Nov 2026 02:19:27 +0100 Subject: [PATCH 025/118] fix(automation): retain native provider Send gate across v2.4 migration --- src/agent_automation/install.rs | 5 +++ src/markdown_chat/mod.rs | 66 +++++++++++++++++++++++++++++++++ src/server.rs | 15 ++++++++ 3 files changed, 86 insertions(+) diff --git a/src/agent_automation/install.rs b/src/agent_automation/install.rs index 05c9a0a3..34ad2576 100644 --- a/src/agent_automation/install.rs +++ b/src/agent_automation/install.rs @@ -326,6 +326,11 @@ impl BrowserCompanionManager { .stdin(Stdio::null()) .stdout(Stdio::from(log)) .stderr(Stdio::from(stderr)); + // Preserve the original browser-companion Send gate. The lock file + // intentionally need not exist until the provider first uses it. + if let Some(path) = &self.config.provider_send_gate_path { + command.env("CODEXIFY_BROWSER_SEND_GATE_PATH", path); + } configure_detached_process(&mut command); let mut child = command .spawn() diff --git a/src/markdown_chat/mod.rs b/src/markdown_chat/mod.rs index 5e11b839..eba4843b 100644 --- a/src/markdown_chat/mod.rs +++ b/src/markdown_chat/mod.rs @@ -178,6 +178,10 @@ pub struct AgentAutomationConfig { #[serde(skip_serializing_if = "Option::is_none")] pub browser_simplicity: Option, pub recovery_enhancements: bool, + /// Shared provider Send lock for the browser companion. This file may + /// be created on first use, so only the path itself is validated here. + #[serde(skip_serializing_if = "Option::is_none")] + pub provider_send_gate_path: Option, } impl Default for AgentAutomationConfig { @@ -204,6 +208,7 @@ impl Default for AgentAutomationConfig { minimal_ui: false, browser_simplicity: None, recovery_enhancements: false, + provider_send_gate_path: None, } } } @@ -227,6 +232,18 @@ impl AgentAutomationConfig { fn validate(&self) -> Result<(), String> { self.retry_timings.validate()?; + if let Some(path) = self.provider_send_gate_path.as_deref() { + if path.is_empty() + || path.len() > 4096 + || path.contains('\0') + || !std::path::Path::new(path).is_absolute() + { + return Err( + "agentChat.automation.providerSendGatePath must be an absolute path up to 4096 bytes" + .into(), + ); + } + } if !(1..=4).contains(&self.browser_action_lanes) { return Err("agentChat.automation.browserActionLanes must be between 1 and 4".into()); } @@ -773,6 +790,55 @@ pub(crate) async fn history_call( #[cfg(test)] mod tests { use super::*; + + #[test] + fn provider_send_gate_path_preserves_live_config_without_requiring_a_lockfile() { + let target = std::env::temp_dir().join("codexify-provider-send-gate-uncreated.lock"); + let path = target.to_string_lossy().into_owned(); + let config: AgentAutomationConfig = + serde_json::from_value(serde_json::json!({"providerSendGatePath": path})).unwrap(); + config.validate().unwrap(); + assert_eq!( + config.provider_send_gate_path.as_deref(), + Some(path.as_str()) + ); + let encoded = serde_json::to_value(&config).unwrap(); + assert_eq!(encoded["providerSendGatePath"], path.as_str()); + let restored: AgentAutomationConfig = serde_json::from_value(encoded).unwrap(); + restored.validate().unwrap(); + assert_eq!(restored.provider_send_gate_path, Some(path)); + + let default = AgentAutomationConfig::default(); + assert!(default.provider_send_gate_path.is_none()); + let omitted = serde_json::to_value(default).unwrap(); + assert!(omitted.get("providerSendGatePath").is_none()); + } + + #[test] + fn provider_send_gate_rejects_relative_nul_and_overlong_paths() { + for value in ["", "./send-gate.lock", "relative.lock", "bad\0path"] { + let config: AgentAutomationConfig = + serde_json::from_value(serde_json::json!({"providerSendGatePath": value})).unwrap(); + assert!(config.validate().is_err(), "{value:?} must be rejected"); + } + let overlong = std::env::temp_dir().join("x".repeat(4096)); + let config: AgentAutomationConfig = serde_json::from_value( + serde_json::json!({"providerSendGatePath": overlong.to_string_lossy()}), + ) + .unwrap(); + assert!(config.validate().is_err()); + } + + #[test] + fn provider_send_gate_does_not_weaken_other_schema_validation() { + assert!( + serde_json::from_value::( + serde_json::json!({"unknownSendGateProperty": "unsafe"}) + ) + .is_err() + ); + } + #[test] fn browser_simplicity_levels_preserve_legacy_choices_and_validate_values() { for (value, expected) in [ diff --git a/src/server.rs b/src/server.rs index 456491a4..a32f8b25 100644 --- a/src/server.rs +++ b/src/server.rs @@ -2162,6 +2162,21 @@ pub async fn start_http_server(mut config: AppConfig) -> anyhow::Result<()> { Err(error) => tracing::warn!("managed-worktree cleanup skipped: {error}"), } } + // Persisted configuration remains the source of truth. The historical + // override exists for explicitly isolated canary launches; validate it + // before handing it to the browser companion. + if let Ok(path) = std::env::var("CODEXIFY_BROWSER_SEND_GATE_PATH") { + if path.is_empty() + || path.len() > 4096 + || path.contains('\0') + || !std::path::Path::new(&path).is_absolute() + { + anyhow::bail!( + "CODEXIFY_BROWSER_SEND_GATE_PATH must be an absolute path up to 4096 bytes" + ); + } + config.markdown_chat.automation.provider_send_gate_path = Some(path); + } let config = Arc::new(config); let _browser_recovery = crate::agent_automation::watch_browser_companion(&config.markdown_chat.automation); From aed31a3a07f117d4e93ea43d84430a9eb22d4139 Mon Sep 17 00:00:00 2001 From: tomi Date: Thu, 19 Nov 2026 02:19:27 +0100 Subject: [PATCH 026/118] ci(windows): validate browser isolation and build review-only v2.4 candidate --- .../workflows/v240-playwright-compatible.yml | 72 +++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 .github/workflows/v240-playwright-compatible.yml diff --git a/.github/workflows/v240-playwright-compatible.yml b/.github/workflows/v240-playwright-compatible.yml new file mode 100644 index 00000000..7f6682f6 --- /dev/null +++ b/.github/workflows/v240-playwright-compatible.yml @@ -0,0 +1,72 @@ +name: v2.4 Playwright per-chat Windows candidate (validation only) + +on: + push: + branches: + - fix/v240-playwright-compatible-20261119 + +permissions: + contents: read + +jobs: + windows-candidate: + runs-on: windows-latest + timeout-minutes: 90 + defaults: + run: + shell: pwsh + env: + CARGO_BUILD_JOBS: '2' + CARGO_INCREMENTAL: '0' + CARGO_PROFILE_DEV_DEBUG: line-tables-only + CARGO_PROFILE_TEST_DEBUG: line-tables-only + steps: + - uses: actions/checkout@v5 + with: + fetch-depth: 0 + - uses: dtolnay/rust-toolchain@stable + with: + components: rustfmt + - uses: Swatinem/rust-cache@v2 + - name: Verify source provenance and formatting + run: | + $ErrorActionPreference = 'Stop' + git merge-base --is-ancestor ef323c124f73396e5c3cdada6f471c4b2783d910 HEAD + if ($LASTEXITCODE -ne 0) { throw 'Missing verified v2.4 OAuth/goal baseline' } + git merge-base --is-ancestor cd4e483 HEAD + if ($LASTEXITCODE -ne 0) { throw 'Missing per-chat Playwright isolation baseline' } + git diff --check ef323c124f73396e5c3cdada6f471c4b2783d910 HEAD + if ($LASTEXITCODE -ne 0) { throw 'Diff whitespace validation failed' } + cargo fmt --all -- --check + if ($LASTEXITCODE -ne 0) { throw 'Rustfmt validation failed' } + - name: Validate all Rust test targets + run: | + cargo check --locked --tests -j 2 + if ($LASTEXITCODE -ne 0) { throw 'Rust test targets do not compile' } + - name: Verify browser ownership and preserved Send gate + run: | + cargo test --locked --lib playwright_sessions::tests -j 2 + if ($LASTEXITCODE -ne 0) { throw 'Per-chat browser ownership regression' } + cargo test --locked --lib provider_send_gate -j 2 + if ($LASTEXITCODE -ne 0) { throw 'Provider Send gate compatibility regression' } + cargo test --locked --lib bridge::tests -j 2 + if ($LASTEXITCODE -ne 0) { throw 'Upstream MCP bridge regression' } + - name: Verify complete v2.4 library suite + run: | + cargo test --locked --lib -j 2 + if ($LASTEXITCODE -ne 0) { throw 'Full library regression suite failed' } + - name: Build official v2.4-based Windows executable + run: | + cargo build --locked --release --bin codexify -j 2 + if ($LASTEXITCODE -ne 0) { throw 'Windows native release build failed' } + & .\target\release\codexify.exe --help | Select-Object -First 5 + if ($LASTEXITCODE -ne 0) { throw 'Built executable is not runnable' } + $sha = (Get-FileHash .\target\release\codexify.exe -Algorithm SHA256).Hash + Write-Output "Verified Windows candidate SHA256: $sha" + - name: Upload reviewable binary without installing + uses: actions/upload-artifact@v4 + with: + name: codexify-v240-playwright-compatible-windows + path: target/release/codexify.exe + if-no-files-found: error + retention-days: 1 From 171560052a437ef06010000d09d9949a4dc2d975 Mon Sep 17 00:00:00 2001 From: tomi Date: Thu, 19 Nov 2026 03:18:21 +0100 Subject: [PATCH 027/118] perf(mcp): bound parallel upstream startup and preserve catalog order --- src/bridge.rs | 190 ++++++++++++++++++++++++++++++------- src/playwright_sessions.rs | 25 +++++ 2 files changed, 180 insertions(+), 35 deletions(-) diff --git a/src/bridge.rs b/src/bridge.rs index e39e0fa7..0b118f59 100644 --- a/src/bridge.rs +++ b/src/bridge.rs @@ -703,50 +703,81 @@ pub async fn connect_upstreams(config: &AppConfig) -> Bridge { let mut catalog_sources = Vec::new(); let resources = Arc::new(BridgedResourceStore::new(config.artifact_egress.clone())); - // Deterministic order so logs and tool ordering are stable across runs. - let mut names: Vec<&String> = config.mcp_servers.keys().collect(); + // Discover tool schemas concurrently, but in small bounded batches so + // launching local MCP children cannot exhaust RAM on a desktop host. + // Connection results are retained in sorted order for stable tool names, + // catalog ordering, and diagnostics. Per-chat Playwright still creates + // agent-owned browser processes only when that agent actually calls a tool. + const MAX_PARALLEL_UPSTREAM_STARTS: usize = 3; + let mut names: Vec = config.mcp_servers.keys().cloned().collect(); names.sort(); + let source_config = Arc::new(config.clone()); + let startup_slots = Arc::new(tokio::sync::Semaphore::new(MAX_PARALLEL_UPSTREAM_STARTS)); + let mut joins = tokio::task::JoinSet::new(); + for (index, server_name) in names.iter().cloned().enumerate() { + let source_config = Arc::clone(&source_config); + let startup_slots = Arc::clone(&startup_slots); + joins.spawn(async move { + let _permit = match startup_slots.acquire_owned().await { + Ok(permit) => permit, + Err(_) => return (index, None, Err("MCP startup limiter closed".into())), + }; + let spec = &source_config.mcp_servers[&server_name]; + if spec.disabled { + return (index, None, Err("disabled".into())); + } + let scoped_pool = if spec.session_scope == McpSessionScope::PerChat { + match crate::playwright_sessions::ScopedPlaywrightPool::new( + &server_name, + spec, + &source_config, + ) { + Ok(pool) => Some(Arc::new(pool)), + Err(error) => return (index, None, Err(error)), + } + } else { + None + }; + let discovery = match &scoped_pool { + Some(pool) => match pool.discovery_spec() { + Ok(spec) => Some(spec), + Err(error) => return (index, None, Err(error)), + }, + None => None, + }; + let spec_for_discovery = discovery.as_ref().unwrap_or(spec); + let connected = connect_one(&server_name, spec_for_discovery, &source_config).await; + (index, scoped_pool, connected) + }); + } + // A child startup failure must not abort healthy unrelated MCP sources. + let mut results: Vec<_> = std::iter::repeat_with(|| None).take(names.len()).collect(); + while let Some(result) = joins.join_next().await { + match result { + Ok((index, pool, connection)) => results[index] = Some((pool, connection)), + Err(error) => { + tracing::warn!("upstream initialization task failed without a result: {error}") + } + } + } - for server_name in names { - let spec = &config.mcp_servers[server_name]; + for (index, server_name) in names.into_iter().enumerate() { + let spec = &config.mcp_servers[&server_name]; if spec.disabled { report.push(format!("{server_name} -> disabled")); continue; } - let sanitized = sanitize(server_name); + let sanitized = sanitize(&server_name); let exposure = spec.exposure(); - - // Validate per-chat ownership and prepare an isolated schema-discovery - // browser before launching any extension. Without the token, skip the - // provider entirely: no accidental manual approval dialog. - let scoped_pool = if spec.session_scope == McpSessionScope::PerChat { - match crate::playwright_sessions::ScopedPlaywrightPool::new(server_name, spec, config) { - Ok(pool) => Some(Arc::new(pool)), - Err(error) => { - report.push(format!("{server_name} -> FAILED: {error}")); - continue; - } - } - } else { - None - }; - let discovery = match &scoped_pool { - Some(pool) => match pool.discovery_spec() { - Ok(spec) => Some(spec), - Err(error) => { - report.push(format!("{server_name} -> FAILED: {error}")); - continue; - } - }, - None => None, - }; - let discovery_spec = discovery.as_ref().unwrap_or(spec); - match connect_one(server_name, discovery_spec, config).await { + let (scoped_pool, connection) = results[index] + .take() + .unwrap_or_else(|| (None, Err("MCP startup task failed".into()))); + match connection { Ok((service, upstream_tools, tool_timeout)) => { let peer = service.peer().clone(); let control = Arc::new( crate::upstream_control::UpstreamControl::new(spec.request_limits.clone()) - .for_server(server_name, spec) + .for_server(&server_name, spec) .with_scoped_playwright(scoped_pool), ); upstreams.insert(server_name.clone(), control.clone()); @@ -768,13 +799,13 @@ pub async fn connect_upstreams(config: &AppConfig) -> Bridge { }) .collect(); - write_gateway_skill(config, server_name, &sanitized, &functions); + write_gateway_skill(config, &server_name, &sanitized, &functions); let leaked: &'static str = Box::leak(sanitized.clone().into_boxed_str()); tools.push(Box::new(GatewayTool { name: leaked, server: server_name.clone(), - description: gateway_description(server_name, &functions), + description: gateway_description(&server_name, &functions), function_names: functions.iter().map(|f| f.name.clone()).collect(), peer: peer.clone(), tool_timeout, @@ -3386,6 +3417,95 @@ mod tests { task.abort(); } + #[derive(Clone)] + struct DelayedCatalogMcp { + active: Arc, + peak: Arc, + } + + impl ServerHandler for DelayedCatalogMcp { + fn get_info(&self) -> ServerInfo { + InitializeResult::new(ServerCapabilities::builder().enable_tools().build()) + .with_server_info(Implementation::new("delayed-catalog", "1.0.0")) + } + + async fn list_tools( + &self, + _request: Option, + _context: RequestContext, + ) -> Result { + use std::sync::atomic::Ordering; + let count = self.active.fetch_add(1, Ordering::SeqCst) + 1; + self.peak.fetch_max(count, Ordering::SeqCst); + tokio::time::sleep(Duration::from_millis(400)).await; + self.active.fetch_sub(1, Ordering::SeqCst); + let schema = json!({"type":"object"}).as_object().unwrap().clone(); + Ok(ListToolsResult::with_all_items(vec![ + rmcp::model::Tool::new("noop", "No-op for bounded startup regression", schema), + ])) + } + } + + #[tokio::test] + async fn initializes_multiple_mcp_sources_concurrently_without_reordering_the_catalog() { + use std::sync::atomic::{AtomicUsize, Ordering}; + let active = Arc::new(AtomicUsize::new(0)); + let peak = Arc::new(AtomicUsize::new(0)); + let upstream = DelayedCatalogMcp { + active: Arc::clone(&active), + peak: Arc::clone(&peak), + }; + let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0)) + .await + .unwrap(); + let address = listener.local_addr().unwrap(); + let mut http = StreamableHttpServerConfig::default(); + http.json_response = true; + let service = StreamableHttpService::new( + move || Ok(upstream.clone()), + Arc::new(LocalSessionManager::default()), + http, + ); + let server_task = tokio::spawn(async move { + axum::serve(listener, Router::new().nest_service("/mcp", service)) + .await + .unwrap(); + }); + let mut config = crate::config::default_config(std::env::temp_dir()); + for name in ["delta", "bravo", "alpha", "charlie"] { + config.mcp_servers.insert( + name.into(), + McpServerSpec { + url: Some(format!("http://{address}/mcp")), + transport: Some("http".into()), + mode: Some(McpToolExposure::Direct), + startup_timeout_sec: Some(5.0), + ..Default::default() + }, + ); + } + let bridge = connect_upstreams(&config).await; + assert_eq!( + bridge.services.len(), + 4, + "all four MCP sources should connect" + ); + let reported: Vec<_> = bridge + .report + .iter() + .map(|line| line.split_once(" ->").unwrap().0) + .collect(); + assert_eq!(reported, ["alpha", "bravo", "charlie", "delta"]); + let maximum = peak.load(Ordering::SeqCst); + assert!( + (2..=3).contains(&maximum), + "MCP cold-start requests must overlap without exceeding the three-slot limit: {maximum}" + ); + assert_eq!(active.load(Ordering::SeqCst), 0); + drop(bridge); + server_task.abort(); + } + #[tokio::test] async fn skips_upstream_that_fails_to_launch() { let mut config = crate::config::default_config(std::env::temp_dir()); diff --git a/src/playwright_sessions.rs b/src/playwright_sessions.rs index c0010255..e1a69785 100644 --- a/src/playwright_sessions.rs +++ b/src/playwright_sessions.rs @@ -159,6 +159,11 @@ impl ScopedPlaywrightPool { return Err("invalid per-chat browser owner identity".into()); } let mut spec = self.spec.clone(); + // Managed Chromium can take longer than the generic 20-second MCP + // default to cold-start under desktop load. Keep explicit overrides. + if !self.extension && spec.startup_timeout_sec.is_none() { + spec.startup_timeout_sec = Some(60.0); + } if self.extension { load_extension_token(&mut spec)?; spec.env.insert( @@ -347,6 +352,26 @@ mod tests { spec } + #[test] + fn managed_playwright_cold_start_is_bounded_but_respects_owner_override() { + let initial = spec(false); + let pool = ScopedPlaywrightPool::new("playwright", &initial, &stub_config()).unwrap(); + let discovery = pool.discovery_spec().unwrap(); + assert_eq!(discovery.startup_timeout_sec, Some(60.0)); + let owner = ConversationIdentity::from_openai_session("agent-a").unwrap(); + assert_eq!( + pool.scoped_spec(&owner).unwrap().startup_timeout_sec, + Some(60.0) + ); + let mut overridden = spec(false); + overridden.startup_timeout_sec = Some(95.0); + let pool = ScopedPlaywrightPool::new("playwright", &overridden, &stub_config()).unwrap(); + assert_eq!( + pool.discovery_spec().unwrap().startup_timeout_sec, + Some(95.0) + ); + } + #[test] fn distinct_conversations_receive_distinct_persistent_profiles() { let pool = ScopedPlaywrightPool::new("playwright", &spec(false), &stub_config()).unwrap(); From cad7292f29942be54b61cee7f7603855e2cf45b7 Mon Sep 17 00:00:00 2001 From: tomi Date: Thu, 19 Nov 2026 03:18:23 +0100 Subject: [PATCH 028/118] ci(windows): validate parallel-startup candidate on public runner --- .github/workflows/v240-playwright-compatible.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/v240-playwright-compatible.yml b/.github/workflows/v240-playwright-compatible.yml index 7f6682f6..c13db4e4 100644 --- a/.github/workflows/v240-playwright-compatible.yml +++ b/.github/workflows/v240-playwright-compatible.yml @@ -4,6 +4,7 @@ on: push: branches: - fix/v240-playwright-compatible-20261119 + - fix/v240-playwright-parallel-startup-20261119 permissions: contents: read From 2f7c5324ac20559f02822f397960942e0377c83a Mon Sep 17 00:00:00 2001 From: tomi Date: Thu, 19 Nov 2026 16:24:39 +0100 Subject: [PATCH 029/118] fix(config): preserve explicit per-chat MCP session scope --- src/config.rs | 66 ++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 65 insertions(+), 1 deletion(-) diff --git a/src/config.rs b/src/config.rs index 47172b4d..c7692aa1 100644 --- a/src/config.rs +++ b/src/config.rs @@ -23,7 +23,7 @@ use crate::project_catalog::{ProjectCatalog, discover_project_catalog_at}; use crate::types::{ AppConfig, ArtifactEgressConfig, ArtifactIngressConfig, AuditConfig, CodexProjectCatalogConfig, CommandConfig, ConversationAuthToken, DiffConfig, ExecConfig, ExperimentalConfig, - FilesystemConfig, IgnoreConfig, McpServerSpec, McpToolExposure, MemoryConfig, + FilesystemConfig, IgnoreConfig, McpServerSpec, McpSessionScope, McpToolExposure, MemoryConfig, OpenAiTunnelConfig, OutputConfig, ProjectCatalogConfig, ProjectCatalogEntryConfig, ProjectDocConfig, SkillsConfig, ToolLogLevel, ToolLogMode, ToolLoggingConfig, TreeConfig, WorktreeConfig, WorktreeMode, WorktreeUpstreamRefreshMode, @@ -615,6 +615,9 @@ struct PartialMcpServerSpec { tools: Option>, disabled_tools: Option>, mode: Option, + // Dropping this explicit field silently downgrades per-chat browser + // ownership and its token-file authorization to a shared global client. + session_scope: Option, } impl PartialMcpServerSpec { @@ -636,6 +639,7 @@ impl PartialMcpServerSpec { tools, disabled_tools, mode, + session_scope, } = self; let sets_command = command.is_some(); let sets_args = args.is_some(); @@ -695,6 +699,9 @@ impl PartialMcpServerSpec { if let Some(mode) = mode { base.mode = Some(mode); } + if let Some(scope) = session_scope { + base.session_scope = scope; + } // Naming a different transport replaces the imported transport rather // than leaving an impossible command+URL hybrid behind. @@ -3154,6 +3161,63 @@ mod tests { } } + #[test] + fn explicit_playwright_session_scope_survives_json_overlay() { + let partial: PartialMcpServerSpec = serde_json::from_value(serde_json::json!({ + "command": "node", + "args": ["@playwright/mcp", "--extension"], + "sessionScope": "per-chat", + "env": { + "PLAYWRIGHT_MCP_PROFILE_DIR_NAME": "Profile 3", + "PLAYWRIGHT_MCP_EXTENSION_TOKEN_FILE": "C:/private/extension-token" + } + })) + .unwrap(); + let (servers, _) = merge_mcp_servers( + HashMap::new(), + HashMap::from([("playwright-extension".to_string(), partial)]), + ); + let spec = &servers["playwright-extension"]; + assert_eq!(spec.session_scope, McpSessionScope::PerChat); + assert_eq!(spec.exposure(), McpToolExposure::Direct); + assert_eq!( + spec.env + .get("PLAYWRIGHT_MCP_PROFILE_DIR_NAME") + .map(String::as_str), + Some("Profile 3") + ); + assert!(spec.env.contains_key("PLAYWRIGHT_MCP_EXTENSION_TOKEN_FILE")); + } + + #[test] + fn explicit_scope_overlay_preserves_or_overrides_imported_scope() { + let mut imported = imported_server(); + imported.session_scope = McpSessionScope::PerChat; + let untouched = PartialMcpServerSpec { + disabled: Some(false), + ..Default::default() + }; + let (servers, _) = merge_mcp_servers( + HashMap::from([("demo".to_string(), imported.clone())]), + HashMap::from([("demo".to_string(), untouched)]), + ); + assert_eq!(servers["demo"].session_scope, McpSessionScope::PerChat); + + let explicit: PartialMcpServerSpec = + serde_json::from_value(serde_json::json!({"sessionScope": "global"})).unwrap(); + let (servers, _) = merge_mcp_servers( + HashMap::from([("demo".to_string(), imported)]), + HashMap::from([("demo".to_string(), explicit)]), + ); + assert_eq!(servers["demo"].session_scope, McpSessionScope::Global); + assert!( + serde_json::from_value::( + serde_json::json!({"sessionScope": "shared"}) + ) + .is_err() + ); + } + #[test] fn local_entry_can_add_gateway_mode_without_repeating_launch_config() { let imported = HashMap::from([("demo".to_string(), imported_server())]); From 6ff8ce75f492e21527104c7dff358f8fb538806a Mon Sep 17 00:00:00 2001 From: tomi Date: Thu, 19 Nov 2026 16:24:40 +0100 Subject: [PATCH 030/118] ci(windows): test MCP session-scope overlay before release --- .github/workflows/v240-playwright-compatible.yml | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/.github/workflows/v240-playwright-compatible.yml b/.github/workflows/v240-playwright-compatible.yml index c13db4e4..4eb60bec 100644 --- a/.github/workflows/v240-playwright-compatible.yml +++ b/.github/workflows/v240-playwright-compatible.yml @@ -5,6 +5,7 @@ on: branches: - fix/v240-playwright-compatible-20261119 - fix/v240-playwright-parallel-startup-20261119 + - fix/v240-configured-playwright-scope-20261119 permissions: contents: read @@ -44,6 +45,12 @@ jobs: run: | cargo check --locked --tests -j 2 if ($LASTEXITCODE -ne 0) { throw 'Rust test targets do not compile' } + - name: Verify explicit per-chat configuration overlay + run: | + cargo test --locked --lib config::tests::explicit_playwright_session_scope_survives_json_overlay -j 2 + if ($LASTEXITCODE -ne 0) { throw 'Playwright sessionScope was silently downgraded to global' } + cargo test --locked --lib config::tests::explicit_scope_overlay_preserves_or_overrides_imported_scope -j 2 + if ($LASTEXITCODE -ne 0) { throw 'MCP imported scope overlay regression' } - name: Verify browser ownership and preserved Send gate run: | cargo test --locked --lib playwright_sessions::tests -j 2 From 69167b51dd2baf624182e8ba136aebc0b48092bf Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:18:56 +0100 Subject: [PATCH 031/118] feat(mcp): introduce isolated transactional upstream reload runtime --- src/bridge/hot_reload.rs | 512 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 512 insertions(+) create mode 100644 src/bridge/hot_reload.rs diff --git a/src/bridge/hot_reload.rs b/src/bridge/hot_reload.rs new file mode 100644 index 00000000..77b14cc0 --- /dev/null +++ b/src/bridge/hot_reload.rs @@ -0,0 +1,512 @@ +//! Transactional replacement of one upstream MCP connection. +//! +//! All model-visible tools are rebuilt as one immutable registry snapshot. A +//! dispatch keeps its snapshot for its entire call, so old generations cannot +//! be disposed while requests are using them. +use super::*; +use clap::Parser; +use std::collections::{HashMap, HashSet}; +use std::sync::{Arc, Mutex, RwLock}; +use tokio::sync::{Mutex as AsyncMutex, Notify}; + +const MAX_INTERNED_TOOL_NAMES: usize = 4096; +const REPLACEMENT_PING_TIMEOUT: Duration = Duration::from_secs(3); + +pub(super) struct Generation { + pub(super) name: String, + pub(super) spec: crate::types::McpServerSpec, + pub(super) peer: Peer, + pub(super) tools: Vec, + pub(super) timeout: Option, + pub(super) control: Arc, + pub(super) number: u64, + // Keep the transport alive until every snapshot/call using it is dropped. + _service: Mutex>, + _monitor: UpstreamMonitor, + calls: Mutex, + drained: Notify, +} + +pub(super) struct CallLease<'a>(&'a Generation); + +impl Drop for CallLease<'_> { + fn drop(&mut self) { + let mut calls = self.0.calls.lock().unwrap(); + *calls -= 1; + if *calls == 0 { + self.0.drained.notify_one(); + } + } +} + +impl Generation { + pub(super) fn new( + name: String, + spec: crate::types::McpServerSpec, + service: RunningService, + tools: Vec, + timeout: Option, + number: u64, + ) -> Arc { + let peer = service.peer().clone(); + let control = Arc::new(crate::upstream_control::UpstreamControl::new( + spec.request_limits.clone(), + )); + let monitor = monitor_upstream(peer.clone(), control.clone()); + Arc::new(Self { + name, + spec, + peer, + tools, + timeout, + control, + number, + _service: Mutex::new(service), + _monitor: monitor, + calls: Mutex::new(0), + drained: Notify::new(), + }) + } + + pub(super) fn begin_call(&self) -> CallLease<'_> { + *self.calls.lock().unwrap() += 1; + CallLease(self) + } + + async fn wait_for_calls(&self, limit: Duration) -> bool { + tokio::time::timeout(limit, async { + loop { + if *self.calls.lock().unwrap() == 0 { + break; + } + self.drained.notified().await; + } + }) + .await + .is_ok() + } + + fn version(&self) -> Option { + self.peer + .peer_info() + .and_then(|info| info.server_info.as_ref().map(|info| info.version.to_string())) + } +} + +struct NamePool(HashMap); + +impl NamePool { + fn intern(&mut self, name: String) -> Result<&'static str, &'static str> { + if let Some(value) = self.0.get(&name) { + return Ok(value); + } + if self.0.len() >= MAX_INTERNED_TOOL_NAMES { + return Err("TOOL_NAME_LIMIT"); + } + let leaked: &'static str = Box::leak(name.clone().into_boxed_str()); + self.0.insert(name, leaked); + Ok(leaked) + } +} + +pub(crate) struct BridgeView { + pub(crate) tools: Arc>>, + sources: HashMap>, +} + +pub(crate) struct HotReloadRuntime { + view: RwLock>, + config: Arc, + resources: Arc, + names: Mutex, + locks: HashMap>>, + pub(crate) upstreams: + Arc>>>, +} + +impl HotReloadRuntime { + pub(super) fn new( + config: Arc, + resources: Arc, + sources: HashMap>, + ) -> Arc { + let upstreams = sources + .iter() + .map(|(name, generation)| (name.clone(), generation.control.clone())) + .collect(); + let locks = config + .mcp_servers + .keys() + .map(|name| (name.clone(), Arc::new(AsyncMutex::new(())))) + .collect(); + let runtime = Arc::new(Self { + view: RwLock::new(Arc::new(BridgeView { + tools: Arc::new(Vec::new()), + sources: sources.clone(), + })), + config, + resources, + names: Mutex::new(NamePool(HashMap::new())), + locks, + upstreams: Arc::new(RwLock::new(upstreams)), + }); + match runtime.build_view(sources) { + Ok(view) => *runtime.view.write().unwrap() = Arc::new(view), + Err(code) => tracing::error!(%code, "initial MCP registry could not be built"), + } + runtime + } + + pub(crate) fn snapshot(&self) -> Arc { + self.view.read().unwrap().clone() + } + + fn build_view( + &self, + sources: HashMap>, + ) -> Result { + let mut exposed = Vec::new(); + let mut catalog = Vec::new(); + let mut names = self.names.lock().unwrap(); + let mut sorted: Vec<_> = sources.keys().collect(); + sorted.sort(); + for name in sorted { + let source = &sources[name]; + let sanitized = sanitize(name); + match source.spec.exposure() { + McpToolExposure::Gateway => { + let functions: Vec = source + .tools + .iter() + .map(|tool| GatewayFunction { + name: tool.name.to_string(), + description: tool + .description + .as_ref() + .map(ToString::to_string) + .unwrap_or_default(), + input_schema: Value::Object((*tool.input_schema).clone()), + }) + .collect(); + let tool = GatewayTool { + name: names.intern(sanitized)?, + server: name.clone(), + description: gateway_description(name, &functions), + function_names: functions.iter().map(|tool| tool.name.clone()).collect(), + peer: source.peer.clone(), + tool_timeout: source.timeout, + control: source.control.clone(), + resources: self.resources.clone(), + generation: source.clone(), + }; + exposed.push(Box::new(tool) as Box); + } + McpToolExposure::Direct => { + let mut used = HashSet::new(); + for tool in &source.tools { + let raw_name = tool.name.to_string(); + let display = + unique_name(bridged_name(&sanitized, &raw_name), &used); + used.insert(display.clone()); + let description = tool + .description + .as_ref() + .map(ToString::to_string) + .filter(|description| !description.trim().is_empty()) + .unwrap_or_else(|| { + format!("Call the '{raw_name}' tool on the '{name}' MCP server.") + }); + exposed.push(Box::new(BridgedTool { + name: names.intern(display)?, + original_name: raw_name, + server: name.clone(), + title: tool.title.clone().filter(|value| !value.trim().is_empty()), + description, + input_schema: Value::Object((*tool.input_schema).clone()), + output_schema: tool + .output_schema + .as_ref() + .map(|schema| Value::Object((**schema).clone())), + annotations: tool.annotations.clone(), + icons: tool.icons.clone(), + meta: tool.meta.clone(), + peer: source.peer.clone(), + tool_timeout: source.timeout, + control: source.control.clone(), + resources: self.resources.clone(), + generation: source.clone(), + }) as Box); + } + } + McpToolExposure::Catalog => { + catalog.push(CatalogSourceInput { + raw_name: name.clone(), + provenance: source.spec.provenance, + transport: transport_label(&source.spec), + peer_info: source.peer.peer_info(), + tools: source.tools.clone(), + peer: source.peer.clone(), + tool_timeout: source.timeout, + control: source.control.clone(), + generation: source.clone(), + }); + } + } + } + let mut tools = build_catalog_tools(catalog, self.resources.clone()); + tools.append(&mut exposed); + let tools = tools + .into_iter() + .filter_map(|tool| match crate::tool::validate_and_wrap_tool(tool) { + Ok(tool) => Some(tool), + Err(error) => { + tracing::warn!(%error, "invalid upstream MCP tool skipped"); + None + } + }) + .collect(); + Ok(BridgeView { + sources, + tools: Arc::new(tools), + }) + } + + fn latest_spec(&self, name: &str) -> Result { + // Parse the same CLI arguments as startup; this is read-only and never + // rewrites a config migration. No executable or path comes from the MCP + // request: only the operator's configured source ID is accepted. + let cli = crate::config::Cli::try_parse_from(std::env::args_os()) + .map_err(|_| "CONFIG_CLI_INVALID")?; + let config = crate::config::load_config_quiet_read_only(cli) + .map_err(|_| "CONFIG_INVALID")?; + config + .mcp_servers + .get(name) + .cloned() + .ok_or("SOURCE_REMOVED") + } + + pub(crate) async fn reload( + &self, + name: &str, + cancellation: Option<&CancellationToken>, + ) -> Result { + if name.is_empty() || name.len() > 128 || name.chars().any(char::is_control) { + return Err("SOURCE_ID_INVALID"); + } + let lock = self.locks.get(name).ok_or("SOURCE_UNKNOWN")?; + let _lease = lock.try_lock().map_err(|_| "RELOAD_IN_PROGRESS")?; + let spec = self.latest_spec(name)?; + self.reload_with_spec_locked(name, spec, cancellation).await + } + + // Injecting a spec is intentionally private to the server process. It also + // allows hermetic fault-injection tests without reading the operator config. + async fn reload_with_spec_locked( + &self, + name: &str, + spec: crate::types::McpServerSpec, + cancellation: Option<&CancellationToken>, + ) -> Result { + if spec.disabled { + return Err("SOURCE_DISABLED"); + } + if cancellation.is_some_and(CancellationToken::is_cancelled) { + return Err("CANCELLED"); + } + let previous = self.snapshot().sources.get(name).cloned(); + let old_generation = previous.as_ref().map_or(0, |source| source.number); + let future = connect_one(name, &spec, &self.config); + let (service, tools, timeout) = if let Some(token) = cancellation { + tokio::select! { + _ = token.cancelled() => return Err("CANCELLED"), + result = future => result.map_err(|_| "INITIALIZE_FAILED")?, + } + } else { + future.await.map_err(|_| "INITIALIZE_FAILED")? + }; + let ready = matches!( + tokio::time::timeout( + REPLACEMENT_PING_TIMEOUT, + service + .peer() + .send_request(ClientRequest::PingRequest(Default::default())) + ) + .await, + Ok(Ok(_) | Err(ServiceError::McpError(_))) + ); + if !ready { + return Err("READINESS_FAILED"); + } + + let added; + let removed; + let changed; + let unchanged; + { + let before: HashMap<_, _> = previous + .as_ref() + .map(|generation| &generation.tools) + .into_iter() + .flatten() + .map(|tool| (tool.name.as_ref(), serde_json::to_value(tool).unwrap_or(Value::Null))) + .collect(); + let after: HashMap<_, _> = tools + .iter() + .map(|tool| (tool.name.as_ref(), serde_json::to_value(tool).unwrap_or(Value::Null))) + .collect(); + added = after.keys().filter(|key| !before.contains_key(**key)).count(); + removed = before.keys().filter(|key| !after.contains_key(**key)).count(); + changed = after + .iter() + .filter(|(key, value)| before.get(**key).is_some_and(|old| old != *value)) + .count(); + unchanged = after + .iter() + .filter(|(key, value)| before.get(**key).is_some_and(|old| old == *value)) + .count(); + } + let new = Generation::new( + name.to_owned(), + spec, + service, + tools, + timeout, + old_generation + 1, + ); + let new_version = new.version(); + // Connection preparation and view construction are outside the write + // lock. Compare-and-rebuild prevents concurrent distinct-source reloads + // from overwriting each other. + loop { + let before = self.snapshot(); + let mut sources = before.sources.clone(); + sources.insert(name.to_owned(), new.clone()); + let candidate = Arc::new(self.build_view(sources)?); + let mut current = self.view.write().unwrap(); + if !Arc::ptr_eq(&before, ¤t) { + continue; + } + *current = candidate; + break; + } + self.upstreams + .write() + .unwrap() + .insert(name.to_owned(), new.control.clone()); + + if new.spec.exposure() == McpToolExposure::Gateway { + let funcs = new + .tools + .iter() + .map(|t| GatewayFunction { + name: t.name.to_string(), + description: t.description.as_ref().map(ToString::to_string).unwrap_or_default(), + input_schema: Value::Object((*t.input_schema).clone()), + }) + .collect::>(); + write_gateway_skill(&self.config, name, &sanitize(name), &funcs); + } + + // The old generation stays alive in any request's registry snapshot. + // On a bounded drain timeout its existing calls are NOT cancelled or + // replayed; the generation retires when the last call releases it. + let drain_ms = previous + .as_ref() + .map_or(0, |source| source.spec.request_limits.slow_cancellation_ms); + let drained = if let Some(old) = &previous { + old.wait_for_calls(Duration::from_millis(drain_ms)).await + } else { + true + }; + Ok(json!({ + "source": name, + "outcome": "reloaded", + "previousGeneration": old_generation, + "replacementGeneration": new.number, + "previousVersion": previous.as_ref().and_then(|old| old.version()), + "replacementVersion": new_version, + "ready": true, + "toolChanges": { + "added": added, "removed": removed, "changed": changed, "unchanged": unchanged + }, + "oldCallsDrained": drained, + "oldGenerationRetiring": !drained, + "rollback": "not_required", + "clientRediscoveryRequired": true, + "diagnosticCode": "OK" + })) + } +} + +pub(crate) struct ReloadMcpTool { + pub(crate) runtime: Arc, +} + +#[async_trait] +impl Tool for ReloadMcpTool { + fn name(&self) -> &'static str { + "reload_mcp" + } + + fn title(&self) -> String { + "Reload one MCP source".into() + } + + fn description(&self) -> String { + "Transactionally replace one configured upstream MCP source without restarting Codexify or reconnecting any other source. The source is its exact configured MCP server key, not an executable path. Existing calls keep the previous generation. Tool definition changes require the client to rediscover tools/list; in-chat ChatGPT schema updates are not guaranteed.".into() + } + + fn behavior(&self) -> ToolBehavior { + ToolBehavior::new( + false, + true, + false, + false, + "Process replacement is an operator action; no arbitrary executable arguments are accepted.", + ) + } + + fn input_schema(&self) -> Value { + json!({ + "type": "object", + "properties": { + "source": {"type": "string", "minLength": 1, "maxLength": 128, + "description": "Exact stable key of an existing configured MCP server"} + }, + "required": ["source"], + "additionalProperties": false + }) + } + + fn requires_project_root(&self) -> bool { + false + } + + async fn call(&self, args: Value, _config: &AppConfig, _session: &SessionState) -> ToolResult { + self.run(&args, None).await + } + + async fn call_with_context( + &self, + args: Value, + _config: &AppConfig, + _session: &SessionState, + context: &ToolRequestContext, + ) -> ToolResult { + self.run(&args, Some(&context.cancellation)).await + } +} + +impl ReloadMcpTool { + async fn run(&self, args: &Value, cancellation: Option<&CancellationToken>) -> ToolResult { + let Some(source) = args.get("source").and_then(Value::as_str) else { + return ToolResult::error("SOURCE_ID_INVALID"); + }; + match self.runtime.reload(source, cancellation).await { + Ok(report) => ToolResult::text("MCP source reloaded; rediscover tools to refresh client schemas.") + .with_structured(report), + Err(code) => ToolResult::error(format!("MCP reload did not switch connections: {code}")), + } + } +} From 7feef36064aadee73edb5a171b6f7ba05940dd51 Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:19:25 +0100 Subject: [PATCH 032/118] refactor(mcp): own upstream services by immutable connection generation --- src/bridge.rs | 190 ++++++++++++-------------------------------------- 1 file changed, 46 insertions(+), 144 deletions(-) diff --git a/src/bridge.rs b/src/bridge.rs index 68bdcef4..37a32e78 100644 --- a/src/bridge.rs +++ b/src/bridge.rs @@ -36,25 +36,22 @@ use crate::tool::{Tool, ToolBehavior, ToolCallIdentity, ToolRequestContext}; use crate::types::{AppConfig, McpToolExposure, ToolContent, ToolResult}; mod stderr; +mod hot_reload; +pub(crate) use hot_reload::{HotReloadRuntime, ReloadMcpTool}; /// How long to wait for an upstream to start up and answer `tools/list` before /// giving up on it. const CONNECT_TIMEOUT: Duration = Duration::from_secs(20); -/// The result of connecting to every configured upstream: the tools to merge -/// into the registry, plus the running services kept alive for the server's -/// lifetime (dropping one closes its transport and any child process). +/// Connected MCP sources are owned by a transactional registry. Its immutable +/// view is shared across transport sessions, while calls pin their generation. pub struct Bridge { - pub tools: Vec>, - /// Shared opaque-capability store for resource links returned by upstream tools. + pub tools: Arc>>, pub resources: Arc, - /// Held only to keep upstream transports alive; never read directly. - pub services: Vec>, - /// One human-readable line per configured server (connected or failed), - /// printed in the startup banner so a bad path or handshake is never silent. pub report: Vec, - pub(crate) upstreams: Arc>>, - pub(crate) monitors: Vec, + pub(crate) runtime: Arc, + pub(crate) upstreams: + Arc>>>, } pub(crate) struct UpstreamMonitor(tokio::task::JoinHandle<()>); @@ -120,10 +117,12 @@ struct BridgedTool { tool_timeout: Option, control: Arc, resources: Arc, + generation: Arc, } impl BridgedTool { async fn run(&self, args: Value, cancellation: Option<&CancellationToken>) -> ToolResult { + let _lease = self.generation.begin_call(); let mut params = CallToolRequestParams::new(self.original_name.clone()); if let Some(obj) = args.as_object() && !obj.is_empty() @@ -518,154 +517,54 @@ fn unique_name(base: String, used: &std::collections::HashSet) -> String /// materialize its effective exposure mode. A server that fails to launch or /// answer is logged and skipped — it never blocks startup. pub async fn connect_upstreams(config: &AppConfig) -> Bridge { - let mut tools: Vec> = Vec::new(); - let mut services: Vec> = Vec::new(); - let mut upstreams = HashMap::new(); - let mut monitors = Vec::new(); - let mut report: Vec = Vec::new(); - let mut catalog_sources = Vec::new(); let resources = Arc::new(BridgedResourceStore::new(config.artifact_egress.clone())); - - // Deterministic order so logs and tool ordering are stable across runs. - let mut names: Vec<&String> = config.mcp_servers.keys().collect(); + let mut sources = HashMap::new(); + let mut report = Vec::new(); + let mut names: Vec<_> = config.mcp_servers.keys().collect(); names.sort(); - for server_name in names { - let spec = &config.mcp_servers[server_name]; + for name in names { + let spec = &config.mcp_servers[name]; if spec.disabled { - report.push(format!("{server_name} -> disabled")); + report.push(format!("{name} -> disabled")); continue; } - let sanitized = sanitize(server_name); - let exposure = spec.exposure(); - - match connect_one(server_name, spec, config).await { - Ok((service, upstream_tools, tool_timeout)) => { - let peer = service.peer().clone(); - let control = Arc::new(crate::upstream_control::UpstreamControl::new( - spec.request_limits.clone(), - )); - upstreams.insert(server_name.clone(), control.clone()); - monitors.push(monitor_upstream(peer.clone(), control.clone())); - let count = upstream_tools.len(); - - match exposure { - McpToolExposure::Gateway => { - let functions: Vec = upstream_tools - .iter() - .map(|t| GatewayFunction { - name: t.name.to_string(), - description: t - .description - .as_ref() - .map(|c| c.to_string()) - .unwrap_or_default(), - input_schema: Value::Object((*t.input_schema).clone()), - }) - .collect(); - - write_gateway_skill(config, server_name, &sanitized, &functions); - - let leaked: &'static str = Box::leak(sanitized.clone().into_boxed_str()); - tools.push(Box::new(GatewayTool { - name: leaked, - server: server_name.clone(), - description: gateway_description(server_name, &functions), - function_names: functions.iter().map(|f| f.name.clone()).collect(), - peer: peer.clone(), - tool_timeout, - control: control.clone(), - resources: resources.clone(), - })); - report.push(format!( - "{server_name} -> gateway ({count} functions via `{sanitized}`)" - )); - tracing::info!( - "bridged MCP server '{server_name}' as gateway: {count} function(s)" - ); - } - McpToolExposure::Direct => { - report.push(format!("{server_name} -> direct ({count} tool(s))")); - let mut used: std::collections::HashSet = - std::collections::HashSet::new(); - for tool in upstream_tools { - let original_name = tool.name.to_string(); - let display = - unique_name(bridged_name(&sanitized, &original_name), &used); - used.insert(display.clone()); - let leaked: &'static str = Box::leak(display.into_boxed_str()); - let title = tool.title.filter(|title| !title.trim().is_empty()); - let description = tool - .description - .map(|description| description.to_string()) - .filter(|description| !description.trim().is_empty()) - .unwrap_or_else(|| { - format!( - "Call the `{original_name}` tool on the `{server_name}` MCP server." - ) - }); - tools.push(Box::new(BridgedTool { - name: leaked, - original_name, - server: server_name.clone(), - title, - description, - input_schema: Value::Object((*tool.input_schema).clone()), - output_schema: tool - .output_schema - .map(|schema| Value::Object((*schema).clone())), - annotations: tool.annotations, - icons: tool.icons, - meta: tool.meta, - peer: peer.clone(), - tool_timeout, - control: control.clone(), - resources: resources.clone(), - })); - } - tracing::info!( - "bridged MCP server '{server_name}' directly: {count} tool(s)" - ); - } - McpToolExposure::Catalog => { - report.push(format!( - "{server_name} -> catalog ({count} private tool(s))" - )); - catalog_sources.push(CatalogSourceInput { - raw_name: server_name.clone(), - provenance: spec.provenance, - transport: transport_label(spec), - peer_info: peer.peer_info(), - tools: upstream_tools, - peer: peer.clone(), - tool_timeout, - control: control.clone(), - }); - tracing::info!( - "indexed MCP server '{server_name}' privately: {count} tool(s)" - ); - } + match connect_one(name, spec, config).await { + Ok((service, tools, timeout)) => { + let count = tools.len(); + let mode = spec.exposure(); + if mode == McpToolExposure::Gateway { + let functions = tools.iter().map(|tool| GatewayFunction { + name: tool.name.to_string(), + description: tool.description.as_ref() + .map(ToString::to_string).unwrap_or_default(), + input_schema: Value::Object((*tool.input_schema).clone()), + }).collect::>(); + write_gateway_skill(config, name, &sanitize(name), &functions); } - services.push(service); + let generation = hot_reload::Generation::new( + name.clone(), spec.clone(), service, tools, timeout, 1, + ); + sources.insert(name.clone(), generation); + report.push(format!("{name} -> {} ({count} tool(s))", mode.as_str())); + tracing::info!(source = %name, %count, exposure = mode.as_str(), "MCP source connected"); } - Err(e) => { - report.push(format!("{server_name} -> FAILED: {e}")); - tracing::warn!("skipping MCP server '{server_name}': {e}"); + Err(_) => { + // Upstream configuration can contain private header or command + // values; do not echo a failed spawn/handshake error to clients. + report.push(format!("{name} -> FAILED (initialization)")); + tracing::warn!(source = %name, "MCP source failed initialization"); } } } - let mut catalog_tools = build_catalog_tools(catalog_sources, resources.clone()); - catalog_tools.append(&mut tools); - tools = catalog_tools; - + let runtime = HotReloadRuntime::new(Arc::new(config.clone()), resources.clone(), sources); Bridge { - tools, + tools: runtime.snapshot().tools.clone(), resources, - services, report, - upstreams: Arc::new(upstreams), - monitors, + upstreams: runtime.upstreams.clone(), + runtime, } } @@ -767,10 +666,12 @@ struct GatewayTool { tool_timeout: Option, control: Arc, resources: Arc, + generation: Arc, } impl GatewayTool { async fn run(&self, args: Value, cancellation: Option<&CancellationToken>) -> ToolResult { + let _lease = self.generation.begin_call(); let Some(function) = args.get("function").and_then(|v| v.as_str()) else { return ToolResult::error("`function` is required (the name of the function to call)"); }; @@ -1133,6 +1034,7 @@ async fn connect_one_with_env( let connect = match select_transport(spec)? { UpstreamTransport::Stdio(command_path) => { let mut command = Command::new(command_path); + command.kill_on_drop(true); command.args(&spec.args); for (key, value) in &spec.env { command.env(key, value); From 6529804e3b9387ab029da039742a3ce709467982 Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:19:41 +0100 Subject: [PATCH 033/118] fix(mcp): expose generation call lease within internal catalog --- src/bridge/hot_reload.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/bridge/hot_reload.rs b/src/bridge/hot_reload.rs index 77b14cc0..92bda613 100644 --- a/src/bridge/hot_reload.rs +++ b/src/bridge/hot_reload.rs @@ -12,7 +12,7 @@ use tokio::sync::{Mutex as AsyncMutex, Notify}; const MAX_INTERNED_TOOL_NAMES: usize = 4096; const REPLACEMENT_PING_TIMEOUT: Duration = Duration::from_secs(3); -pub(super) struct Generation { +pub(crate) struct Generation { pub(super) name: String, pub(super) spec: crate::types::McpServerSpec, pub(super) peer: Peer, @@ -27,7 +27,7 @@ pub(super) struct Generation { drained: Notify, } -pub(super) struct CallLease<'a>(&'a Generation); +pub(crate) struct CallLease<'a>(&'a Generation); impl Drop for CallLease<'_> { fn drop(&mut self) { @@ -68,7 +68,7 @@ impl Generation { }) } - pub(super) fn begin_call(&self) -> CallLease<'_> { + pub(crate) fn begin_call(&self) -> CallLease<'_> { *self.calls.lock().unwrap() += 1; CallLease(self) } @@ -98,7 +98,7 @@ struct NamePool(HashMap); impl NamePool { fn intern(&mut self, name: String) -> Result<&'static str, &'static str> { if let Some(value) = self.0.get(&name) { - return Ok(value); + return Ok(*value); } if self.0.len() >= MAX_INTERNED_TOOL_NAMES { return Err("TOOL_NAME_LIMIT"); From 529c728329eef7776b2d0de596707d7443cc863e Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:19:44 +0100 Subject: [PATCH 034/118] fix(mcp): share generation type with catalog router --- src/bridge.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/bridge.rs b/src/bridge.rs index 37a32e78..546b7f1a 100644 --- a/src/bridge.rs +++ b/src/bridge.rs @@ -37,7 +37,7 @@ use crate::types::{AppConfig, McpToolExposure, ToolContent, ToolResult}; mod stderr; mod hot_reload; -pub(crate) use hot_reload::{HotReloadRuntime, ReloadMcpTool}; +pub(crate) use hot_reload::{Generation, HotReloadRuntime, ReloadMcpTool}; /// How long to wait for an upstream to start up and answer `tools/list` before /// giving up on it. From b82396bf82b4534adfe2133e8c0bd5e2e9d1142f Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:19:46 +0100 Subject: [PATCH 035/118] feat(mcp): pin catalog calls to their source generation --- src/mcp_catalog.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/mcp_catalog.rs b/src/mcp_catalog.rs index 2144716f..6a607424 100644 --- a/src/mcp_catalog.rs +++ b/src/mcp_catalog.rs @@ -40,6 +40,7 @@ pub(crate) struct CatalogSourceInput { pub peer: Peer, pub tool_timeout: Option, pub control: Arc, + pub generation: Arc, } struct CatalogTool { @@ -59,6 +60,7 @@ struct CatalogSource { peer: Peer, tool_timeout: Option, control: Arc, + generation: Arc, } struct SearchDocument { @@ -128,6 +130,7 @@ impl Catalog { peer: input.peer, tool_timeout: input.tool_timeout, control: input.control, + generation: input.generation, }); } @@ -1032,6 +1035,7 @@ impl McpCallToolTool { Err(error) => return ToolResult::error(error), }; + let _lease = source.generation.begin_call(); let mut params = CallToolRequestParams::new(tool.raw.name.to_string()); match args.get("arguments") { None | Some(Value::Null) => {} From 68beb01b7a7d206a8eefbcbefa59374542ec8824 Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:20:40 +0100 Subject: [PATCH 036/118] feat(mcp): dispatch across atomic reloadable tool snapshots --- src/server.rs | 92 +++++++++++++++++++++++++++++---------------------- 1 file changed, 52 insertions(+), 40 deletions(-) diff --git a/src/server.rs b/src/server.rs index 456491a4..47564f55 100644 --- a/src/server.rs +++ b/src/server.rs @@ -146,6 +146,7 @@ type HttpServerTask = JoinHandle>; pub struct CodexHandler { config: Arc, tools: Arc>>, + bridge_runtime: Option>, project_bindings: Arc, connector_schemas: Arc, markdown_chat: Arc, @@ -653,11 +654,20 @@ impl ServerHandler for CodexHandler { }) .await .unwrap_or_else(|_| self.config.as_ref().clone()); - let tools = self - .tools - .iter() - .map(|tool| advertised_tool(tool.as_ref(), &advertising)) - .collect(); + let mut names = std::collections::HashSet::new(); + let mut tools = Vec::new(); + for tool in self.tools.iter() { + names.insert(tool.name()); + tools.push(advertised_tool(tool.as_ref(), &advertising)); + } + if let Some(runtime) = &self.bridge_runtime { + let view = runtime.snapshot(); + for tool in view.tools.iter() { + if names.insert(tool.name()) { + tools.push(advertised_tool(tool.as_ref(), &advertising)); + } + } + } let mut result = ListToolsResult::with_all_items(tools); let caller = crate::connector_schema::caller_key(&context.meta).or_else(|| { request @@ -826,7 +836,18 @@ impl ServerHandler for CodexHandler { .arguments .map(Value::Object) .unwrap_or_else(|| json!({})); - let tool = self.tools.iter().find(|t| t.name() == name); + // Pin a complete immutable upstream registry through the entire async + // dispatch. Hot reload cannot close this request's source generation. + let bridge_view = self.bridge_runtime.as_ref().map(|runtime| runtime.snapshot()); + let tool = self + .tools + .iter() + .find(|tool| tool.name() == name) + .or_else(|| { + bridge_view.as_ref().and_then(|view| { + view.tools.iter().find(|tool| tool.name() == name) + }) + }); let ticket_wait = name == TicketWait::NAME && tool.is_some(); let model_call = !tool.is_some_and(|tool| app_only_tool(tool.as_ref())); let mut task_conversation = conversation.clone(); @@ -2062,7 +2083,8 @@ struct HealthState { tool_count: usize, ready: Arc, multi_tunnel: Option<(Arc, usize)>, - upstreams: Arc>>, + upstreams: Arc>>>, + runtime: Option>, filesystem: Option>, } @@ -2083,17 +2105,15 @@ async fn health(State(state): State) -> (StatusCode, Json) { || state.ready.load(Ordering::Acquire), |(active, _)| *active > 0, ); + let exposed = state.runtime.as_ref().map_or(0, |runtime| runtime.snapshot().tools.len()); let mut payload = json!({ "status": if is_ready { "ok" } else { "starting" }, - "tools": state.tool_count, + "tools": state.tool_count + exposed, }); - if !state.upstreams.is_empty() { + let upstreams = state.upstreams.read().unwrap(); + if !upstreams.is_empty() { payload["upstreams"] = Value::Object( - state - .upstreams - .iter() - .map(|(name, state)| (name.clone(), state.snapshot())) - .collect(), + upstreams.iter().map(|(name, state)| (name.clone(), state.snapshot())).collect(), ); } if let Some(filesystem) = &state.filesystem { @@ -2180,35 +2200,18 @@ pub async fn start_http_server(mut config: AppConfig) -> anyhow::Result<()> { let bridge = crate::bridge::connect_upstreams(&config).await; let bridge_report = bridge.report; let bridged_resources = bridge.resources; - let _bridge_services = bridge.services; - let _bridge_monitors = bridge.monitors; let upstreams = bridge.upstreams; + let bridge_runtime = bridge.runtime; let mut all_tools = validate_and_wrap_tools(load_tools_for_config(&config)) .map_err(|error| anyhow::anyhow!("invalid native tool contract: {error}"))?; - let native: std::collections::HashSet<&'static str> = - all_tools.iter().map(|t| t.name()).collect(); - let mut seen = native.clone(); - for tool in bridge.tools { - let name = tool.name(); - if seen.contains(name) { - tracing::warn!("bridged tool '{name}' collides with an existing tool; skipping"); - continue; - } - match validate_and_wrap_tool(tool) { - Ok(tool) => { - seen.insert(name); - all_tools.push(tool); - } - Err(error) => { - tracing::warn!( - "bridged tool '{name}' has an invalid contract and was skipped: {error}" - ); - } - } + let bridged_count = bridge_runtime.snapshot().tools.len(); + if !config.mcp_servers.is_empty() { + all_tools.push(validate_and_wrap_tool(Box::new(crate::bridge::ReloadMcpTool { + runtime: bridge_runtime.clone(), + })) + .map_err(|error| anyhow::anyhow!("invalid reload MCP tool contract: {error}"))?); } - let bridged_count = all_tools.len() - native.len(); - let tools = Arc::new(all_tools); if let Some(supervisor) = &agent_automation { supervisor @@ -2272,6 +2275,7 @@ pub async fn start_http_server(mut config: AppConfig) -> anyhow::Result<()> { let factory_diff_checkpoints = diff_checkpoints.clone(); let factory_artifact_egress = artifact_egress.clone(); let factory_bridged_resources = bridged_resources.clone(); + let factory_bridge_runtime = bridge_runtime.clone(); let factory_audit = audit.clone(); let factory_tool_logging = tool_logging.clone(); let factory_next_tool_call_id = next_tool_call_id.clone(); @@ -2294,6 +2298,7 @@ pub async fn start_http_server(mut config: AppConfig) -> anyhow::Result<()> { diff_checkpoints: factory_diff_checkpoints.clone(), artifact_egress: factory_artifact_egress.clone(), bridged_resources: factory_bridged_resources.clone(), + bridge_runtime: Some(factory_bridge_runtime.clone()), audit: factory_audit.clone(), tool_logging: factory_tool_logging.clone(), next_tool_call_id: factory_next_tool_call_id.clone(), @@ -2320,6 +2325,7 @@ pub async fn start_http_server(mut config: AppConfig) -> anyhow::Result<()> { .with_state(HealthState { tool_count, upstreams: upstreams.clone(), + runtime: Some(bridge_runtime.clone()), filesystem: Some(config.filesystem_worker.clone()), ready: ready.clone(), multi_tunnel: multi_availability.as_ref().map(|availability| { @@ -3292,6 +3298,7 @@ mod tests { let tools = validate_and_wrap_tools(tools).expect("test tool contracts must be valid"); CodexHandler { config: Arc::new(config), + bridge_runtime: None, tools: Arc::new(tools), connector_schemas: Arc::new(crate::connector_schema::ConnectorSchemaStore::default()), markdown_chat: Arc::new(crate::markdown_chat::MarkdownChatStore::default()), @@ -4039,6 +4046,7 @@ mod tests { let root = tempfile::tempdir().unwrap(); let mut handler = CodexHandler { config: Arc::new(crate::config::default_config(root.path().to_path_buf())), + bridge_runtime: None, tools: Arc::new(crate::registry::load_tools()), connector_schemas: Arc::new(crate::connector_schema::ConnectorSchemaStore::default()), markdown_chat: Arc::new(crate::markdown_chat::MarkdownChatStore::default()), @@ -4158,6 +4166,7 @@ mod tests { let handler = CodexHandler { config: Arc::new(config), + bridge_runtime: None, tools: Arc::new(crate::registry::load_tools()), connector_schemas: Arc::new(crate::connector_schema::ConnectorSchemaStore::default()), markdown_chat: Arc::new(crate::markdown_chat::MarkdownChatStore::default()), @@ -4202,6 +4211,7 @@ mod tests { let authorizations = Arc::new(ConversationAuthorizationStore::new()); let handler = CodexHandler { config: Arc::new(config), + bridge_runtime: None, tools: Arc::new(tools), connector_schemas: Arc::new(crate::connector_schema::ConnectorSchemaStore::default()), markdown_chat: Arc::new(crate::markdown_chat::MarkdownChatStore::default()), @@ -4808,7 +4818,8 @@ mod tests { let ready = Arc::new(AtomicBool::new(false)); let state = HealthState { tool_count: 38, - upstreams: Arc::new(HashMap::new()), + upstreams: Arc::new(std::sync::RwLock::new(HashMap::new())), + runtime: None, filesystem: None, ready: ready.clone(), multi_tunnel: None, @@ -4833,7 +4844,8 @@ mod tests { }); let state = HealthState { tool_count: 38, - upstreams: Arc::new(HashMap::new()), + upstreams: Arc::new(std::sync::RwLock::new(HashMap::new())), + runtime: None, filesystem: None, ready, multi_tunnel: Some((availability.clone(), 2)), From 405de74e09223a654153b89e078f2a955c56cdcb Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:21:00 +0100 Subject: [PATCH 037/118] fix(mcp): count reloadable bridge tools correctly in server banner --- src/server.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/server.rs b/src/server.rs index 47564f55..4e6533bf 100644 --- a/src/server.rs +++ b/src/server.rs @@ -2391,8 +2391,8 @@ pub async fn start_http_server(mut config: AppConfig) -> anyhow::Result<()> { ); } println!( - "Tools loaded ({tool_count}): {} native + {bridged_count} upstream-facing MCP tools", - tool_count - bridged_count + "Tools loaded ({}): {tool_count} native + {bridged_count} upstream-facing MCP tools", + tool_count + bridged_count ); if !bridge_report.is_empty() { println!("Upstream MCP servers:"); From bb49f57e1b2a43a3cff6e5a74f9c68129f59752e Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:23:21 +0100 Subject: [PATCH 038/118] refactor(mcp): enforce per-source reload leases and remove unused state --- src/bridge/hot_reload.rs | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/src/bridge/hot_reload.rs b/src/bridge/hot_reload.rs index 92bda613..0f97c213 100644 --- a/src/bridge/hot_reload.rs +++ b/src/bridge/hot_reload.rs @@ -13,7 +13,6 @@ const MAX_INTERNED_TOOL_NAMES: usize = 4096; const REPLACEMENT_PING_TIMEOUT: Duration = Duration::from_secs(3); pub(crate) struct Generation { - pub(super) name: String, pub(super) spec: crate::types::McpServerSpec, pub(super) peer: Peer, pub(super) tools: Vec, @@ -41,7 +40,6 @@ impl Drop for CallLease<'_> { impl Generation { pub(super) fn new( - name: String, spec: crate::types::McpServerSpec, service: RunningService, tools: Vec, @@ -54,7 +52,6 @@ impl Generation { )); let monitor = monitor_upstream(peer.clone(), control.clone()); Arc::new(Self { - name, spec, peer, tools, @@ -294,14 +291,24 @@ impl HotReloadRuntime { if name.is_empty() || name.len() > 128 || name.chars().any(char::is_control) { return Err("SOURCE_ID_INVALID"); } + let spec = self.latest_spec(name)?; + self.reload_with_spec(name, spec, cancellation).await + } + + // A test harness can supply an isolated spec without reloading real + // operator configuration. Production accepts source ID only and always + // resolves the current configured spec before reaching this boundary. + pub(super) async fn reload_with_spec( + &self, + name: &str, + spec: crate::types::McpServerSpec, + cancellation: Option<&CancellationToken>, + ) -> Result { let lock = self.locks.get(name).ok_or("SOURCE_UNKNOWN")?; let _lease = lock.try_lock().map_err(|_| "RELOAD_IN_PROGRESS")?; - let spec = self.latest_spec(name)?; self.reload_with_spec_locked(name, spec, cancellation).await } - // Injecting a spec is intentionally private to the server process. It also - // allows hermetic fault-injection tests without reading the operator config. async fn reload_with_spec_locked( &self, name: &str, @@ -367,7 +374,6 @@ impl HotReloadRuntime { .count(); } let new = Generation::new( - name.to_owned(), spec, service, tools, From 3ce2d61c598d27cd0ebb9d94ec9863e43261b8c3 Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:23:23 +0100 Subject: [PATCH 039/118] refactor(mcp): align generation construction with minimal state --- src/bridge.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/bridge.rs b/src/bridge.rs index 546b7f1a..d47c06c0 100644 --- a/src/bridge.rs +++ b/src/bridge.rs @@ -543,7 +543,7 @@ pub async fn connect_upstreams(config: &AppConfig) -> Bridge { write_gateway_skill(config, name, &sanitize(name), &functions); } let generation = hot_reload::Generation::new( - name.clone(), spec.clone(), service, tools, timeout, 1, + spec.clone(), service, tools, timeout, 1, ); sources.insert(name.clone(), generation); report.push(format!("{name} -> {} ({count} tool(s))", mode.as_str())); From 43fcde4e233cfd22388973230e06dea5673d84cc Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:24:02 +0100 Subject: [PATCH 040/118] test(mcp): exercise real upstream swapping, pinned calls, rollback and concurrency --- src/bridge/hot_reload_tests.rs | 250 +++++++++++++++++++++++++++++++++ 1 file changed, 250 insertions(+) create mode 100644 src/bridge/hot_reload_tests.rs diff --git a/src/bridge/hot_reload_tests.rs b/src/bridge/hot_reload_tests.rs new file mode 100644 index 00000000..9a80750d --- /dev/null +++ b/src/bridge/hot_reload_tests.rs @@ -0,0 +1,250 @@ +//! Isolated, real HTTP MCP fault-injection coverage for per-source reload. +use super::*; +use axum::Router; +use rmcp::{ + ErrorData as McpError, ServerHandler, + model::{ + CallToolResponse, Implementation, InitializeResult, ListToolsResult, + PaginatedRequestParams, ServerCapabilities, ServerInfo, + }, + service::{RequestContext, RoleServer}, + transport::streamable_http_server::{ + StreamableHttpServerConfig, StreamableHttpService, + session::local::LocalSessionManager, + }, +}; +use std::sync::atomic::{AtomicUsize, Ordering}; + +#[derive(Clone)] +struct Fixture { + version: &'static str, + new_tool: bool, + list_delay: Duration, + call_delay: Duration, + started: Arc, +} + +impl ServerHandler for Fixture { + fn get_info(&self) -> ServerInfo { + InitializeResult::new(ServerCapabilities::builder().enable_tools().build()) + .with_server_info(Implementation::new("hot-reload-fixture", self.version)) + } + + async fn list_tools( + &self, + _request: Option, + _context: RequestContext, + ) -> Result { + tokio::time::sleep(self.list_delay).await; + let schema = serde_json::json!({ + "type": "object", + "properties": {}, + "additionalProperties": false + }).as_object().cloned().unwrap(); + let mut tools = vec![ + rmcp::model::Tool::new("probe", "Report this fixture's version", schema.clone()), + rmcp::model::Tool::new("slow", "Report this fixture's version after a delay", schema.clone()), + ]; + if self.new_tool { + tools.push(rmcp::model::Tool::new( + "new_tool", "Added in version two", schema + )); + } + Ok(ListToolsResult::with_all_items(tools)) + } + + async fn call_tool( + &self, + request: CallToolRequestParams, + _context: RequestContext, + ) -> Result { + self.started.fetch_add(1, Ordering::SeqCst); + if request.name.as_ref() == "slow" { + tokio::time::sleep(self.call_delay).await; + } + Ok(CallToolResult::success(vec![ContentBlock::text(self.version)]).into()) + } +} + +async fn fixture( + version: &'static str, + new_tool: bool, + list_delay: Duration, + call_delay: Duration, +) -> (String, Arc, tokio::task::JoinHandle<()>) { + let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0)).await.unwrap(); + let address = listener.local_addr().unwrap(); + let calls = Arc::new(AtomicUsize::new(0)); + let fixture = Fixture { + version, + new_tool, + list_delay, + call_delay, + started: calls.clone(), + }; + let mut transport = StreamableHttpServerConfig::default(); + transport.json_response = true; + let service = StreamableHttpService::new( + move || Ok(fixture.clone()), + Arc::new(LocalSessionManager::default()), + transport, + ); + let app = Router::new().nest_service("/mcp", service); + let task = tokio::spawn(async move { + axum::serve(listener, app).await.unwrap(); + }); + (format!("http://{address}/mcp"), calls, task) +} + +fn spec(url: &str, exposure: McpToolExposure) -> crate::types::McpServerSpec { + crate::types::McpServerSpec { + url: Some(url.to_string()), + mode: Some(exposure), + ..Default::default() + } +} + +async fn invoke(view: Arc, name: &str) -> ToolResult { + let tool = view.tools.iter().find(|tool| tool.name() == name) + .unwrap_or_else(|| panic!("tool {name} missing from view")); + tool.call( + json!({}), + &crate::config::default_config(std::env::temp_dir()), + &SessionState::new(), + ).await +} + +#[tokio::test] +async fn single_source_reload_updates_tools_but_not_other_mcp() { + let (old_url, _, old_task) = + fixture("1", false, Duration::ZERO, Duration::ZERO).await; + let (new_url, _, new_task) = + fixture("2", true, Duration::ZERO, Duration::ZERO).await; + let (other_url, _, other_task) = + fixture("other", false, Duration::ZERO, Duration::ZERO).await; + let mut config = crate::config::default_config(std::env::temp_dir()); + config.mcp_servers.insert("alpha".into(), spec(&old_url, McpToolExposure::Direct)); + config.mcp_servers.insert("beta".into(), spec(&other_url, McpToolExposure::Direct)); + let bridge = connect_upstreams(&config).await; + let runtime = bridge.runtime.clone(); + let before = runtime.snapshot(); + assert_eq!(invoke(before.clone(), "alpha__probe").await.joined_text(), "1"); + assert_eq!(invoke(before.clone(), "beta__probe").await.joined_text(), "other"); + + let result = runtime.reload_with_spec( + "alpha", spec(&new_url, McpToolExposure::Direct), None + ).await.unwrap(); + assert_eq!(result["outcome"], "reloaded"); + assert_eq!(result["previousGeneration"], 1); + assert_eq!(result["replacementGeneration"], 2); + assert_eq!(result["previousVersion"], "1"); + assert_eq!(result["replacementVersion"], "2"); + assert_eq!(result["toolChanges"]["added"], 1); + assert_eq!(result["oldCallsDrained"], true); + + let after = runtime.snapshot(); + assert!(Arc::ptr_eq(&before.sources["beta"], &after.sources["beta"])); + assert!(!Arc::ptr_eq(&before.sources["alpha"], &after.sources["alpha"])); + assert_eq!(invoke(after.clone(), "alpha__probe").await.joined_text(), "2"); + assert_eq!(invoke(after.clone(), "alpha__new_tool").await.joined_text(), "2"); + assert_eq!(invoke(after, "beta__probe").await.joined_text(), "other"); + assert_eq!(invoke(before, "alpha__probe").await.joined_text(), "1"); + old_task.abort(); + new_task.abort(); + other_task.abort(); +} + +#[tokio::test] +async fn active_calls_keep_their_original_generation_without_replay() { + let (old_url, old_count, old_task) = + fixture("1", false, Duration::ZERO, Duration::from_millis(450)).await; + let (new_url, new_count, new_task) = + fixture("2", true, Duration::ZERO, Duration::ZERO).await; + let mut config = crate::config::default_config(std::env::temp_dir()); + config.mcp_servers.insert("alpha".into(), spec(&old_url, McpToolExposure::Direct)); + let runtime = connect_upstreams(&config).await.runtime; + let initial = runtime.snapshot(); + let pending = tokio::spawn(invoke(initial, "alpha__slow")); + tokio::time::timeout(Duration::from_secs(2), async { + while old_count.load(Ordering::SeqCst) == 0 { + tokio::time::sleep(Duration::from_millis(5)).await; + } + }).await.unwrap(); + let started = std::time::Instant::now(); + let result = runtime.reload_with_spec( + "alpha", spec(&new_url, McpToolExposure::Direct), None + ).await.unwrap(); + assert_eq!(result["oldCallsDrained"], true); + assert!(started.elapsed() >= Duration::from_millis(100)); + assert_eq!(pending.await.unwrap().joined_text(), "1"); + assert_eq!(old_count.load(Ordering::SeqCst), 1); + assert_eq!(invoke(runtime.snapshot(), "alpha__probe").await.joined_text(), "2"); + assert_eq!(new_count.load(Ordering::SeqCst), 1); + old_task.abort(); + new_task.abort(); +} + +#[tokio::test] +async fn failed_replacement_and_unknown_ids_cannot_mutate_active_generation() { + let (old_url, _, old_task) = + fixture("1", false, Duration::ZERO, Duration::ZERO).await; + let mut config = crate::config::default_config(std::env::temp_dir()); + config.mcp_servers.insert("alpha".into(), spec(&old_url, McpToolExposure::Direct)); + let runtime = connect_upstreams(&config).await.runtime; + let old = runtime.snapshot(); + + assert_eq!( + runtime.reload_with_spec( + "missing", spec("http://127.0.0.1:9/mcp", McpToolExposure::Direct), None + ).await.unwrap_err(), + "SOURCE_UNKNOWN" + ); + assert_eq!( + runtime.reload_with_spec( + "alpha", spec("http://127.0.0.1:9/mcp", McpToolExposure::Direct), None + ).await.unwrap_err(), + "INITIALIZE_FAILED" + ); + let after = runtime.snapshot(); + assert!(Arc::ptr_eq(&old, &after)); + assert_eq!(invoke(after, "alpha__probe").await.joined_text(), "1"); + old_task.abort(); +} + +#[tokio::test] +async fn same_source_reload_conflicts_while_other_source_can_reload() { + let (a1, _, first_task) = + fixture("1", false, Duration::ZERO, Duration::ZERO).await; + let (a2, _, second_task) = + fixture("2", true, Duration::from_millis(300), Duration::ZERO).await; + let (b1, _, third_task) = + fixture("other1", false, Duration::ZERO, Duration::ZERO).await; + let (b2, _, fourth_task) = + fixture("other2", false, Duration::ZERO, Duration::ZERO).await; + let mut config = crate::config::default_config(std::env::temp_dir()); + config.mcp_servers.insert("alpha".into(), spec(&a1, McpToolExposure::Direct)); + config.mcp_servers.insert("beta".into(), spec(&b1, McpToolExposure::Direct)); + let runtime = connect_upstreams(&config).await.runtime; + let clone = runtime.clone(); + let initial = tokio::spawn(async move { + clone.reload_with_spec("alpha", spec(&a2, McpToolExposure::Direct), None).await + }); + tokio::time::sleep(Duration::from_millis(50)).await; + assert_eq!( + runtime.reload_with_spec("alpha", spec(&a1, McpToolExposure::Direct), None) + .await.unwrap_err(), + "RELOAD_IN_PROGRESS" + ); + let other = runtime.reload_with_spec( + "beta", spec(&b2, McpToolExposure::Direct), None + ).await.unwrap(); + assert_eq!(other["replacementGeneration"], 2); + assert_eq!(initial.await.unwrap().unwrap()["replacementGeneration"], 2); + let view = runtime.snapshot(); + assert_eq!(invoke(view.clone(), "alpha__probe").await.joined_text(), "2"); + assert_eq!(invoke(view, "beta__probe").await.joined_text(), "other2"); + first_task.abort(); + second_task.abort(); + third_task.abort(); + fourth_task.abort(); +} From 93ee0f861c40504f5e023ecc2661949fecbce5ca Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:24:05 +0100 Subject: [PATCH 041/118] test(mcp): enable isolated reload integration fixtures --- src/bridge.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/bridge.rs b/src/bridge.rs index d47c06c0..7145e8a2 100644 --- a/src/bridge.rs +++ b/src/bridge.rs @@ -37,6 +37,8 @@ use crate::types::{AppConfig, McpToolExposure, ToolContent, ToolResult}; mod stderr; mod hot_reload; +#[cfg(test)] +mod hot_reload_tests; pub(crate) use hot_reload::{Generation, HotReloadRuntime, ReloadMcpTool}; /// How long to wait for an upstream to start up and answer `tools/list` before From 755cb026ca4a893f0ad9752afa491f006cf9c4ca Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:24:35 +0100 Subject: [PATCH 042/118] fix(mcp): make reload initialization future Send and update legacy assertions --- src/bridge.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/bridge.rs b/src/bridge.rs index 7145e8a2..96de8ff7 100644 --- a/src/bridge.rs +++ b/src/bridge.rs @@ -1015,7 +1015,7 @@ async fn connect_one_with_env( server_name: &str, spec: &crate::types::McpServerSpec, config: &AppConfig, - env_lookup: &dyn Fn(&str) -> Option, + env_lookup: &(dyn Fn(&str) -> Option + Sync), ) -> Result< ( RunningService, @@ -2756,7 +2756,7 @@ mod tests { bridge.tools.is_empty(), "a failing upstream must be skipped, not fatal" ); - assert!(bridge.services.is_empty()); + assert!(bridge.runtime.snapshot().sources.is_empty()); // The failure is surfaced in the report, not swallowed. assert!(bridge.report.iter().any(|l| l.contains("bad -> FAILED"))); } From 1034a6ce42779413486582535d4928bc73cb8892 Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:25:11 +0100 Subject: [PATCH 043/118] docs(mcp): document transactional reload behavior, limits and gated dogfooding --- docs/MCP_HOT_RELOAD.md | 106 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 106 insertions(+) create mode 100644 docs/MCP_HOT_RELOAD.md diff --git a/docs/MCP_HOT_RELOAD.md b/docs/MCP_HOT_RELOAD.md new file mode 100644 index 00000000..0c0203bf --- /dev/null +++ b/docs/MCP_HOT_RELOAD.md @@ -0,0 +1,106 @@ +# Per-source MCP hot reload (operator guide) + +**Status:** experimental, opt-in through a staged build. This document describes +source behavior, not a deployed feature. Do not replace an active Codexify +service without separate approval and validation. + +## Scope + +\`reload_mcp\` reloads exactly one existing upstream source, identified by the +key in the resolved \`mcpServers\` configuration. A caller provides +\`{"source":"god_prompt_mcp"}\`; it cannot provide a command, executable, +working directory, URL, environment variables, or credentials. + +The server rereads its operator configuration (including inherited Codex MCP +sources) **read-only** using its startup CLI selection. A target that was +removed or disabled fails closed. No global service restart, tunnel reconnect, +task replacement, or unrelated source reconnection is part of this operation. + +The replacement uses the existing MCP transport implementation for **stdio** +and **Streamable HTTP**. Unsupported legacy SSE and WebSocket sources remain +unsupported; the operation never silently falls back to a process-wide restart. + +## Lifecycle and safety + +1. The scoped reload lock rejects concurrent attempts for the same source + (\`RELOAD_IN_PROGRESS\`); unrelated source reloads can progress concurrently. +2. The updated source specification is validated, started, initialized, and + queried with \`tools/list\`. A bounded MCP ping must also receive a + successful response or a protocol-level MCP error indicating a live peer. +3. The new tool definitions are validated and an immutable registry view is + constructed. The new view replaces the old view in one atomic pointer swap. + Concurrent distinct-source reloads rebuild against the latest view. +4. Calls already using an old registry snapshot stay pinned to that snapshot + and connection generation; write-capable calls are **never replayed**. + Cancellation and timeout semantics remain those of the forwarded request. +5. The old generation is released when no surviving snapshot or call retains + it. The operation reports whether active calls drained within the source's + configured \`requestLimits.slowCancellationMs\` interval. A drain timeout + does **not** kill or replay an in-progress side-effecting call. +6. On failure **before** the swap, the new candidate is dropped and the old + view is never replaced. Errors use bounded diagnostic codes and do not + echo credentials, command lines, headers, environment variables, or raw + tool-response bodies. + +For stdio, the spawned Tokio child has \`kill_on_drop\` enabled, so aborted +initializations should not leave the candidate running. A platform-specific +Windows child-lifecycle integration and repeated process-tree soak remain +required acceptance gates before production activation. + +## Result and tool discovery + +A successful result includes \`source\`, \`outcome\`, +\`previousGeneration\`, \`replacementGeneration\`, old/new reported MCP +server versions, readiness, counts of added/removed/changed/unchanged +tool definitions, \`oldCallsDrained\`, \`oldGenerationRetiring\`, +\`rollback\`, and \`diagnosticCode\`. + +The source's discovery data and forwarded-call routes change together in the +server's tool registry. Existing transport sessions can observe changed +definitions on **another \`tools/list\`** request. **An already-open ChatGPT +chat is not guaranteed to receive new tool definitions automatically.** +Its connector may need Refresh, reconnection or a new conversation before +new direct tools appear. The result explicitly sets +\`clientRediscoveryRequired: true\`. + +Catalog-mode source and tool identifiers remain generated by the existing +catalog and may change when a source's tool set changes. Re-query +\`mcp_list_sources\`, \`mcp_search_tools\`, and \`mcp_get_tool\` before calling +a new or modified tool. Gateway clients must refresh their advertised schema +and generated skill after reload. + +## Failure and boundary conditions + +- \`SOURCE_UNKNOWN\` / \`SOURCE_REMOVED\` / \`SOURCE_DISABLED\`: do not spawn + an arbitrary process or reinterpret the input as a path. +- \`RELOAD_IN_PROGRESS\`: no duplicate replacement of the same source. +- \`CONFIG_INVALID\`, \`CONFIG_CLI_INVALID\`, \`INITIALIZE_FAILED\`, + \`READINESS_FAILED\`: old healthy generation is retained. +- \`TOOL_NAME_LIMIT\`: bound on unique registered direct/gateway tool names; + the attempted registry swap is discarded. +- \`CANCELLED\`: an aborted preparation does not switch generations. +- If the old generation became unhealthy independently, a successful new + connection is preferred; the operation does not imply that the old peer can + be resurrected. +- Invalid data from upstream tool descriptions must remain untrusted. + Reload permission uses existing Codexify connector authorization and audit + boundaries. Do not expose the control plane to unauthenticated clients. + +## Verification gate + +The following must pass on the **exact candidate commit** before any +deployment: Rust formatting and compilation, strict lint, full Rust suite, +downstream HTTP MCP handshake, selected-source version and tool-diff checks, +two independent unrelated MCP sources, read/write in-flight calls, duplicate +reload and failure injection, cleanup/leak soak, and Windows native-process +termination. Reproduce an isolated old-to-new GodPrompt candidate switch +without touching the running GodPrompt instance; verify new version and +rollback. Measure switchover, drain and end-to-end request latency using a +repeatable workload. Do not report "zero downtime" without observed proof. + +**Not included:** automatic filesystem watching. It remains disabled rather +than introducing unverified debouncing and partially written config races. + +This feature does not merge the separate Windows scheduled-supervisor orphan +cleanup branch. Keep that work independent and verify its eventual integration +before any production cutover. From 09dcce8bf5c4d41a87b4e681bb51291f68a728e3 Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:26:04 +0100 Subject: [PATCH 044/118] test(mcp): expose immutable source snapshot to integration assertions --- src/bridge/hot_reload.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/bridge/hot_reload.rs b/src/bridge/hot_reload.rs index 0f97c213..91bda8b6 100644 --- a/src/bridge/hot_reload.rs +++ b/src/bridge/hot_reload.rs @@ -108,7 +108,7 @@ impl NamePool { pub(crate) struct BridgeView { pub(crate) tools: Arc>>, - sources: HashMap>, + pub(crate) sources: HashMap>, } pub(crate) struct HotReloadRuntime { From 62f12eb4d9670cf4de28c127a91fa0b038713648 Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:27:37 +0100 Subject: [PATCH 045/118] fix(mcp): keep direct and catalog tool registry unique across sources --- src/bridge/hot_reload.rs | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/src/bridge/hot_reload.rs b/src/bridge/hot_reload.rs index 91bda8b6..b30cc508 100644 --- a/src/bridge/hot_reload.rs +++ b/src/bridge/hot_reload.rs @@ -252,13 +252,23 @@ impl HotReloadRuntime { } let mut tools = build_catalog_tools(catalog, self.resources.clone()); tools.append(&mut exposed); + let mut seen = HashSet::new(); let tools = tools .into_iter() - .filter_map(|tool| match crate::tool::validate_and_wrap_tool(tool) { - Ok(tool) => Some(tool), - Err(error) => { - tracing::warn!(%error, "invalid upstream MCP tool skipped"); - None + .filter_map(|tool| { + if !seen.insert(tool.name()) { + tracing::warn!( + name = tool.name(), + "duplicate upstream MCP tool name skipped" + ); + return None; + } + match crate::tool::validate_and_wrap_tool(tool) { + Ok(tool) => Some(tool), + Err(error) => { + tracing::warn!(%error, "invalid upstream MCP tool skipped"); + None + } } }) .collect(); From c3fdffc728caf155d63fa1ba80785fa71ef8bd7c Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:28:30 +0100 Subject: [PATCH 046/118] test(mcp): cover catalog/gateway rediscovery, reconnect, cancellation, repeated reload and collisions --- src/bridge/hot_reload_tests.rs | 145 ++++++++++++++++++++++++++++++++- 1 file changed, 144 insertions(+), 1 deletion(-) diff --git a/src/bridge/hot_reload_tests.rs b/src/bridge/hot_reload_tests.rs index 9a80750d..78b1b59a 100644 --- a/src/bridge/hot_reload_tests.rs +++ b/src/bridge/hot_reload_tests.rs @@ -105,10 +105,18 @@ fn spec(url: &str, exposure: McpToolExposure) -> crate::types::McpServerSpec { } async fn invoke(view: Arc, name: &str) -> ToolResult { + invoke_args(view, name, json!({})).await +} + +async fn invoke_args( + view: Arc, + name: &str, + args: Value, +) -> ToolResult { let tool = view.tools.iter().find(|tool| tool.name() == name) .unwrap_or_else(|| panic!("tool {name} missing from view")); tool.call( - json!({}), + args, &crate::config::default_config(std::env::temp_dir()), &SessionState::new(), ).await @@ -248,3 +256,138 @@ async fn same_source_reload_conflicts_while_other_source_can_reload() { third_task.abort(); fourth_task.abort(); } + +#[tokio::test] +async fn catalog_reload_refreshes_search_schema_and_call_routing() { + let (old_url, _, old_task) = + fixture("1", false, Duration::ZERO, Duration::ZERO).await; + let (new_url, _, new_task) = + fixture("2", true, Duration::ZERO, Duration::ZERO).await; + let mut config = crate::config::default_config(std::env::temp_dir()); + config.mcp_servers.insert("catalog".into(), spec(&old_url, McpToolExposure::Catalog)); + let runtime = connect_upstreams(&config).await.runtime; + let before = runtime.snapshot(); + let source = invoke(before, "mcp_list_sources").await.structured_content.unwrap(); + assert_eq!(source["sources"][0]["toolCount"], 2); + let result = runtime.reload_with_spec( + "catalog", spec(&new_url, McpToolExposure::Catalog), None + ).await.unwrap(); + assert_eq!(result["toolChanges"]["added"], 1); + let after = runtime.snapshot(); + let list = invoke(after.clone(), "mcp_list_sources").await.structured_content.unwrap(); + assert_eq!(list["sources"][0]["toolCount"], 3); + let source_id = list["sources"][0]["id"].as_str().unwrap(); + let found = invoke_args( + after.clone(), "mcp_search_tools", json!({"query":"new_tool","source":source_id}) + ).await.structured_content.unwrap(); + assert!(found["total"].as_u64().unwrap_or(0) >= 1); + let tool_id = found["matches"][0]["toolId"].as_str().unwrap(); + let call = invoke_args( + after, "mcp_call_tool", + json!({"source":source_id,"tool":tool_id,"arguments":{}}) + ).await; + assert!(!call.is_error); + assert_eq!(call.joined_text(), "2"); + old_task.abort(); + new_task.abort(); +} + +#[tokio::test] +async fn gateway_reload_reflects_added_functions() { + let (old_url, _, old_task) = + fixture("1", false, Duration::ZERO, Duration::ZERO).await; + let (new_url, _, new_task) = + fixture("2", true, Duration::ZERO, Duration::ZERO).await; + let mut config = crate::config::default_config(std::env::temp_dir()); + config.mcp_servers.insert("gateway".into(), spec(&old_url, McpToolExposure::Gateway)); + let runtime = connect_upstreams(&config).await.runtime; + let before = runtime.snapshot(); + let old = invoke_args( + before, "gateway", json!({"function":"probe","arguments":{}}) + ).await; + assert_eq!(old.joined_text(), "1"); + runtime.reload_with_spec( + "gateway", spec(&new_url, McpToolExposure::Gateway), None + ).await.unwrap(); + let after = runtime.snapshot(); + let tool = after.tools.iter().find(|tool| tool.name() == "gateway").unwrap(); + assert!( + tool.input_schema()["properties"]["function"]["enum"] + .as_array().unwrap().contains(&json!("new_tool")) + ); + let new = invoke_args( + after, "gateway", json!({"function":"new_tool","arguments":{}}) + ).await; + assert_eq!(new.joined_text(), "2"); + old_task.abort(); + new_task.abort(); +} + +#[tokio::test] +async fn reconnect_failed_initial_source_and_cancel_without_switching() { + let (url, _, task) = fixture("recovered", false, Duration::ZERO, Duration::ZERO).await; + let mut config = crate::config::default_config(std::env::temp_dir()); + config.mcp_servers.insert( + "unavailable".into(), crate::types::McpServerSpec { + url: Some("http://127.0.0.1:9/mcp".into()), + startup_timeout_sec: Some(0.5), + ..Default::default() + } + ); + let runtime = connect_upstreams(&config).await.runtime; + assert!(!runtime.snapshot().sources.contains_key("unavailable")); + let result = runtime.reload_with_spec( + "unavailable", spec(&url, McpToolExposure::Direct), None + ).await.unwrap(); + assert_eq!(result["previousGeneration"], 0); + assert_eq!(result["replacementGeneration"], 1); + assert_eq!(invoke(runtime.snapshot(), "unavailable__probe").await.joined_text(), "recovered"); + + let old = runtime.snapshot(); + let cancelled = CancellationToken::new(); + cancelled.cancel(); + assert_eq!( + runtime.reload_with_spec( + "unavailable", spec(&url, McpToolExposure::Direct), Some(&cancelled) + ).await.unwrap_err(), "CANCELLED" + ); + assert!(Arc::ptr_eq(&old, &runtime.snapshot())); + task.abort(); +} + +#[tokio::test] +async fn repeated_reloads_keep_one_active_generation_per_source() { + let (url, _, task) = fixture("stable", false, Duration::ZERO, Duration::ZERO).await; + let mut config = crate::config::default_config(std::env::temp_dir()); + config.mcp_servers.insert("alpha".into(), spec(&url, McpToolExposure::Direct)); + let runtime = connect_upstreams(&config).await.runtime; + for expected in 2..=6 { + let result = runtime.reload_with_spec( + "alpha", spec(&url, McpToolExposure::Direct), None + ).await.unwrap(); + assert_eq!(result["replacementGeneration"], expected); + assert_eq!(result["oldCallsDrained"], true); + let view = runtime.snapshot(); + assert_eq!(view.sources.len(), 1); + assert_eq!(invoke(view, "alpha__probe").await.joined_text(), "stable"); + } + task.abort(); +} + +#[tokio::test] +async fn direct_name_collisions_are_not_ambiguous_after_reload() { + let (url1, _, task1) = fixture("one", false, Duration::ZERO, Duration::ZERO).await; + let (url2, _, task2) = fixture("two", true, Duration::ZERO, Duration::ZERO).await; + let mut config = crate::config::default_config(std::env::temp_dir()); + // sanitize("dup!")==sanitize("dup?"), so both would generate dup___probe. + config.mcp_servers.insert("dup!".into(), spec(&url1, McpToolExposure::Direct)); + config.mcp_servers.insert("dup?".into(), spec(&url2, McpToolExposure::Direct)); + let runtime = connect_upstreams(&config).await.runtime; + let view = runtime.snapshot(); + let names = view.tools.iter().map(|tool| tool.name()).collect::>(); + let unique = names.iter().copied().collect::>(); + assert_eq!(unique.len(), names.len()); + assert_eq!(names.iter().filter(|name| **name == "dup___probe").count(), 1); + task1.abort(); + task2.abort(); +} From 138abc1536649246a9ec89af29c9160858ca64ce Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:29:30 +0100 Subject: [PATCH 047/118] style(mcp): apply rustfmt fixes confirmed by CI (src/bridge/hot_reload.rs) --- src/bridge/hot_reload.rs | 55 +++++++++++++++++++++++++++++----------- 1 file changed, 40 insertions(+), 15 deletions(-) diff --git a/src/bridge/hot_reload.rs b/src/bridge/hot_reload.rs index b30cc508..01518355 100644 --- a/src/bridge/hot_reload.rs +++ b/src/bridge/hot_reload.rs @@ -84,9 +84,11 @@ impl Generation { } fn version(&self) -> Option { - self.peer - .peer_info() - .and_then(|info| info.server_info.as_ref().map(|info| info.version.to_string())) + self.peer.peer_info().and_then(|info| { + info.server_info + .as_ref() + .map(|info| info.version.to_string()) + }) } } @@ -202,8 +204,7 @@ impl HotReloadRuntime { let mut used = HashSet::new(); for tool in &source.tools { let raw_name = tool.name.to_string(); - let display = - unique_name(bridged_name(&sanitized, &raw_name), &used); + let display = unique_name(bridged_name(&sanitized, &raw_name), &used); used.insert(display.clone()); let description = tool .description @@ -284,8 +285,8 @@ impl HotReloadRuntime { // request: only the operator's configured source ID is accepted. let cli = crate::config::Cli::try_parse_from(std::env::args_os()) .map_err(|_| "CONFIG_CLI_INVALID")?; - let config = crate::config::load_config_quiet_read_only(cli) - .map_err(|_| "CONFIG_INVALID")?; + let config = + crate::config::load_config_quiet_read_only(cli).map_err(|_| "CONFIG_INVALID")?; config .mcp_servers .get(name) @@ -366,14 +367,30 @@ impl HotReloadRuntime { .map(|generation| &generation.tools) .into_iter() .flatten() - .map(|tool| (tool.name.as_ref(), serde_json::to_value(tool).unwrap_or(Value::Null))) + .map(|tool| { + ( + tool.name.as_ref(), + serde_json::to_value(tool).unwrap_or(Value::Null), + ) + }) .collect(); let after: HashMap<_, _> = tools .iter() - .map(|tool| (tool.name.as_ref(), serde_json::to_value(tool).unwrap_or(Value::Null))) + .map(|tool| { + ( + tool.name.as_ref(), + serde_json::to_value(tool).unwrap_or(Value::Null), + ) + }) .collect(); - added = after.keys().filter(|key| !before.contains_key(**key)).count(); - removed = before.keys().filter(|key| !after.contains_key(**key)).count(); + added = after + .keys() + .filter(|key| !before.contains_key(**key)) + .count(); + removed = before + .keys() + .filter(|key| !after.contains_key(**key)) + .count(); changed = after .iter() .filter(|(key, value)| before.get(**key).is_some_and(|old| old != *value)) @@ -417,7 +434,11 @@ impl HotReloadRuntime { .iter() .map(|t| GatewayFunction { name: t.name.to_string(), - description: t.description.as_ref().map(ToString::to_string).unwrap_or_default(), + description: t + .description + .as_ref() + .map(ToString::to_string) + .unwrap_or_default(), input_schema: Value::Object((*t.input_schema).clone()), }) .collect::>(); @@ -520,9 +541,13 @@ impl ReloadMcpTool { return ToolResult::error("SOURCE_ID_INVALID"); }; match self.runtime.reload(source, cancellation).await { - Ok(report) => ToolResult::text("MCP source reloaded; rediscover tools to refresh client schemas.") - .with_structured(report), - Err(code) => ToolResult::error(format!("MCP reload did not switch connections: {code}")), + Ok(report) => { + ToolResult::text("MCP source reloaded; rediscover tools to refresh client schemas.") + .with_structured(report) + } + Err(code) => { + ToolResult::error(format!("MCP reload did not switch connections: {code}")) + } } } } From cc4dcd4156dd76079874b30539d66fe345e92603 Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:29:32 +0100 Subject: [PATCH 048/118] style(mcp): apply rustfmt fixes confirmed by CI (src/bridge.rs) --- src/bridge.rs | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/src/bridge.rs b/src/bridge.rs index 96de8ff7..1d1d111a 100644 --- a/src/bridge.rs +++ b/src/bridge.rs @@ -536,12 +536,18 @@ pub async fn connect_upstreams(config: &AppConfig) -> Bridge { let count = tools.len(); let mode = spec.exposure(); if mode == McpToolExposure::Gateway { - let functions = tools.iter().map(|tool| GatewayFunction { - name: tool.name.to_string(), - description: tool.description.as_ref() - .map(ToString::to_string).unwrap_or_default(), - input_schema: Value::Object((*tool.input_schema).clone()), - }).collect::>(); + let functions = tools + .iter() + .map(|tool| GatewayFunction { + name: tool.name.to_string(), + description: tool + .description + .as_ref() + .map(ToString::to_string) + .unwrap_or_default(), + input_schema: Value::Object((*tool.input_schema).clone()), + }) + .collect::>(); write_gateway_skill(config, name, &sanitize(name), &functions); } let generation = hot_reload::Generation::new( From 8f0ee099e238d4a826bd469808cea5b206a6b679 Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:29:35 +0100 Subject: [PATCH 049/118] style(mcp): apply rustfmt fixes confirmed by CI (src/server.rs) --- src/server.rs | 34 +++++++++++++++++++++++----------- 1 file changed, 23 insertions(+), 11 deletions(-) diff --git a/src/server.rs b/src/server.rs index 4e6533bf..164f696b 100644 --- a/src/server.rs +++ b/src/server.rs @@ -838,15 +838,18 @@ impl ServerHandler for CodexHandler { .unwrap_or_else(|| json!({})); // Pin a complete immutable upstream registry through the entire async // dispatch. Hot reload cannot close this request's source generation. - let bridge_view = self.bridge_runtime.as_ref().map(|runtime| runtime.snapshot()); + let bridge_view = self + .bridge_runtime + .as_ref() + .map(|runtime| runtime.snapshot()); let tool = self .tools .iter() .find(|tool| tool.name() == name) .or_else(|| { - bridge_view.as_ref().and_then(|view| { - view.tools.iter().find(|tool| tool.name() == name) - }) + bridge_view + .as_ref() + .and_then(|view| view.tools.iter().find(|tool| tool.name() == name)) }); let ticket_wait = name == TicketWait::NAME && tool.is_some(); let model_call = !tool.is_some_and(|tool| app_only_tool(tool.as_ref())); @@ -2083,7 +2086,8 @@ struct HealthState { tool_count: usize, ready: Arc, multi_tunnel: Option<(Arc, usize)>, - upstreams: Arc>>>, + upstreams: + Arc>>>, runtime: Option>, filesystem: Option>, } @@ -2105,7 +2109,10 @@ async fn health(State(state): State) -> (StatusCode, Json) { || state.ready.load(Ordering::Acquire), |(active, _)| *active > 0, ); - let exposed = state.runtime.as_ref().map_or(0, |runtime| runtime.snapshot().tools.len()); + let exposed = state + .runtime + .as_ref() + .map_or(0, |runtime| runtime.snapshot().tools.len()); let mut payload = json!({ "status": if is_ready { "ok" } else { "starting" }, "tools": state.tool_count + exposed, @@ -2113,7 +2120,10 @@ async fn health(State(state): State) -> (StatusCode, Json) { let upstreams = state.upstreams.read().unwrap(); if !upstreams.is_empty() { payload["upstreams"] = Value::Object( - upstreams.iter().map(|(name, state)| (name.clone(), state.snapshot())).collect(), + upstreams + .iter() + .map(|(name, state)| (name.clone(), state.snapshot())) + .collect(), ); } if let Some(filesystem) = &state.filesystem { @@ -2207,10 +2217,12 @@ pub async fn start_http_server(mut config: AppConfig) -> anyhow::Result<()> { .map_err(|error| anyhow::anyhow!("invalid native tool contract: {error}"))?; let bridged_count = bridge_runtime.snapshot().tools.len(); if !config.mcp_servers.is_empty() { - all_tools.push(validate_and_wrap_tool(Box::new(crate::bridge::ReloadMcpTool { - runtime: bridge_runtime.clone(), - })) - .map_err(|error| anyhow::anyhow!("invalid reload MCP tool contract: {error}"))?); + all_tools.push( + validate_and_wrap_tool(Box::new(crate::bridge::ReloadMcpTool { + runtime: bridge_runtime.clone(), + })) + .map_err(|error| anyhow::anyhow!("invalid reload MCP tool contract: {error}"))?, + ); } let tools = Arc::new(all_tools); if let Some(supervisor) = &agent_automation { From 9c48bc8db3d6d2a2d1e3318ff84072a5c83960fb Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:30:42 +0100 Subject: [PATCH 050/118] fix(mcp): return structured failure and retained-generation diagnostics --- src/bridge/hot_reload.rs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/src/bridge/hot_reload.rs b/src/bridge/hot_reload.rs index 01518355..2cfa4d5c 100644 --- a/src/bridge/hot_reload.rs +++ b/src/bridge/hot_reload.rs @@ -302,6 +302,9 @@ impl HotReloadRuntime { if name.is_empty() || name.len() > 128 || name.chars().any(char::is_control) { return Err("SOURCE_ID_INVALID"); } + if !self.locks.contains_key(name) { + return Err("SOURCE_UNKNOWN"); + } let spec = self.latest_spec(name)?; self.reload_with_spec(name, spec, cancellation).await } @@ -546,7 +549,18 @@ impl ReloadMcpTool { .with_structured(report) } Err(code) => { + let old = self.runtime.snapshot().sources.get(source).cloned(); + let report = json!({ + "source": source, + "outcome": "failed_without_switch", + "previousGeneration": old.as_ref().map(|generation| generation.number), + "previousVersion": old.as_ref().and_then(|generation| generation.version()), + "rollback": "previous_registry_retained", + "clientRediscoveryRequired": false, + "diagnosticCode": code + }); ToolResult::error(format!("MCP reload did not switch connections: {code}")) + .with_structured(report) } } } From cfbc29526a3ceb5864e255b9c4c159d8670d8400 Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:30:50 +0100 Subject: [PATCH 051/118] docs(mcp): correct operator guide Markdown code spans --- docs/MCP_HOT_RELOAD.md | 40 ++++++++++++++++++++-------------------- 1 file changed, 20 insertions(+), 20 deletions(-) diff --git a/docs/MCP_HOT_RELOAD.md b/docs/MCP_HOT_RELOAD.md index 0c0203bf..952001d1 100644 --- a/docs/MCP_HOT_RELOAD.md +++ b/docs/MCP_HOT_RELOAD.md @@ -6,9 +6,9 @@ service without separate approval and validation. ## Scope -\`reload_mcp\` reloads exactly one existing upstream source, identified by the -key in the resolved \`mcpServers\` configuration. A caller provides -\`{"source":"god_prompt_mcp"}\`; it cannot provide a command, executable, +`reload_mcp` reloads exactly one existing upstream source, identified by the +key in the resolved `mcpServers` configuration. A caller provides +`{"source":"god_prompt_mcp"}`; it cannot provide a command, executable, working directory, URL, environment variables, or credentials. The server rereads its operator configuration (including inherited Codex MCP @@ -23,9 +23,9 @@ unsupported; the operation never silently falls back to a process-wide restart. ## Lifecycle and safety 1. The scoped reload lock rejects concurrent attempts for the same source - (\`RELOAD_IN_PROGRESS\`); unrelated source reloads can progress concurrently. + (`RELOAD_IN_PROGRESS`); unrelated source reloads can progress concurrently. 2. The updated source specification is validated, started, initialized, and - queried with \`tools/list\`. A bounded MCP ping must also receive a + queried with `tools/list`. A bounded MCP ping must also receive a successful response or a protocol-level MCP error indicating a live peer. 3. The new tool definitions are validated and an immutable registry view is constructed. The new view replaces the old view in one atomic pointer swap. @@ -35,50 +35,50 @@ unsupported; the operation never silently falls back to a process-wide restart. Cancellation and timeout semantics remain those of the forwarded request. 5. The old generation is released when no surviving snapshot or call retains it. The operation reports whether active calls drained within the source's - configured \`requestLimits.slowCancellationMs\` interval. A drain timeout + configured `requestLimits.slowCancellationMs` interval. A drain timeout does **not** kill or replay an in-progress side-effecting call. 6. On failure **before** the swap, the new candidate is dropped and the old view is never replaced. Errors use bounded diagnostic codes and do not echo credentials, command lines, headers, environment variables, or raw tool-response bodies. -For stdio, the spawned Tokio child has \`kill_on_drop\` enabled, so aborted +For stdio, the spawned Tokio child has `kill_on_drop` enabled, so aborted initializations should not leave the candidate running. A platform-specific Windows child-lifecycle integration and repeated process-tree soak remain required acceptance gates before production activation. ## Result and tool discovery -A successful result includes \`source\`, \`outcome\`, -\`previousGeneration\`, \`replacementGeneration\`, old/new reported MCP +A successful result includes `source`, `outcome`, +`previousGeneration`, `replacementGeneration`, old/new reported MCP server versions, readiness, counts of added/removed/changed/unchanged -tool definitions, \`oldCallsDrained\`, \`oldGenerationRetiring\`, -\`rollback\`, and \`diagnosticCode\`. +tool definitions, `oldCallsDrained`, `oldGenerationRetiring`, +`rollback`, and `diagnosticCode`. The source's discovery data and forwarded-call routes change together in the server's tool registry. Existing transport sessions can observe changed -definitions on **another \`tools/list\`** request. **An already-open ChatGPT +definitions on **another `tools/list`** request. **An already-open ChatGPT chat is not guaranteed to receive new tool definitions automatically.** Its connector may need Refresh, reconnection or a new conversation before new direct tools appear. The result explicitly sets -\`clientRediscoveryRequired: true\`. +`clientRediscoveryRequired: true`. Catalog-mode source and tool identifiers remain generated by the existing catalog and may change when a source's tool set changes. Re-query -\`mcp_list_sources\`, \`mcp_search_tools\`, and \`mcp_get_tool\` before calling +`mcp_list_sources`, `mcp_search_tools`, and `mcp_get_tool` before calling a new or modified tool. Gateway clients must refresh their advertised schema and generated skill after reload. ## Failure and boundary conditions -- \`SOURCE_UNKNOWN\` / \`SOURCE_REMOVED\` / \`SOURCE_DISABLED\`: do not spawn +- `SOURCE_UNKNOWN` / `SOURCE_REMOVED` / `SOURCE_DISABLED`: do not spawn an arbitrary process or reinterpret the input as a path. -- \`RELOAD_IN_PROGRESS\`: no duplicate replacement of the same source. -- \`CONFIG_INVALID\`, \`CONFIG_CLI_INVALID\`, \`INITIALIZE_FAILED\`, - \`READINESS_FAILED\`: old healthy generation is retained. -- \`TOOL_NAME_LIMIT\`: bound on unique registered direct/gateway tool names; +- `RELOAD_IN_PROGRESS`: no duplicate replacement of the same source. +- `CONFIG_INVALID`, `CONFIG_CLI_INVALID`, `INITIALIZE_FAILED`, + `READINESS_FAILED`: old healthy generation is retained. +- `TOOL_NAME_LIMIT`: bound on unique registered direct/gateway tool names; the attempted registry swap is discarded. -- \`CANCELLED\`: an aborted preparation does not switch generations. +- `CANCELLED`: an aborted preparation does not switch generations. - If the old generation became unhealthy independently, a successful new connection is preferred; the operation does not imply that the old peer can be resurrected. From 8281331880a8be2ca9d2a1ea195d9060005e44fc Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:32:58 +0100 Subject: [PATCH 052/118] feat(mcp): expose reload phase timings and remaining in-flight calls --- src/bridge/hot_reload.rs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/src/bridge/hot_reload.rs b/src/bridge/hot_reload.rs index 2cfa4d5c..30f03399 100644 --- a/src/bridge/hot_reload.rs +++ b/src/bridge/hot_reload.rs @@ -335,6 +335,7 @@ impl HotReloadRuntime { if cancellation.is_some_and(CancellationToken::is_cancelled) { return Err("CANCELLED"); } + let started = std::time::Instant::now(); let previous = self.snapshot().sources.get(name).cloned(); let old_generation = previous.as_ref().map_or(0, |source| source.number); let future = connect_one(name, &spec, &self.config); @@ -403,6 +404,7 @@ impl HotReloadRuntime { .filter(|(key, value)| before.get(**key).is_some_and(|old| old == *value)) .count(); } + let initialization_ms = started.elapsed().as_millis() as u64; let new = Generation::new( spec, service, @@ -414,6 +416,7 @@ impl HotReloadRuntime { // Connection preparation and view construction are outside the write // lock. Compare-and-rebuild prevents concurrent distinct-source reloads // from overwriting each other. + let switching = std::time::Instant::now(); loop { let before = self.snapshot(); let mut sources = before.sources.clone(); @@ -430,6 +433,7 @@ impl HotReloadRuntime { .write() .unwrap() .insert(name.to_owned(), new.control.clone()); + let switching_ms = switching.elapsed().as_millis() as u64; if new.spec.exposure() == McpToolExposure::Gateway { let funcs = new @@ -454,11 +458,15 @@ impl HotReloadRuntime { let drain_ms = previous .as_ref() .map_or(0, |source| source.spec.request_limits.slow_cancellation_ms); + let draining = std::time::Instant::now(); let drained = if let Some(old) = &previous { old.wait_for_calls(Duration::from_millis(drain_ms)).await } else { true }; + let in_flight = previous + .as_ref() + .map_or(0, |old| *old.calls.lock().unwrap()); Ok(json!({ "source": name, "outcome": "reloaded", @@ -471,8 +479,15 @@ impl HotReloadRuntime { "added": added, "removed": removed, "changed": changed, "unchanged": unchanged }, "oldCallsDrained": drained, + "oldCallsStillRunning": in_flight, "oldGenerationRetiring": !drained, "rollback": "not_required", + "timingsMs": { + "initializationAndReadiness": initialization_ms, + "registrySwitch": switching_ms, + "drain": draining.elapsed().as_millis() as u64, + "total": started.elapsed().as_millis() as u64 + }, "clientRediscoveryRequired": true, "diagnosticCode": "OK" })) From 9c5367eaea74c057bd2b12308e13dbe5f857f9fc Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:33:53 +0100 Subject: [PATCH 053/118] refactor(mcp): use one conversion for gateway function descriptors --- src/bridge.rs | 30 ++++++++++++++++++------------ 1 file changed, 18 insertions(+), 12 deletions(-) diff --git a/src/bridge.rs b/src/bridge.rs index 1d1d111a..557dcea7 100644 --- a/src/bridge.rs +++ b/src/bridge.rs @@ -536,18 +536,7 @@ pub async fn connect_upstreams(config: &AppConfig) -> Bridge { let count = tools.len(); let mode = spec.exposure(); if mode == McpToolExposure::Gateway { - let functions = tools - .iter() - .map(|tool| GatewayFunction { - name: tool.name.to_string(), - description: tool - .description - .as_ref() - .map(ToString::to_string) - .unwrap_or_default(), - input_schema: Value::Object((*tool.input_schema).clone()), - }) - .collect::>(); + let functions = gateway_functions(&tools); write_gateway_skill(config, name, &sanitize(name), &functions); } let generation = hot_reload::Generation::new( @@ -576,6 +565,23 @@ pub async fn connect_upstreams(config: &AppConfig) -> Bridge { } } +/// Use one conversion for startup registration, registry replacement and +/// generated gateway skills, so schema/description metadata cannot diverge. +fn gateway_functions(tools: &[rmcp::model::Tool]) -> Vec { + tools + .iter() + .map(|tool| GatewayFunction { + name: tool.name.to_string(), + description: tool + .description + .as_ref() + .map(ToString::to_string) + .unwrap_or_default(), + input_schema: Value::Object((*tool.input_schema).clone()), + }) + .collect() +} + /// One function exposed by a gateway-mode server. struct GatewayFunction { name: String, From 8987a6c25d739c15ec6d0d17a65391de76fd9477 Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:33:55 +0100 Subject: [PATCH 054/118] refactor(mcp): reuse gateway metadata conversion on reload --- src/bridge/hot_reload.rs | 28 ++-------------------------- 1 file changed, 2 insertions(+), 26 deletions(-) diff --git a/src/bridge/hot_reload.rs b/src/bridge/hot_reload.rs index 30f03399..517bef1a 100644 --- a/src/bridge/hot_reload.rs +++ b/src/bridge/hot_reload.rs @@ -174,19 +174,7 @@ impl HotReloadRuntime { let sanitized = sanitize(name); match source.spec.exposure() { McpToolExposure::Gateway => { - let functions: Vec = source - .tools - .iter() - .map(|tool| GatewayFunction { - name: tool.name.to_string(), - description: tool - .description - .as_ref() - .map(ToString::to_string) - .unwrap_or_default(), - input_schema: Value::Object((*tool.input_schema).clone()), - }) - .collect(); + let functions = gateway_functions(&source.tools); let tool = GatewayTool { name: names.intern(sanitized)?, server: name.clone(), @@ -436,19 +424,7 @@ impl HotReloadRuntime { let switching_ms = switching.elapsed().as_millis() as u64; if new.spec.exposure() == McpToolExposure::Gateway { - let funcs = new - .tools - .iter() - .map(|t| GatewayFunction { - name: t.name.to_string(), - description: t - .description - .as_ref() - .map(ToString::to_string) - .unwrap_or_default(), - input_schema: Value::Object((*t.input_schema).clone()), - }) - .collect::>(); + let funcs = gateway_functions(&new.tools); write_gateway_skill(&self.config, name, &sanitize(name), &funcs); } From f10b5040bc6eee164ccd3aac1776b6da2ac100b6 Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:35:00 +0100 Subject: [PATCH 055/118] fix(mcp): honor cancellation after readiness but before registry publication --- src/bridge/hot_reload.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/bridge/hot_reload.rs b/src/bridge/hot_reload.rs index 517bef1a..844a4248 100644 --- a/src/bridge/hot_reload.rs +++ b/src/bridge/hot_reload.rs @@ -404,6 +404,9 @@ impl HotReloadRuntime { // Connection preparation and view construction are outside the write // lock. Compare-and-rebuild prevents concurrent distinct-source reloads // from overwriting each other. + if cancellation.is_some_and(CancellationToken::is_cancelled) { + return Err("CANCELLED"); + } let switching = std::time::Instant::now(); loop { let before = self.snapshot(); From f3d74c17a7628131c9c4d736b510c0064dd9246c Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:35:35 +0100 Subject: [PATCH 056/118] fix(mcp): release startup bridge tool snapshot to retire old processes --- src/server.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/server.rs b/src/server.rs index 164f696b..b5b5df4c 100644 --- a/src/server.rs +++ b/src/server.rs @@ -2212,6 +2212,10 @@ pub async fn start_http_server(mut config: AppConfig) -> anyhow::Result<()> { let bridged_resources = bridge.resources; let upstreams = bridge.upstreams; let bridge_runtime = bridge.runtime; + // The test-facing startup tool vector holds references to generation 1. + // Drop it immediately: only the runtime's replaceable snapshot may retain + // active sources, or retired child processes would remain pinned forever. + drop(bridge.tools); let mut all_tools = validate_and_wrap_tools(load_tools_for_config(&config)) .map_err(|error| anyhow::anyhow!("invalid native tool contract: {error}"))?; From 63d325779db0c99798df030a60f0a6e65f9ec4c6 Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:35:48 +0100 Subject: [PATCH 057/118] test(mcp): assert drained generations and services are not retained --- src/bridge/hot_reload_tests.rs | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/src/bridge/hot_reload_tests.rs b/src/bridge/hot_reload_tests.rs index 78b1b59a..65c5e0ef 100644 --- a/src/bridge/hot_reload_tests.rs +++ b/src/bridge/hot_reload_tests.rs @@ -391,3 +391,30 @@ async fn direct_name_collisions_are_not_ambiguous_after_reload() { task1.abort(); task2.abort(); } + +#[tokio::test] +async fn old_generation_is_released_after_draining_without_stale_snapshots() { + let (old_url, _, old_task) = + fixture("old", false, Duration::ZERO, Duration::ZERO).await; + let (new_url, _, new_task) = + fixture("new", true, Duration::ZERO, Duration::ZERO).await; + let mut config = crate::config::default_config(std::env::temp_dir()); + config.mcp_servers.insert("alpha".into(), spec(&old_url, McpToolExposure::Direct)); + let bridge = connect_upstreams(&config).await; + let runtime = bridge.runtime.clone(); + let first = runtime.snapshot(); + let weak = Arc::downgrade(&first.sources["alpha"]); + drop(first); + // The service keeps only the runtime after consuming the startup report. + drop(bridge); + assert!(weak.upgrade().is_some()); + + let result = runtime.reload_with_spec( + "alpha", spec(&new_url, McpToolExposure::Direct), None + ).await.unwrap(); + assert_eq!(result["oldCallsDrained"], true); + assert!(weak.upgrade().is_none(), "retired service generation leaked"); + assert_eq!(invoke(runtime.snapshot(), "alpha__probe").await.joined_text(), "new"); + old_task.abort(); + new_task.abort(); +} From abd069772f16963443585bc53aceb88dc5305737 Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:36:35 +0100 Subject: [PATCH 058/118] docs(mcp): record phase timings and cross-generation resource-link caveat --- docs/MCP_HOT_RELOAD.md | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/docs/MCP_HOT_RELOAD.md b/docs/MCP_HOT_RELOAD.md index 952001d1..913f8fac 100644 --- a/docs/MCP_HOT_RELOAD.md +++ b/docs/MCP_HOT_RELOAD.md @@ -52,8 +52,10 @@ required acceptance gates before production activation. A successful result includes `source`, `outcome`, `previousGeneration`, `replacementGeneration`, old/new reported MCP server versions, readiness, counts of added/removed/changed/unchanged -tool definitions, `oldCallsDrained`, `oldGenerationRetiring`, -`rollback`, and `diagnosticCode`. +tool definitions, `oldCallsDrained`, `oldCallsStillRunning`, +`oldGenerationRetiring`, `rollback`, `diagnosticCode`, and measured +`timingsMs` for initialization/readiness, registry switch, draining and total +reload duration. The source's discovery data and forwarded-call routes change together in the server's tool registry. Existing transport sessions can observe changed @@ -82,6 +84,11 @@ and generated skill after reload. - If the old generation became unhealthy independently, a successful new connection is preferred; the operation does not imply that the old peer can be resurrected. +- Resource links issued before a reload are separate capabilities. An upstream + resource fetched **after** its old connection retires can fail; request a + fresh resource link from the new source. Already-running resource reads + retain their own peer and cancellation semantics, but cross-generation + resource-link durability is not claimed by this implementation. - Invalid data from upstream tool descriptions must remain untrusted. Reload permission uses existing Codexify connector authorization and audit boundaries. Do not expose the control plane to unauthenticated clients. From 49d93e39a889c49d5b439080c9755892ac1297c7 Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:42:40 +0100 Subject: [PATCH 059/118] style(mcp): apply CI rustfmt corrections in src/bridge/hot_reload_tests.rs --- src/bridge/hot_reload_tests.rs | 332 ++++++++++++++++++++++----------- 1 file changed, 222 insertions(+), 110 deletions(-) diff --git a/src/bridge/hot_reload_tests.rs b/src/bridge/hot_reload_tests.rs index 65c5e0ef..73bac52f 100644 --- a/src/bridge/hot_reload_tests.rs +++ b/src/bridge/hot_reload_tests.rs @@ -9,8 +9,7 @@ use rmcp::{ }, service::{RequestContext, RoleServer}, transport::streamable_http_server::{ - StreamableHttpServerConfig, StreamableHttpService, - session::local::LocalSessionManager, + StreamableHttpServerConfig, StreamableHttpService, session::local::LocalSessionManager, }, }; use std::sync::atomic::{AtomicUsize, Ordering}; @@ -40,14 +39,23 @@ impl ServerHandler for Fixture { "type": "object", "properties": {}, "additionalProperties": false - }).as_object().cloned().unwrap(); + }) + .as_object() + .cloned() + .unwrap(); let mut tools = vec![ rmcp::model::Tool::new("probe", "Report this fixture's version", schema.clone()), - rmcp::model::Tool::new("slow", "Report this fixture's version after a delay", schema.clone()), + rmcp::model::Tool::new( + "slow", + "Report this fixture's version after a delay", + schema.clone(), + ), ]; if self.new_tool { tools.push(rmcp::model::Tool::new( - "new_tool", "Added in version two", schema + "new_tool", + "Added in version two", + schema, )); } Ok(ListToolsResult::with_all_items(tools)) @@ -72,7 +80,9 @@ async fn fixture( list_delay: Duration, call_delay: Duration, ) -> (String, Arc, tokio::task::JoinHandle<()>) { - let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0)).await.unwrap(); + let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0)) + .await + .unwrap(); let address = listener.local_addr().unwrap(); let calls = Arc::new(AtomicUsize::new(0)); let fixture = Fixture { @@ -108,40 +118,48 @@ async fn invoke(view: Arc, name: &str) -> ToolResult { invoke_args(view, name, json!({})).await } -async fn invoke_args( - view: Arc, - name: &str, - args: Value, -) -> ToolResult { - let tool = view.tools.iter().find(|tool| tool.name() == name) +async fn invoke_args(view: Arc, name: &str, args: Value) -> ToolResult { + let tool = view + .tools + .iter() + .find(|tool| tool.name() == name) .unwrap_or_else(|| panic!("tool {name} missing from view")); tool.call( args, &crate::config::default_config(std::env::temp_dir()), &SessionState::new(), - ).await + ) + .await } #[tokio::test] async fn single_source_reload_updates_tools_but_not_other_mcp() { - let (old_url, _, old_task) = - fixture("1", false, Duration::ZERO, Duration::ZERO).await; - let (new_url, _, new_task) = - fixture("2", true, Duration::ZERO, Duration::ZERO).await; - let (other_url, _, other_task) = - fixture("other", false, Duration::ZERO, Duration::ZERO).await; + let (old_url, _, old_task) = fixture("1", false, Duration::ZERO, Duration::ZERO).await; + let (new_url, _, new_task) = fixture("2", true, Duration::ZERO, Duration::ZERO).await; + let (other_url, _, other_task) = fixture("other", false, Duration::ZERO, Duration::ZERO).await; let mut config = crate::config::default_config(std::env::temp_dir()); - config.mcp_servers.insert("alpha".into(), spec(&old_url, McpToolExposure::Direct)); - config.mcp_servers.insert("beta".into(), spec(&other_url, McpToolExposure::Direct)); + config + .mcp_servers + .insert("alpha".into(), spec(&old_url, McpToolExposure::Direct)); + config + .mcp_servers + .insert("beta".into(), spec(&other_url, McpToolExposure::Direct)); let bridge = connect_upstreams(&config).await; let runtime = bridge.runtime.clone(); let before = runtime.snapshot(); - assert_eq!(invoke(before.clone(), "alpha__probe").await.joined_text(), "1"); - assert_eq!(invoke(before.clone(), "beta__probe").await.joined_text(), "other"); + assert_eq!( + invoke(before.clone(), "alpha__probe").await.joined_text(), + "1" + ); + assert_eq!( + invoke(before.clone(), "beta__probe").await.joined_text(), + "other" + ); - let result = runtime.reload_with_spec( - "alpha", spec(&new_url, McpToolExposure::Direct), None - ).await.unwrap(); + let result = runtime + .reload_with_spec("alpha", spec(&new_url, McpToolExposure::Direct), None) + .await + .unwrap(); assert_eq!(result["outcome"], "reloaded"); assert_eq!(result["previousGeneration"], 1); assert_eq!(result["replacementGeneration"], 2); @@ -152,9 +170,18 @@ async fn single_source_reload_updates_tools_but_not_other_mcp() { let after = runtime.snapshot(); assert!(Arc::ptr_eq(&before.sources["beta"], &after.sources["beta"])); - assert!(!Arc::ptr_eq(&before.sources["alpha"], &after.sources["alpha"])); - assert_eq!(invoke(after.clone(), "alpha__probe").await.joined_text(), "2"); - assert_eq!(invoke(after.clone(), "alpha__new_tool").await.joined_text(), "2"); + assert!(!Arc::ptr_eq( + &before.sources["alpha"], + &after.sources["alpha"] + )); + assert_eq!( + invoke(after.clone(), "alpha__probe").await.joined_text(), + "2" + ); + assert_eq!( + invoke(after.clone(), "alpha__new_tool").await.joined_text(), + "2" + ); assert_eq!(invoke(after, "beta__probe").await.joined_text(), "other"); assert_eq!(invoke(before, "alpha__probe").await.joined_text(), "1"); old_task.abort(); @@ -166,10 +193,11 @@ async fn single_source_reload_updates_tools_but_not_other_mcp() { async fn active_calls_keep_their_original_generation_without_replay() { let (old_url, old_count, old_task) = fixture("1", false, Duration::ZERO, Duration::from_millis(450)).await; - let (new_url, new_count, new_task) = - fixture("2", true, Duration::ZERO, Duration::ZERO).await; + let (new_url, new_count, new_task) = fixture("2", true, Duration::ZERO, Duration::ZERO).await; let mut config = crate::config::default_config(std::env::temp_dir()); - config.mcp_servers.insert("alpha".into(), spec(&old_url, McpToolExposure::Direct)); + config + .mcp_servers + .insert("alpha".into(), spec(&old_url, McpToolExposure::Direct)); let runtime = connect_upstreams(&config).await.runtime; let initial = runtime.snapshot(); let pending = tokio::spawn(invoke(initial, "alpha__slow")); @@ -177,16 +205,24 @@ async fn active_calls_keep_their_original_generation_without_replay() { while old_count.load(Ordering::SeqCst) == 0 { tokio::time::sleep(Duration::from_millis(5)).await; } - }).await.unwrap(); + }) + .await + .unwrap(); let started = std::time::Instant::now(); - let result = runtime.reload_with_spec( - "alpha", spec(&new_url, McpToolExposure::Direct), None - ).await.unwrap(); + let result = runtime + .reload_with_spec("alpha", spec(&new_url, McpToolExposure::Direct), None) + .await + .unwrap(); assert_eq!(result["oldCallsDrained"], true); assert!(started.elapsed() >= Duration::from_millis(100)); assert_eq!(pending.await.unwrap().joined_text(), "1"); assert_eq!(old_count.load(Ordering::SeqCst), 1); - assert_eq!(invoke(runtime.snapshot(), "alpha__probe").await.joined_text(), "2"); + assert_eq!( + invoke(runtime.snapshot(), "alpha__probe") + .await + .joined_text(), + "2" + ); assert_eq!(new_count.load(Ordering::SeqCst), 1); old_task.abort(); new_task.abort(); @@ -194,23 +230,34 @@ async fn active_calls_keep_their_original_generation_without_replay() { #[tokio::test] async fn failed_replacement_and_unknown_ids_cannot_mutate_active_generation() { - let (old_url, _, old_task) = - fixture("1", false, Duration::ZERO, Duration::ZERO).await; + let (old_url, _, old_task) = fixture("1", false, Duration::ZERO, Duration::ZERO).await; let mut config = crate::config::default_config(std::env::temp_dir()); - config.mcp_servers.insert("alpha".into(), spec(&old_url, McpToolExposure::Direct)); + config + .mcp_servers + .insert("alpha".into(), spec(&old_url, McpToolExposure::Direct)); let runtime = connect_upstreams(&config).await.runtime; let old = runtime.snapshot(); assert_eq!( - runtime.reload_with_spec( - "missing", spec("http://127.0.0.1:9/mcp", McpToolExposure::Direct), None - ).await.unwrap_err(), + runtime + .reload_with_spec( + "missing", + spec("http://127.0.0.1:9/mcp", McpToolExposure::Direct), + None + ) + .await + .unwrap_err(), "SOURCE_UNKNOWN" ); assert_eq!( - runtime.reload_with_spec( - "alpha", spec("http://127.0.0.1:9/mcp", McpToolExposure::Direct), None - ).await.unwrap_err(), + runtime + .reload_with_spec( + "alpha", + spec("http://127.0.0.1:9/mcp", McpToolExposure::Direct), + None + ) + .await + .unwrap_err(), "INITIALIZE_FAILED" ); let after = runtime.snapshot(); @@ -221,35 +268,43 @@ async fn failed_replacement_and_unknown_ids_cannot_mutate_active_generation() { #[tokio::test] async fn same_source_reload_conflicts_while_other_source_can_reload() { - let (a1, _, first_task) = - fixture("1", false, Duration::ZERO, Duration::ZERO).await; - let (a2, _, second_task) = - fixture("2", true, Duration::from_millis(300), Duration::ZERO).await; - let (b1, _, third_task) = - fixture("other1", false, Duration::ZERO, Duration::ZERO).await; - let (b2, _, fourth_task) = - fixture("other2", false, Duration::ZERO, Duration::ZERO).await; + let (a1, _, first_task) = fixture("1", false, Duration::ZERO, Duration::ZERO).await; + let (a2, _, second_task) = fixture("2", true, Duration::from_millis(300), Duration::ZERO).await; + let (b1, _, third_task) = fixture("other1", false, Duration::ZERO, Duration::ZERO).await; + let (b2, _, fourth_task) = fixture("other2", false, Duration::ZERO, Duration::ZERO).await; let mut config = crate::config::default_config(std::env::temp_dir()); - config.mcp_servers.insert("alpha".into(), spec(&a1, McpToolExposure::Direct)); - config.mcp_servers.insert("beta".into(), spec(&b1, McpToolExposure::Direct)); + config + .mcp_servers + .insert("alpha".into(), spec(&a1, McpToolExposure::Direct)); + config + .mcp_servers + .insert("beta".into(), spec(&b1, McpToolExposure::Direct)); let runtime = connect_upstreams(&config).await.runtime; let clone = runtime.clone(); let initial = tokio::spawn(async move { - clone.reload_with_spec("alpha", spec(&a2, McpToolExposure::Direct), None).await + clone + .reload_with_spec("alpha", spec(&a2, McpToolExposure::Direct), None) + .await }); tokio::time::sleep(Duration::from_millis(50)).await; assert_eq!( - runtime.reload_with_spec("alpha", spec(&a1, McpToolExposure::Direct), None) - .await.unwrap_err(), + runtime + .reload_with_spec("alpha", spec(&a1, McpToolExposure::Direct), None) + .await + .unwrap_err(), "RELOAD_IN_PROGRESS" ); - let other = runtime.reload_with_spec( - "beta", spec(&b2, McpToolExposure::Direct), None - ).await.unwrap(); + let other = runtime + .reload_with_spec("beta", spec(&b2, McpToolExposure::Direct), None) + .await + .unwrap(); assert_eq!(other["replacementGeneration"], 2); assert_eq!(initial.await.unwrap().unwrap()["replacementGeneration"], 2); let view = runtime.snapshot(); - assert_eq!(invoke(view.clone(), "alpha__probe").await.joined_text(), "2"); + assert_eq!( + invoke(view.clone(), "alpha__probe").await.joined_text(), + "2" + ); assert_eq!(invoke(view, "beta__probe").await.joined_text(), "other2"); first_task.abort(); second_task.abort(); @@ -259,33 +314,47 @@ async fn same_source_reload_conflicts_while_other_source_can_reload() { #[tokio::test] async fn catalog_reload_refreshes_search_schema_and_call_routing() { - let (old_url, _, old_task) = - fixture("1", false, Duration::ZERO, Duration::ZERO).await; - let (new_url, _, new_task) = - fixture("2", true, Duration::ZERO, Duration::ZERO).await; + let (old_url, _, old_task) = fixture("1", false, Duration::ZERO, Duration::ZERO).await; + let (new_url, _, new_task) = fixture("2", true, Duration::ZERO, Duration::ZERO).await; let mut config = crate::config::default_config(std::env::temp_dir()); - config.mcp_servers.insert("catalog".into(), spec(&old_url, McpToolExposure::Catalog)); + config + .mcp_servers + .insert("catalog".into(), spec(&old_url, McpToolExposure::Catalog)); let runtime = connect_upstreams(&config).await.runtime; let before = runtime.snapshot(); - let source = invoke(before, "mcp_list_sources").await.structured_content.unwrap(); + let source = invoke(before, "mcp_list_sources") + .await + .structured_content + .unwrap(); assert_eq!(source["sources"][0]["toolCount"], 2); - let result = runtime.reload_with_spec( - "catalog", spec(&new_url, McpToolExposure::Catalog), None - ).await.unwrap(); + let result = runtime + .reload_with_spec("catalog", spec(&new_url, McpToolExposure::Catalog), None) + .await + .unwrap(); assert_eq!(result["toolChanges"]["added"], 1); let after = runtime.snapshot(); - let list = invoke(after.clone(), "mcp_list_sources").await.structured_content.unwrap(); + let list = invoke(after.clone(), "mcp_list_sources") + .await + .structured_content + .unwrap(); assert_eq!(list["sources"][0]["toolCount"], 3); let source_id = list["sources"][0]["id"].as_str().unwrap(); let found = invoke_args( - after.clone(), "mcp_search_tools", json!({"query":"new_tool","source":source_id}) - ).await.structured_content.unwrap(); + after.clone(), + "mcp_search_tools", + json!({"query":"new_tool","source":source_id}), + ) + .await + .structured_content + .unwrap(); assert!(found["total"].as_u64().unwrap_or(0) >= 1); let tool_id = found["matches"][0]["toolId"].as_str().unwrap(); let call = invoke_args( - after, "mcp_call_tool", - json!({"source":source_id,"tool":tool_id,"arguments":{}}) - ).await; + after, + "mcp_call_tool", + json!({"source":source_id,"tool":tool_id,"arguments":{}}), + ) + .await; assert!(!call.is_error); assert_eq!(call.joined_text(), "2"); old_task.abort(); @@ -294,30 +363,43 @@ async fn catalog_reload_refreshes_search_schema_and_call_routing() { #[tokio::test] async fn gateway_reload_reflects_added_functions() { - let (old_url, _, old_task) = - fixture("1", false, Duration::ZERO, Duration::ZERO).await; - let (new_url, _, new_task) = - fixture("2", true, Duration::ZERO, Duration::ZERO).await; + let (old_url, _, old_task) = fixture("1", false, Duration::ZERO, Duration::ZERO).await; + let (new_url, _, new_task) = fixture("2", true, Duration::ZERO, Duration::ZERO).await; let mut config = crate::config::default_config(std::env::temp_dir()); - config.mcp_servers.insert("gateway".into(), spec(&old_url, McpToolExposure::Gateway)); + config + .mcp_servers + .insert("gateway".into(), spec(&old_url, McpToolExposure::Gateway)); let runtime = connect_upstreams(&config).await.runtime; let before = runtime.snapshot(); let old = invoke_args( - before, "gateway", json!({"function":"probe","arguments":{}}) - ).await; + before, + "gateway", + json!({"function":"probe","arguments":{}}), + ) + .await; assert_eq!(old.joined_text(), "1"); - runtime.reload_with_spec( - "gateway", spec(&new_url, McpToolExposure::Gateway), None - ).await.unwrap(); + runtime + .reload_with_spec("gateway", spec(&new_url, McpToolExposure::Gateway), None) + .await + .unwrap(); let after = runtime.snapshot(); - let tool = after.tools.iter().find(|tool| tool.name() == "gateway").unwrap(); + let tool = after + .tools + .iter() + .find(|tool| tool.name() == "gateway") + .unwrap(); assert!( tool.input_schema()["properties"]["function"]["enum"] - .as_array().unwrap().contains(&json!("new_tool")) + .as_array() + .unwrap() + .contains(&json!("new_tool")) ); let new = invoke_args( - after, "gateway", json!({"function":"new_tool","arguments":{}}) - ).await; + after, + "gateway", + json!({"function":"new_tool","arguments":{}}), + ) + .await; assert_eq!(new.joined_text(), "2"); old_task.abort(); new_task.abort(); @@ -328,28 +410,41 @@ async fn reconnect_failed_initial_source_and_cancel_without_switching() { let (url, _, task) = fixture("recovered", false, Duration::ZERO, Duration::ZERO).await; let mut config = crate::config::default_config(std::env::temp_dir()); config.mcp_servers.insert( - "unavailable".into(), crate::types::McpServerSpec { + "unavailable".into(), + crate::types::McpServerSpec { url: Some("http://127.0.0.1:9/mcp".into()), startup_timeout_sec: Some(0.5), ..Default::default() - } + }, ); let runtime = connect_upstreams(&config).await.runtime; assert!(!runtime.snapshot().sources.contains_key("unavailable")); - let result = runtime.reload_with_spec( - "unavailable", spec(&url, McpToolExposure::Direct), None - ).await.unwrap(); + let result = runtime + .reload_with_spec("unavailable", spec(&url, McpToolExposure::Direct), None) + .await + .unwrap(); assert_eq!(result["previousGeneration"], 0); assert_eq!(result["replacementGeneration"], 1); - assert_eq!(invoke(runtime.snapshot(), "unavailable__probe").await.joined_text(), "recovered"); + assert_eq!( + invoke(runtime.snapshot(), "unavailable__probe") + .await + .joined_text(), + "recovered" + ); let old = runtime.snapshot(); let cancelled = CancellationToken::new(); cancelled.cancel(); assert_eq!( - runtime.reload_with_spec( - "unavailable", spec(&url, McpToolExposure::Direct), Some(&cancelled) - ).await.unwrap_err(), "CANCELLED" + runtime + .reload_with_spec( + "unavailable", + spec(&url, McpToolExposure::Direct), + Some(&cancelled) + ) + .await + .unwrap_err(), + "CANCELLED" ); assert!(Arc::ptr_eq(&old, &runtime.snapshot())); task.abort(); @@ -359,12 +454,15 @@ async fn reconnect_failed_initial_source_and_cancel_without_switching() { async fn repeated_reloads_keep_one_active_generation_per_source() { let (url, _, task) = fixture("stable", false, Duration::ZERO, Duration::ZERO).await; let mut config = crate::config::default_config(std::env::temp_dir()); - config.mcp_servers.insert("alpha".into(), spec(&url, McpToolExposure::Direct)); + config + .mcp_servers + .insert("alpha".into(), spec(&url, McpToolExposure::Direct)); let runtime = connect_upstreams(&config).await.runtime; for expected in 2..=6 { - let result = runtime.reload_with_spec( - "alpha", spec(&url, McpToolExposure::Direct), None - ).await.unwrap(); + let result = runtime + .reload_with_spec("alpha", spec(&url, McpToolExposure::Direct), None) + .await + .unwrap(); assert_eq!(result["replacementGeneration"], expected); assert_eq!(result["oldCallsDrained"], true); let view = runtime.snapshot(); @@ -380,14 +478,28 @@ async fn direct_name_collisions_are_not_ambiguous_after_reload() { let (url2, _, task2) = fixture("two", true, Duration::ZERO, Duration::ZERO).await; let mut config = crate::config::default_config(std::env::temp_dir()); // sanitize("dup!")==sanitize("dup?"), so both would generate dup___probe. - config.mcp_servers.insert("dup!".into(), spec(&url1, McpToolExposure::Direct)); - config.mcp_servers.insert("dup?".into(), spec(&url2, McpToolExposure::Direct)); + config + .mcp_servers + .insert("dup!".into(), spec(&url1, McpToolExposure::Direct)); + config + .mcp_servers + .insert("dup?".into(), spec(&url2, McpToolExposure::Direct)); let runtime = connect_upstreams(&config).await.runtime; let view = runtime.snapshot(); - let names = view.tools.iter().map(|tool| tool.name()).collect::>(); - let unique = names.iter().copied().collect::>(); + let names = view + .tools + .iter() + .map(|tool| tool.name()) + .collect::>(); + let unique = names + .iter() + .copied() + .collect::>(); assert_eq!(unique.len(), names.len()); - assert_eq!(names.iter().filter(|name| **name == "dup___probe").count(), 1); + assert_eq!( + names.iter().filter(|name| **name == "dup___probe").count(), + 1 + ); task1.abort(); task2.abort(); } From d5feede9d571e2f6d37c584e8456b9c2a901c745 Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:42:42 +0100 Subject: [PATCH 060/118] style(mcp): apply CI rustfmt corrections in src/bridge.rs --- src/bridge.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/bridge.rs b/src/bridge.rs index 557dcea7..2a8cd172 100644 --- a/src/bridge.rs +++ b/src/bridge.rs @@ -35,10 +35,10 @@ use crate::process_env::scrub_untrusted_child_env; use crate::tool::{Tool, ToolBehavior, ToolCallIdentity, ToolRequestContext}; use crate::types::{AppConfig, McpToolExposure, ToolContent, ToolResult}; -mod stderr; mod hot_reload; #[cfg(test)] mod hot_reload_tests; +mod stderr; pub(crate) use hot_reload::{Generation, HotReloadRuntime, ReloadMcpTool}; /// How long to wait for an upstream to start up and answer `tools/list` before From 3acf5cddadee4ba16807795c4b09615a8ac37135 Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:46:24 +0100 Subject: [PATCH 061/118] refactor(mcp): share individual dynamic tools independently of registry snapshots --- src/bridge.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/bridge.rs b/src/bridge.rs index 2a8cd172..6dae727e 100644 --- a/src/bridge.rs +++ b/src/bridge.rs @@ -48,7 +48,7 @@ const CONNECT_TIMEOUT: Duration = Duration::from_secs(20); /// Connected MCP sources are owned by a transactional registry. Its immutable /// view is shared across transport sessions, while calls pin their generation. pub struct Bridge { - pub tools: Arc>>, + pub tools: Arc>>, pub resources: Arc, pub report: Vec, pub(crate) runtime: Arc, From 998130af92dc3f9599481063d86b660b245b6e61 Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:46:26 +0100 Subject: [PATCH 062/118] fix(mcp): store validated MCP tool descriptors as independently pinned Arc --- src/bridge/hot_reload.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/bridge/hot_reload.rs b/src/bridge/hot_reload.rs index 844a4248..046ec945 100644 --- a/src/bridge/hot_reload.rs +++ b/src/bridge/hot_reload.rs @@ -109,7 +109,7 @@ impl NamePool { } pub(crate) struct BridgeView { - pub(crate) tools: Arc>>, + pub(crate) tools: Arc>>, pub(crate) sources: HashMap>, } @@ -253,7 +253,7 @@ impl HotReloadRuntime { return None; } match crate::tool::validate_and_wrap_tool(tool) { - Ok(tool) => Some(tool), + Ok(tool) => Some(Arc::::from(tool)), Err(error) => { tracing::warn!(%error, "invalid upstream MCP tool skipped"); None From 8556193b84f58d2c8b4328948bedcc8a16cde972 Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:46:28 +0100 Subject: [PATCH 063/118] fix(mcp): dispatch pins only the selected upstream generation to prevent cross-source retention --- src/server.rs | 20 +++++++++----------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/src/server.rs b/src/server.rs index b5b5df4c..c4d30e51 100644 --- a/src/server.rs +++ b/src/server.rs @@ -836,21 +836,19 @@ impl ServerHandler for CodexHandler { .arguments .map(Value::Object) .unwrap_or_else(|| json!({})); - // Pin a complete immutable upstream registry through the entire async - // dispatch. Hot reload cannot close this request's source generation. - let bridge_view = self - .bridge_runtime - .as_ref() - .map(|runtime| runtime.snapshot()); + // Pin only the selected upstream tool for this entire async dispatch. + // Holding the full registry snapshot here would keep *unrelated* retired + // MCP processes alive while another source runs a long request. + let bridge_tool = self.bridge_runtime.as_ref().and_then(|runtime| { + let view = runtime.snapshot(); + view.tools.iter().find(|tool| tool.name() == name).cloned() + }); let tool = self .tools .iter() .find(|tool| tool.name() == name) - .or_else(|| { - bridge_view - .as_ref() - .and_then(|view| view.tools.iter().find(|tool| tool.name() == name)) - }); + .map(|tool| tool.as_ref()) + .or_else(|| bridge_tool.as_deref()); let ticket_wait = name == TicketWait::NAME && tool.is_some(); let model_call = !tool.is_some_and(|tool| app_only_tool(tool.as_ref())); let mut task_conversation = conversation.clone(); From 040e5e28a729e833b71445b66c0cf12d801cb800 Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:46:52 +0100 Subject: [PATCH 064/118] fix(mcp): propagate trait-object dispatch references after source-specific pinning --- src/server.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/server.rs b/src/server.rs index c4d30e51..9d94765f 100644 --- a/src/server.rs +++ b/src/server.rs @@ -850,7 +850,7 @@ impl ServerHandler for CodexHandler { .map(|tool| tool.as_ref()) .or_else(|| bridge_tool.as_deref()); let ticket_wait = name == TicketWait::NAME && tool.is_some(); - let model_call = !tool.is_some_and(|tool| app_only_tool(tool.as_ref())); + let model_call = !tool.is_some_and(app_only_tool); let mut task_conversation = conversation.clone(); let mut task_owner_generation = None; let mut conversation_retired = false; @@ -1046,7 +1046,7 @@ impl ServerHandler for CodexHandler { // Keep `tool` as an Option so that even an unknown-tool call flows through // the audit begin/finish pairing below rather than short-circuiting. let agent_call = self.config.markdown_chat.enabled - && tool.is_some_and(|tool| !app_only_tool(tool.as_ref())) + && tool.is_some_and(|tool| !app_only_tool(tool)) && !ticket_wait && !context.ct.is_cancelled(); let called_at_ms = crate::markdown_chat::now_ms(); @@ -1679,7 +1679,7 @@ impl ServerHandler for CodexHandler { .await; } } - finalize_model_visible_result(tool.map(|tool| tool.as_ref()), &mut result, &self.config); + finalize_model_visible_result(tool, &mut result, &self.config); if !result.is_error && let Some(tool) = tool && let Err(error) = tool.validate_structured_output(result.structured_content.as_ref()) From 84a081dfe6b9e3e14ce0f8016827d23c3b2a8ea0 Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:47:04 +0100 Subject: [PATCH 065/118] fix(mcp): use trait object in owner-chat cleanup gate --- src/server.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/server.rs b/src/server.rs index 9d94765f..792fc2cb 100644 --- a/src/server.rs +++ b/src/server.rs @@ -1812,7 +1812,7 @@ impl ServerHandler for CodexHandler { && name != "automation_verify_pairing" && !pairing_continuation && !ticket_wait - && !tool.is_some_and(|tool| app_only_tool(tool.as_ref())) + && !tool.is_some_and(app_only_tool) && !context.ct.is_cancelled() && self .conversation_auth_error("chat_read", conversation.as_ref()) From 15e0a992e78723049838e6d04473029dd9c74c47 Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:47:17 +0100 Subject: [PATCH 066/118] test(mcp): verify unrelated long-running request cannot pin old source generation --- src/bridge/hot_reload_tests.rs | 62 ++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) diff --git a/src/bridge/hot_reload_tests.rs b/src/bridge/hot_reload_tests.rs index 73bac52f..b950ea32 100644 --- a/src/bridge/hot_reload_tests.rs +++ b/src/bridge/hot_reload_tests.rs @@ -530,3 +530,65 @@ async fn old_generation_is_released_after_draining_without_stale_snapshots() { old_task.abort(); new_task.abort(); } + +#[tokio::test] +async fn unrelated_in_flight_call_does_not_retain_a_retired_source() { + let (a1, _, task_a1) = + fixture("alpha-1", false, Duration::ZERO, Duration::ZERO).await; + let (a2, _, task_a2) = + fixture("alpha-2", false, Duration::ZERO, Duration::ZERO).await; + let (b, b_calls, task_b) = + fixture("beta", false, Duration::ZERO, Duration::from_millis(400)).await; + let mut config = crate::config::default_config(std::env::temp_dir()); + config + .mcp_servers + .insert("alpha".into(), spec(&a1, McpToolExposure::Direct)); + config + .mcp_servers + .insert("beta".into(), spec(&b, McpToolExposure::Direct)); + let runtime = connect_upstreams(&config).await.runtime; + let initial = runtime.snapshot(); + let alpha = Arc::downgrade(&initial.sources["alpha"]); + // Copy only beta's validated descriptor, just as server dispatch does. + let beta = initial + .tools + .iter() + .find(|tool| tool.name() == "beta__slow") + .unwrap() + .clone(); + drop(initial); + + let pending = tokio::spawn(async move { + beta.call( + json!({}), + &crate::config::default_config(std::env::temp_dir()), + &SessionState::new(), + ) + .await + }); + tokio::time::timeout(Duration::from_secs(2), async { + while b_calls.load(Ordering::SeqCst) == 0 { + tokio::time::sleep(Duration::from_millis(5)).await; + } + }) + .await + .unwrap(); + + let result = runtime + .reload_with_spec("alpha", spec(&a2, McpToolExposure::Direct), None) + .await + .unwrap(); + assert_eq!(result["oldCallsDrained"], true); + assert!( + alpha.upgrade().is_none(), + "a beta request must not retain alpha's retired connection" + ); + assert_eq!(pending.await.unwrap().joined_text(), "beta"); + assert_eq!( + invoke(runtime.snapshot(), "alpha__probe").await.joined_text(), + "alpha-2" + ); + task_a1.abort(); + task_a2.abort(); + task_b.abort(); +} From c89ee1007d1f098c4a6f76cd80d1d022986684bf Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:47:27 +0100 Subject: [PATCH 067/118] docs(mcp): clarify source-specific dispatch pinning and retirement --- src/bridge/hot_reload.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/bridge/hot_reload.rs b/src/bridge/hot_reload.rs index 046ec945..6a174ee5 100644 --- a/src/bridge/hot_reload.rs +++ b/src/bridge/hot_reload.rs @@ -1,8 +1,8 @@ //! Transactional replacement of one upstream MCP connection. //! -//! All model-visible tools are rebuilt as one immutable registry snapshot. A -//! dispatch keeps its snapshot for its entire call, so old generations cannot -//! be disposed while requests are using them. +//! Tool definitions are rebuilt into an immutable registry snapshot. Dispatch +//! clones only its selected tool into the call, preserving that source's old +//! generation without retaining unrelated MCP connections. use super::*; use clap::Parser; use std::collections::{HashMap, HashSet}; @@ -431,7 +431,7 @@ impl HotReloadRuntime { write_gateway_skill(&self.config, name, &sanitize(name), &funcs); } - // The old generation stays alive in any request's registry snapshot. + // The old generation stays alive in requests pinned to its tools. // On a bounded drain timeout its existing calls are NOT cancelled or // replayed; the generation retires when the last call releases it. let drain_ms = previous From da24d1ad9c882800ad70a624390b5c49ff519dc6 Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:48:05 +0100 Subject: [PATCH 068/118] style(mcp): apply remaining format hints (src/bridge/hot_reload.rs) --- src/bridge/hot_reload.rs | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/src/bridge/hot_reload.rs b/src/bridge/hot_reload.rs index 6a174ee5..a7b27c1f 100644 --- a/src/bridge/hot_reload.rs +++ b/src/bridge/hot_reload.rs @@ -393,13 +393,7 @@ impl HotReloadRuntime { .count(); } let initialization_ms = started.elapsed().as_millis() as u64; - let new = Generation::new( - spec, - service, - tools, - timeout, - old_generation + 1, - ); + let new = Generation::new(spec, service, tools, timeout, old_generation + 1); let new_version = new.version(); // Connection preparation and view construction are outside the write // lock. Compare-and-rebuild prevents concurrent distinct-source reloads From a86959440a79b4113fa4cf59b021c2765e432033 Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:48:07 +0100 Subject: [PATCH 069/118] style(mcp): apply remaining format hints (src/bridge.rs) --- src/bridge.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/bridge.rs b/src/bridge.rs index 6dae727e..198904e0 100644 --- a/src/bridge.rs +++ b/src/bridge.rs @@ -39,6 +39,7 @@ mod hot_reload; #[cfg(test)] mod hot_reload_tests; mod stderr; +mod stderr; pub(crate) use hot_reload::{Generation, HotReloadRuntime, ReloadMcpTool}; /// How long to wait for an upstream to start up and answer `tools/list` before From 115576b43fa265e754d67382ea2462e12c567d21 Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:48:36 +0100 Subject: [PATCH 070/118] fix(mcp): report retained old source generations accurately after drain --- src/bridge/hot_reload.rs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/bridge/hot_reload.rs b/src/bridge/hot_reload.rs index a7b27c1f..bbe7c311 100644 --- a/src/bridge/hot_reload.rs +++ b/src/bridge/hot_reload.rs @@ -440,6 +440,12 @@ impl HotReloadRuntime { let in_flight = previous .as_ref() .map_or(0, |old| *old.calls.lock().unwrap()); + // A selected but not yet forwarded call, an old catalog snapshot, + // or an active resource may still pin the retiring generation. + // Do not misreport that its process has already been released. + let still_referenced = previous + .as_ref() + .is_some_and(|old| Arc::strong_count(old) > 1); Ok(json!({ "source": name, "outcome": "reloaded", @@ -453,7 +459,8 @@ impl HotReloadRuntime { }, "oldCallsDrained": drained, "oldCallsStillRunning": in_flight, - "oldGenerationRetiring": !drained, + "oldGenerationStillReferenced": still_referenced, + "oldGenerationRetiring": !drained || still_referenced, "rollback": "not_required", "timingsMs": { "initializationAndReadiness": initialization_ms, From f27c9bf43a1ff217dcb584146e6c4fb313a368de Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:48:53 +0100 Subject: [PATCH 071/118] docs(mcp): describe per-tool dispatch ownership and honest draining report --- docs/MCP_HOT_RELOAD.md | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/docs/MCP_HOT_RELOAD.md b/docs/MCP_HOT_RELOAD.md index 913f8fac..a2feb807 100644 --- a/docs/MCP_HOT_RELOAD.md +++ b/docs/MCP_HOT_RELOAD.md @@ -30,13 +30,16 @@ unsupported; the operation never silently falls back to a process-wide restart. 3. The new tool definitions are validated and an immutable registry view is constructed. The new view replaces the old view in one atomic pointer swap. Concurrent distinct-source reloads rebuild against the latest view. -4. Calls already using an old registry snapshot stay pinned to that snapshot - and connection generation; write-capable calls are **never replayed**. +4. Each dispatch retains only its selected validated upstream tool and that + source's connection generation. Write-capable calls are **never replayed**; + unrelated direct/gateway sources are not retained by a long-running call. Cancellation and timeout semantics remain those of the forwarded request. -5. The old generation is released when no surviving snapshot or call retains - it. The operation reports whether active calls drained within the source's - configured `requestLimits.slowCancellationMs` interval. A drain timeout - does **not** kill or replay an in-progress side-effecting call. +5. The old generation is released when no selected old tool or catalog + snapshot retains it. The operation reports whether forwarded calls drained + within the source's configured `requestLimits.slowCancellationMs` interval. + The separate `oldGenerationStillReferenced` flag covers retained references + even when no forwarded calls remain. A drain timeout does **not** kill or + replay an in-progress side-effecting call. 6. On failure **before** the swap, the new candidate is dropped and the old view is never replaced. Errors use bounded diagnostic codes and do not echo credentials, command lines, headers, environment variables, or raw @@ -53,7 +56,8 @@ A successful result includes `source`, `outcome`, `previousGeneration`, `replacementGeneration`, old/new reported MCP server versions, readiness, counts of added/removed/changed/unchanged tool definitions, `oldCallsDrained`, `oldCallsStillRunning`, -`oldGenerationRetiring`, `rollback`, `diagnosticCode`, and measured +`oldGenerationStillReferenced`, `oldGenerationRetiring`, `rollback`, +`diagnosticCode`, and measured `timingsMs` for initialization/readiness, registry switch, draining and total reload duration. From 402c1bf1bfa31db3a5d765b30fd9d1da97b5da02 Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Thu, 19 Nov 2026 23:31:48 +0100 Subject: [PATCH 072/118] fix(mcp): remove duplicate stderr module and format bridge generation --- src/bridge.rs | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/bridge.rs b/src/bridge.rs index 198904e0..5583fcac 100644 --- a/src/bridge.rs +++ b/src/bridge.rs @@ -39,7 +39,6 @@ mod hot_reload; #[cfg(test)] mod hot_reload_tests; mod stderr; -mod stderr; pub(crate) use hot_reload::{Generation, HotReloadRuntime, ReloadMcpTool}; /// How long to wait for an upstream to start up and answer `tools/list` before @@ -540,9 +539,8 @@ pub async fn connect_upstreams(config: &AppConfig) -> Bridge { let functions = gateway_functions(&tools); write_gateway_skill(config, name, &sanitize(name), &functions); } - let generation = hot_reload::Generation::new( - spec.clone(), service, tools, timeout, 1, - ); + let generation = + hot_reload::Generation::new(spec.clone(), service, tools, timeout, 1); sources.insert(name.clone(), generation); report.push(format!("{name} -> {} ({count} tool(s))", mode.as_str())); tracing::info!(source = %name, %count, exposure = mode.as_str(), "MCP source connected"); From bfb4ea28e033020f0eece13a73347603950c6c87 Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Thu, 19 Nov 2026 23:31:51 +0100 Subject: [PATCH 073/118] style(mcp): apply CI rustfmt changes to live hot reload tests --- src/bridge/hot_reload_tests.rs | 39 +++++++++++++++++++++------------- 1 file changed, 24 insertions(+), 15 deletions(-) diff --git a/src/bridge/hot_reload_tests.rs b/src/bridge/hot_reload_tests.rs index b950ea32..be24d6c0 100644 --- a/src/bridge/hot_reload_tests.rs +++ b/src/bridge/hot_reload_tests.rs @@ -506,12 +506,12 @@ async fn direct_name_collisions_are_not_ambiguous_after_reload() { #[tokio::test] async fn old_generation_is_released_after_draining_without_stale_snapshots() { - let (old_url, _, old_task) = - fixture("old", false, Duration::ZERO, Duration::ZERO).await; - let (new_url, _, new_task) = - fixture("new", true, Duration::ZERO, Duration::ZERO).await; + let (old_url, _, old_task) = fixture("old", false, Duration::ZERO, Duration::ZERO).await; + let (new_url, _, new_task) = fixture("new", true, Duration::ZERO, Duration::ZERO).await; let mut config = crate::config::default_config(std::env::temp_dir()); - config.mcp_servers.insert("alpha".into(), spec(&old_url, McpToolExposure::Direct)); + config + .mcp_servers + .insert("alpha".into(), spec(&old_url, McpToolExposure::Direct)); let bridge = connect_upstreams(&config).await; let runtime = bridge.runtime.clone(); let first = runtime.snapshot(); @@ -521,22 +521,29 @@ async fn old_generation_is_released_after_draining_without_stale_snapshots() { drop(bridge); assert!(weak.upgrade().is_some()); - let result = runtime.reload_with_spec( - "alpha", spec(&new_url, McpToolExposure::Direct), None - ).await.unwrap(); + let result = runtime + .reload_with_spec("alpha", spec(&new_url, McpToolExposure::Direct), None) + .await + .unwrap(); assert_eq!(result["oldCallsDrained"], true); - assert!(weak.upgrade().is_none(), "retired service generation leaked"); - assert_eq!(invoke(runtime.snapshot(), "alpha__probe").await.joined_text(), "new"); + assert!( + weak.upgrade().is_none(), + "retired service generation leaked" + ); + assert_eq!( + invoke(runtime.snapshot(), "alpha__probe") + .await + .joined_text(), + "new" + ); old_task.abort(); new_task.abort(); } #[tokio::test] async fn unrelated_in_flight_call_does_not_retain_a_retired_source() { - let (a1, _, task_a1) = - fixture("alpha-1", false, Duration::ZERO, Duration::ZERO).await; - let (a2, _, task_a2) = - fixture("alpha-2", false, Duration::ZERO, Duration::ZERO).await; + let (a1, _, task_a1) = fixture("alpha-1", false, Duration::ZERO, Duration::ZERO).await; + let (a2, _, task_a2) = fixture("alpha-2", false, Duration::ZERO, Duration::ZERO).await; let (b, b_calls, task_b) = fixture("beta", false, Duration::ZERO, Duration::from_millis(400)).await; let mut config = crate::config::default_config(std::env::temp_dir()); @@ -585,7 +592,9 @@ async fn unrelated_in_flight_call_does_not_retain_a_retired_source() { ); assert_eq!(pending.await.unwrap().joined_text(), "beta"); assert_eq!( - invoke(runtime.snapshot(), "alpha__probe").await.joined_text(), + invoke(runtime.snapshot(), "alpha__probe") + .await + .joined_text(), "alpha-2" ); task_a1.abort(); From a0c72d3582578400e69cafb9053db8c25ddac32c Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Thu, 19 Nov 2026 23:59:46 +0100 Subject: [PATCH 074/118] fix(mcp): satisfy strict Clippy in per-source dispatch fallback --- src/server.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/server.rs b/src/server.rs index 792fc2cb..770b8647 100644 --- a/src/server.rs +++ b/src/server.rs @@ -848,7 +848,7 @@ impl ServerHandler for CodexHandler { .iter() .find(|tool| tool.name() == name) .map(|tool| tool.as_ref()) - .or_else(|| bridge_tool.as_deref()); + .or(bridge_tool.as_deref()); let ticket_wait = name == TicketWait::NAME && tool.is_some(); let model_call = !tool.is_some_and(app_only_tool); let mut task_conversation = conversation.clone(); From cc92b3d413e04c5cd56fc82e72e1874e7e456b02 Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:13:26 +0100 Subject: [PATCH 075/118] fix(mcp): preserve safe startup report wording for catalog and unsupported transports --- src/bridge.rs | 25 ++++++++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/src/bridge.rs b/src/bridge.rs index 5583fcac..47626fc3 100644 --- a/src/bridge.rs +++ b/src/bridge.rs @@ -542,14 +542,33 @@ pub async fn connect_upstreams(config: &AppConfig) -> Bridge { let generation = hot_reload::Generation::new(spec.clone(), service, tools, timeout, 1); sources.insert(name.clone(), generation); - report.push(format!("{name} -> {} ({count} tool(s))", mode.as_str())); + let visibility = if mode == McpToolExposure::Catalog { + " private" + } else { + "" + }; + report.push(format!( + "{name} -> {} ({count}{visibility} tool(s))", + mode.as_str() + )); tracing::info!(source = %name, %count, exposure = mode.as_str(), "MCP source connected"); } Err(_) => { // Upstream configuration can contain private header or command // values; do not echo a failed spawn/handshake error to clients. - report.push(format!("{name} -> FAILED (initialization)")); - tracing::warn!(source = %name, "MCP source failed initialization"); + // An unsupported transport type is a safe, useful static + // diagnostic and should not be hidden as an initialization + // failure; neither diagnostic includes the configured URL. + let legacy_transport = spec.transport.as_deref().is_some_and(|kind| { + matches!(kind.to_ascii_lowercase().as_str(), "sse" | "websocket" | "ws") + }); + if legacy_transport { + report.push(format!("{name} -> not supported (transport)")); + tracing::warn!(source = %name, "MCP source transport is not supported"); + } else { + report.push(format!("{name} -> FAILED (initialization)")); + tracing::warn!(source = %name, "MCP source failed initialization"); + } } } } From 8833c5d3787806135d7826eab25295df3a44f3df Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:14:08 +0100 Subject: [PATCH 076/118] fix(mcp): register drain waiter before reading in-flight count --- src/bridge/hot_reload.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/bridge/hot_reload.rs b/src/bridge/hot_reload.rs index bbe7c311..a46c0a2f 100644 --- a/src/bridge/hot_reload.rs +++ b/src/bridge/hot_reload.rs @@ -73,10 +73,16 @@ impl Generation { async fn wait_for_calls(&self, limit: Duration) -> bool { tokio::time::timeout(limit, async { loop { + // Register the waiter before checking the counter. Otherwise + // the last call can finish between the check and registration, + // losing its wakeup and spuriously timing out the drain. + let notified = self.drained.notified(); + tokio::pin!(notified); + notified.as_mut().enable(); if *self.calls.lock().unwrap() == 0 { break; } - self.drained.notified().await; + notified.await; } }) .await From c85264f8a1e8df9b34c7542df9c5adbbd3398647 Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:21:15 +0100 Subject: [PATCH 077/118] style(mcp): apply exact rustfmt fix to unsupported-transport report --- src/bridge.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/bridge.rs b/src/bridge.rs index 47626fc3..8cb16d98 100644 --- a/src/bridge.rs +++ b/src/bridge.rs @@ -560,7 +560,10 @@ pub async fn connect_upstreams(config: &AppConfig) -> Bridge { // diagnostic and should not be hidden as an initialization // failure; neither diagnostic includes the configured URL. let legacy_transport = spec.transport.as_deref().is_some_and(|kind| { - matches!(kind.to_ascii_lowercase().as_str(), "sse" | "websocket" | "ws") + matches!( + kind.to_ascii_lowercase().as_str(), + "sse" | "websocket" | "ws" + ) }); if legacy_transport { report.push(format!("{name} -> not supported (transport)")); From 8a1540e8ba99f14393419f76e171b64567c10283 Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:50:43 +0100 Subject: [PATCH 078/118] test(mcp): add isolated real stdio fixture with distinct process identity --- scripts/fixtures/hot-reload-stdio-mcp.mjs | 49 +++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 scripts/fixtures/hot-reload-stdio-mcp.mjs diff --git a/scripts/fixtures/hot-reload-stdio-mcp.mjs b/scripts/fixtures/hot-reload-stdio-mcp.mjs new file mode 100644 index 00000000..48a41325 --- /dev/null +++ b/scripts/fixtures/hot-reload-stdio-mcp.mjs @@ -0,0 +1,49 @@ +// No dependencies or network: isolated MCP stdio child for Rust hot-reload tests. +// Every invocation is a separate operating-system process. +import { createInterface } from 'node:readline'; +import { writeFileSync } from 'node:fs'; + +const version = process.argv[2] ?? 'old'; +const pid = process.pid; +const input = createInterface({ input: process.stdin, crlfDelay: Infinity }); + +function respond(id, result) { + process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id, result }) + '\n'); +} +function tool(name, description) { + return { name, description, inputSchema: { type: 'object', properties: {}, additionalProperties: false } }; +} +function replyToTool(id) { + respond(id, { content: [{ type: 'text', text: version + ':' + pid }], isError: false }); +} + +for await (const line of input) { + let request; + try { request = JSON.parse(line); } catch { continue; } + if (!request || !Object.hasOwn(request, 'id')) continue; + const { id, method } = request; + if (method === 'initialize') { + respond(id, { + protocolVersion: request.params?.protocolVersion ?? '2025-03-26', + capabilities: { tools: {} }, + serverInfo: { name: 'isolated-hot-reload-stdio-fixture', version }, + }); + } else if (method === 'tools/list') { + const tools = [tool('probe', 'Version probe ' + version), tool('slow', 'Slow probe ' + version)]; + if (version === 'new') tools.push(tool('new_tool', 'New tool in replacement generation')); + respond(id, { tools }); + } else if (method === 'tools/call') { + if (request.params?.name === 'slow') { + if (process.env.HOT_RELOAD_SLOW_MARKER_FILE) { + writeFileSync(process.env.HOT_RELOAD_SLOW_MARKER_FILE, String(pid)); + } + setTimeout(() => replyToTool(id), 300); + } else { + replyToTool(id); + } + } else if (method === 'ping') { + respond(id, {}); + } else { + process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id, error: { code: -32601, message: 'Method not found' } }) + '\n'); + } +} From d2c4f64e7d6e49a8333c20b9bd4441e99722ef9d Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:51:09 +0100 Subject: [PATCH 079/118] test(mcp): verify real stdio process replacement, drain and rollback on isolated fixtures --- src/bridge/hot_reload_tests.rs | 173 +++++++++++++++++++++++++++++++++ 1 file changed, 173 insertions(+) diff --git a/src/bridge/hot_reload_tests.rs b/src/bridge/hot_reload_tests.rs index be24d6c0..e2f7e033 100644 --- a/src/bridge/hot_reload_tests.rs +++ b/src/bridge/hot_reload_tests.rs @@ -601,3 +601,176 @@ async fn unrelated_in_flight_call_does_not_retain_a_retired_source() { task_a2.abort(); task_b.abort(); } + + +fn isolated_stdio_spec(version: &str) -> crate::types::McpServerSpec { + let fixture = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("scripts") + .join("fixtures") + .join("hot-reload-stdio-mcp.mjs"); + crate::types::McpServerSpec { + command: Some("node".into()), + args: vec![fixture.to_string_lossy().into_owned(), version.into()], + mode: Some(McpToolExposure::Direct), + startup_timeout_sec: Some(8.0), + ..Default::default() + } +} + +fn stdio_process_id(result: ToolResult, expected_version: &str) -> u32 { + assert!(!result.is_error, "stdio call failed: {}", result.joined_text()); + let response = result.joined_text(); + let (version, pid) = response + .trim() + .split_once(':') + .unwrap_or_else(|| panic!("invalid stdio fixture response: {response}")); + assert_eq!(version, expected_version); + pid.parse().expect("stdio fixture process id must be numeric") +} + +#[tokio::test] +async fn isolated_real_stdio_process_reload_preserves_unrelated_sources() { + // This fixture actually spawns three independent OS processes through the + // production TokioChildProcess transport; no live Codexify is involved. + let directory = tempfile::tempdir().unwrap(); + let started = directory.path().join("slow_started"); + let mut old_spec = isolated_stdio_spec("old"); + old_spec.env.insert( + "HOT_RELOAD_SLOW_MARKER_FILE".into(), + started.to_string_lossy().into_owned(), + ); + + let mut config = crate::config::default_config(std::env::temp_dir()); + config.mcp_servers.insert("alpha".into(), old_spec); + config + .mcp_servers + .insert("beta".into(), isolated_stdio_spec("beta")); + config + .mcp_servers + .insert("gamma".into(), isolated_stdio_spec("gamma")); + let bridge = connect_upstreams(&config).await; + assert_eq!( + bridge.runtime.snapshot().sources.len(), + 3, + "all isolated stdio fixtures must start: {:?}", + bridge.report + ); + let runtime = bridge.runtime.clone(); + drop(bridge); + + let initial = runtime.snapshot(); + let retired = Arc::downgrade(&initial.sources["alpha"]); + let old_probe = initial + .tools + .iter() + .find(|tool| tool.name() == "alpha__probe") + .unwrap() + .clone(); + let old_slow = initial + .tools + .iter() + .find(|tool| tool.name() == "alpha__slow") + .unwrap() + .clone(); + drop(initial); + let config_for_call = crate::config::default_config(std::env::temp_dir()); + let original_pid = stdio_process_id( + old_probe.call(json!({}), &config_for_call, &SessionState::new()).await, + "old", + ); + let beta_pid = stdio_process_id(invoke(runtime.snapshot(), "beta__probe").await, "beta"); + let gamma_pid = stdio_process_id(invoke(runtime.snapshot(), "gamma__probe").await, "gamma"); + + let pending = tokio::spawn(async move { + old_slow + .call( + json!({}), + &crate::config::default_config(std::env::temp_dir()), + &SessionState::new(), + ) + .await + }); + // The marker is written by the actual old process when it receives the + // slow request, making this test independent of host scheduling. + tokio::time::timeout(Duration::from_secs(4), async { + while !started.exists() { + tokio::time::sleep(Duration::from_millis(5)).await; + } + }) + .await + .expect("old stdio process did not begin the slow call"); + + let result = runtime + .reload_with_spec("alpha", isolated_stdio_spec("new"), None) + .await + .unwrap(); + assert_eq!(result["previousVersion"], "old"); + assert_eq!(result["replacementVersion"], "new"); + assert_eq!(result["previousGeneration"], 1); + assert_eq!(result["replacementGeneration"], 2); + assert_eq!(result["toolChanges"]["added"], 1); + assert_eq!(result["oldCallsDrained"], true); + assert_eq!(stdio_process_id(pending.await.unwrap(), "old"), original_pid); + assert_eq!( + stdio_process_id( + old_probe.call(json!({}), &config_for_call, &SessionState::new()).await, + "old", + ), + original_pid, + "a pinned retired generation must remain callable until released" + ); + let new_pid = stdio_process_id(invoke(runtime.snapshot(), "alpha__probe").await, "new"); + assert_ne!(new_pid, original_pid, "replacement must be a new OS process"); + assert_eq!( + stdio_process_id(invoke(runtime.snapshot(), "alpha__new_tool").await, "new"), + new_pid + ); + assert_eq!( + stdio_process_id(invoke(runtime.snapshot(), "beta__probe").await, "beta"), + beta_pid, + "beta must not reconnect" + ); + assert_eq!( + stdio_process_id(invoke(runtime.snapshot(), "gamma__probe").await, "gamma"), + gamma_pid, + "gamma must not reconnect" + ); + + let mut invalid_spec = isolated_stdio_spec("broken"); + invalid_spec.command = Some("codexify-nonexistent-hot-reload-fixture".into()); + assert_eq!( + runtime + .reload_with_spec("alpha", invalid_spec, None) + .await + .err(), + Some("INITIALIZE_FAILED") + ); + assert_eq!( + stdio_process_id(invoke(runtime.snapshot(), "alpha__probe").await, "new"), + new_pid, + "an unsuccessful replacement must preserve the healthy process" + ); + + drop(old_probe); + tokio::task::yield_now().await; + assert!( + retired.upgrade().is_none(), + "the retired generation must be released after its last handle drops" + ); + + let repeated = runtime + .reload_with_spec("alpha", isolated_stdio_spec("new"), None) + .await + .unwrap(); + assert_eq!(repeated["previousGeneration"], 2); + assert_eq!(repeated["replacementGeneration"], 3); + assert_eq!(repeated["toolChanges"]["unchanged"], 3); + assert_eq!( + stdio_process_id(invoke(runtime.snapshot(), "beta__probe").await, "beta"), + beta_pid + ); + assert_eq!( + stdio_process_id(invoke(runtime.snapshot(), "gamma__probe").await, "gamma"), + gamma_pid + ); +} From 133b0e26c18f2685ac2aea5a04589a5ea7c6b41e Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:53:57 +0100 Subject: [PATCH 080/118] test(mcp): run isolated stdio process reload in Windows and macOS service CI --- src/bridge/hot_reload_tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/bridge/hot_reload_tests.rs b/src/bridge/hot_reload_tests.rs index e2f7e033..b8dfaa88 100644 --- a/src/bridge/hot_reload_tests.rs +++ b/src/bridge/hot_reload_tests.rs @@ -629,7 +629,7 @@ fn stdio_process_id(result: ToolResult, expected_version: &str) -> u32 { } #[tokio::test] -async fn isolated_real_stdio_process_reload_preserves_unrelated_sources() { +async fn service_isolated_real_stdio_process_reload_preserves_unrelated_sources() { // This fixture actually spawns three independent OS processes through the // production TokioChildProcess transport; no live Codexify is involved. let directory = tempfile::tempdir().unwrap(); From 17b0d3105d02fc8ffc149583e66e57918d7108b7 Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:59:23 +0100 Subject: [PATCH 081/118] test(mcp): verify retired stdio OS child exits and apply CI rustfmt --- src/bridge/hot_reload_tests.rs | 50 +++++++++++++++++++++++++++++----- 1 file changed, 43 insertions(+), 7 deletions(-) diff --git a/src/bridge/hot_reload_tests.rs b/src/bridge/hot_reload_tests.rs index b8dfaa88..a029da4d 100644 --- a/src/bridge/hot_reload_tests.rs +++ b/src/bridge/hot_reload_tests.rs @@ -602,7 +602,6 @@ async fn unrelated_in_flight_call_does_not_retain_a_retired_source() { task_b.abort(); } - fn isolated_stdio_spec(version: &str) -> crate::types::McpServerSpec { let fixture = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) .join("scripts") @@ -618,14 +617,30 @@ fn isolated_stdio_spec(version: &str) -> crate::types::McpServerSpec { } fn stdio_process_id(result: ToolResult, expected_version: &str) -> u32 { - assert!(!result.is_error, "stdio call failed: {}", result.joined_text()); + assert!( + !result.is_error, + "stdio call failed: {}", + result.joined_text() + ); let response = result.joined_text(); let (version, pid) = response .trim() .split_once(':') .unwrap_or_else(|| panic!("invalid stdio fixture response: {response}")); assert_eq!(version, expected_version); - pid.parse().expect("stdio fixture process id must be numeric") + pid.parse() + .expect("stdio fixture process id must be numeric") +} + +async fn stdio_process_still_alive(pid: u32) -> bool { + // Signal 0 checks existence without terminating or signaling a process. + tokio::process::Command::new("node") + .arg("-e") + .arg("try { process.kill(Number(process.argv[1]), 0); } catch { process.exit(1); }") + .arg(pid.to_string()) + .status() + .await + .is_ok_and(|status| status.success()) } #[tokio::test] @@ -675,7 +690,9 @@ async fn service_isolated_real_stdio_process_reload_preserves_unrelated_sources( drop(initial); let config_for_call = crate::config::default_config(std::env::temp_dir()); let original_pid = stdio_process_id( - old_probe.call(json!({}), &config_for_call, &SessionState::new()).await, + old_probe + .call(json!({}), &config_for_call, &SessionState::new()) + .await, "old", ); let beta_pid = stdio_process_id(invoke(runtime.snapshot(), "beta__probe").await, "beta"); @@ -710,17 +727,25 @@ async fn service_isolated_real_stdio_process_reload_preserves_unrelated_sources( assert_eq!(result["replacementGeneration"], 2); assert_eq!(result["toolChanges"]["added"], 1); assert_eq!(result["oldCallsDrained"], true); - assert_eq!(stdio_process_id(pending.await.unwrap(), "old"), original_pid); + assert_eq!( + stdio_process_id(pending.await.unwrap(), "old"), + original_pid + ); assert_eq!( stdio_process_id( - old_probe.call(json!({}), &config_for_call, &SessionState::new()).await, + old_probe + .call(json!({}), &config_for_call, &SessionState::new()) + .await, "old", ), original_pid, "a pinned retired generation must remain callable until released" ); let new_pid = stdio_process_id(invoke(runtime.snapshot(), "alpha__probe").await, "new"); - assert_ne!(new_pid, original_pid, "replacement must be a new OS process"); + assert_ne!( + new_pid, original_pid, + "replacement must be a new OS process" + ); assert_eq!( stdio_process_id(invoke(runtime.snapshot(), "alpha__new_tool").await, "new"), new_pid @@ -751,12 +776,23 @@ async fn service_isolated_real_stdio_process_reload_preserves_unrelated_sources( "an unsuccessful replacement must preserve the healthy process" ); + assert!( + stdio_process_still_alive(original_pid).await, + "retiring process must remain alive while a pinned old handle exists" + ); drop(old_probe); tokio::task::yield_now().await; assert!( retired.upgrade().is_none(), "the retired generation must be released after its last handle drops" ); + tokio::time::timeout(Duration::from_secs(5), async { + while stdio_process_still_alive(original_pid).await { + tokio::time::sleep(Duration::from_millis(25)).await; + } + }) + .await + .expect("retired OS child process remained alive after the last handle dropped"); let repeated = runtime .reload_with_spec("alpha", isolated_stdio_spec("new"), None) From 832ecde4d774168dc4dc71ac679c11b4ca90265b Mon Sep 17 00:00:00 2001 From: tomi Date: Fri, 20 Nov 2026 01:19:44 +0100 Subject: [PATCH 082/118] fix(browser): verify connector permissions against current settings UI --- browser-companion/src/account-settings.ts | 50 ++++++++-- browser-companion/src/chatgpt-driver.ts | 9 +- .../tests/account-settings.test.ts | 48 ++++++---- .../connector-permission-regression.test.ts | 93 +++++++++++++++++++ 4 files changed, 172 insertions(+), 28 deletions(-) create mode 100644 browser-companion/tests/connector-permission-regression.test.ts diff --git a/browser-companion/src/account-settings.ts b/browser-companion/src/account-settings.ts index 2683f885..2da73d27 100644 --- a/browser-companion/src/account-settings.ts +++ b/browser-companion/src/account-settings.ts @@ -186,6 +186,15 @@ async function markRefreshButton(page:Page):Promise { async function allowAllChoice(page:Page,signal?:AbortSignal) { const radios=page.locator('[role="radio"],input[type="radio"]').filter({visible:true}); + // Some versions render the permission choices only after opening the + // permission selector. Never guess which other button opens that selector. + if(await observeReadOnly(radios.count(),signal)===0){ + const trigger=page.locator('[data-action="plugin-permissions"],[data-testid="plugin-permission-trigger"]').filter({visible:true}); + if(await observeReadOnly(trigger.count(),signal)===1) { + signal?.throwIfAborted(); + await trigger.click({timeout:3_000,signal}); + } + } await radios.first().waitFor({state:"visible",timeout:10_000,signal}); if(await observeReadOnly(radios.count(),signal)!==4)throw selectorDrift("ChatGPT permission choices changed; Allow all was not selected"); const choice=radios.nth(3); @@ -242,7 +251,7 @@ export async function identifyConnectorApp(page:Page,connectorName:string,expect return appId; } -async function connectorPage(page:Page,appId:string,account:string,permissions:boolean,signal?:AbortSignal) { +async function connectorPage(page:Page,appId:string,account:string,permissions:boolean,signal?:AbortSignal,reload=false) { signal?.throwIfAborted(); const url=`https://chatgpt.com/settings/plugins-settings/plugin_${appId}${permissions?'/permissions':''}`; const assertPage=async()=>{ @@ -250,7 +259,9 @@ async function connectorPage(page:Page,appId:string,account:string,permissions:b if(new URL(page.url()).origin!=="https://chatgpt.com"||new URL(page.url()).pathname!==new URL(url).pathname)throw selectorDrift("ChatGPT changed the plugin page during connector maintenance"); if((await readChatGptAccount(page,signal)).fingerprint!==account)throw selectorDrift("ChatGPT account changed during connector maintenance"); }; - await navigatePage(page,url,{timeout:30_000,signal}); + // A reload is valid only when this is already the exact target page; on a + // different page, ordinary navigation also produces a fresh document. + await navigatePage(page,url,{timeout:30_000,signal,reload:reload&&page.url()===url}); await assertPage(); return assertPage; } @@ -337,14 +348,24 @@ export async function requestConnectorToolRefresh(page:Page,appId:string,name:st } export async function verifyConnectorAllowAll(page:Page,appId:string,account:string,signal?:AbortSignal):Promise { - await connectorPage(page,appId,account,true,signal); + // Do not count the radio's optimistic checked state as persisted permission. + // A new document must independently confirm the selection on this account. + await connectorPage(page,appId,account,true,signal,true); if(!await (await allowAllChoice(page,signal)).checked())throw selectorDrift("Allow all tools was not confirmed after reloading plugin settings"); } export async function connectorPermissionSummary(page:Page,signal?:AbortSignal):Promise<{summary:string;allowAll:boolean}|null> { - return observeReadOnly(page.evaluate(()=>{ + // These are *selected value* labels, not text to search for anywhere on the + // page: help text can describe an unselected "Allow all" option as well. + const allowAllLabels=[ + "Allow all actions","Allow all tools","Never ask", + "Permitir todo","Tout autoriser","Να επιτρέπονται όλα", + "Consenti tutto","Dovoli vsa dejanja", + ]; + return observeReadOnly(page.evaluate(labels=>{ const candidates=new Set(); - const direct=[...document.querySelectorAll('[data-permission],[data-action="plugin-permissions"],a[href$="/permissions"]')].filter(node=>node.getClientRects().length>0); + const directState=[...document.querySelectorAll('[data-permission],[data-current-permission]')].filter(node=>node.getClientRects().length>0); + const direct=directState.length?directState:[...document.querySelectorAll('[data-action="plugin-permissions"],a[href$="/permissions"]')].filter(node=>node.getClientRects().length>0); for(const node of direct)candidates.add(node); if(!candidates.size)for(const node of document.querySelectorAll('div,section')) { const controls=[...node.querySelectorAll('button,[role="button"]')].filter(button=>button.getClientRects().length>0); @@ -360,15 +381,28 @@ export async function connectorPermissionSummary(page:Page,signal?:AbortSignal): } if(candidates.size!==1)return null; const control=[...candidates][0]!; - return {summary:(control.textContent??'').normalize('NFKC').replace(/\s+/g,' ').trim(),allowAll:control.getAttribute('data-permission')==='allow_all'}; - }),signal); + const summary=(control.textContent??'').normalize('NFKC').replace(/\s+/g,' ').trim(); + const permission=control.getAttribute('data-permission')??control.getAttribute('data-current-permission'); + const leaves:string[]=[]; + const walker=document.createTreeWalker(control,NodeFilter.SHOW_TEXT); + while(walker.nextNode()){ + const text=walker.currentNode.textContent?.normalize('NFKC').replace(/\s+/g,' ').trim(); + if(text&&walker.currentNode.parentElement?.getClientRects().length)leaves.push(text); + } + const selected=leaves.at(-1)?.toLocaleLowerCase('en-US'); + const marked=permission==='allow_all'||permission==='full_access'; + // Explicit non-allow permission metadata always wins over descriptive text. + return {summary,allowAll:marked||(permission===null&&Boolean(selected&&labels.some(label=>label.toLocaleLowerCase('en-US')===selected)))}; + },allowAllLabels),signal); } export type PermissionWitness={summary?:string;remember:(summary:string)=>void}; export async function inspectConnectorSettings(page:Page,appId:string,name:string,account:string,signal?:AbortSignal) { if(!/^asdk_app_[A-Za-z0-9_]{1,128}$/.test(appId))throw selectorDrift("Invalid connector App ID"); traceRefresh("open settings"); - const assertPage=await connectorPage(page,appId,account,false,signal); + // The same URL can still show stale React state after permissions change in + // another ChatGPT tab. Only a fresh document can prove current permissions. + const assertPage=await connectorPage(page,appId,account,false,signal,true); traceRefresh("settings opened"); // The document can finish while settings still shows only a loading shell. // Hydration gets a bounded read inside the coordinator's existing phase diff --git a/browser-companion/src/chatgpt-driver.ts b/browser-companion/src/chatgpt-driver.ts index 0c00bfb6..447aca9c 100644 --- a/browser-companion/src/chatgpt-driver.ts +++ b/browser-companion/src/chatgpt-driver.ts @@ -632,15 +632,16 @@ export class ChatGptBrowserDriver implements BrowserDriver { void interrupted.catch(()=>{}); // Cancellation during preparation is handled by its bounded phase. try { const before=await phase("Inspect connector settings",(page,account,operationSignal)=>inspectConnectorSettings(page,appId,name,account.fingerprint,operationSignal)); - const knownSummary=this.connectorApps.getAllowAllSummary(expectedAccount!,name); - const needsVerification=!before?.allowAll&&(!knownSummary||before?.summary!==knownSummary); + // A cached label is only a hint for diagnostics, never an authorization + // proof. Require a fresh, unambiguous permission state on this account. + const needsVerification=before?.allowAll!==true; let permissionChanged=false; if(needsVerification)permissionChanged=await phase("Verify connector permission",(page,account,operationSignal)=>setConnectorAllowAll(page,appId,account.fingerprint,operationSignal)); observation=await phase("Start connector refresh",async(page,account,operationSignal)=>{ if(needsVerification)await verifyConnectorAllowAll(page,appId,account.fingerprint,operationSignal); const current=await inspectConnectorSettings(page,appId,name,account.fingerprint,operationSignal); - if(!needsVerification&&!current?.allowAll&&(!knownSummary||current?.summary!==knownSummary))throw new BrowserCompanionError("Connector permission changed before refresh","external_interference"); - if(current?.summary)this.connectorApps.rememberAllowAllSummary(account.fingerprint,name,current.summary); + if(current?.allowAll!==true)throw new BrowserCompanionError("Connector permission could not be positively verified before refresh","external_interference"); + if(current.summary)this.connectorApps.rememberAllowAllSummary(account.fingerprint,name,current.summary); return beginConnectorToolRefresh(page,appId,name,account.fingerprint,operationSignal); }); // The coordinator retains the shared window through confirmation and the diff --git a/browser-companion/tests/account-settings.test.ts b/browser-companion/tests/account-settings.test.ts index 8da0a6fe..d3dea8d5 100644 --- a/browser-companion/tests/account-settings.test.ts +++ b/browser-companion/tests/account-settings.test.ts @@ -41,7 +41,8 @@ test.skipIf(process.env.CODEXIFY_TEST_BROWSER_COMPANION_CHROME!=="1")("passive p const browser=await chromium.launch({executablePath,headless:true}); try { const context=await browser.newContext();const page=await context.newPage();let permission='read_only',refreshes=0,deletes=0,billingReads=0,failConnector=false,fastRefresh=false,replaceRefresh=false,refreshDelay=300,permissionVisits=0;const visits:string[]=[]; - let planAccount='fixture-account',permissionLabel='Permiso',allowLabel='Permitir todo',originalHtml='
',sessionAvailable=true; + let planAccount='fixture-account',permissionLabel='Permiso',allowLabel='Permitir todo',originalHtml='
',sessionAvailable=true,collapsedPermissions=false; + let permissionMetadata:string|undefined,displayedPermission:string|undefined; const witness:{summary?:string;remember:(summary:string)=>void}={remember:summary=>witness.summary=summary}; await page.context().route('https://chatgpt.com/**',async route=>{ const path=new URL(route.request().url()).pathname; @@ -49,12 +50,12 @@ test.skipIf(process.env.CODEXIFY_TEST_BROWSER_COMPANION_CHROME!=="1")("passive p if(path==='/api/auth/session')return route.fulfill({json:sessionAvailable?{user:{id:'fixture-user'},account:{id:new URL(route.request().frame().page().url()).pathname==='/settings/billing'?planAccount:'fixture-account',planType:'pro',structure:'personal'}}:{}}); if(path==='/settings/billing'){billingReads++;return route.fulfill({contentType:'text/html; charset=utf-8',body:'

ChatGPT Pro 200

'});} if(path==='/c/original')return route.fulfill({contentType:'text/html; charset=utf-8',body:originalHtml}); - if(path==='/set-permission'){permission='allow_all';return route.fulfill({json:{ok:true}});} + if(path==='/set-permission'){permission='allow_all';permissionMetadata=undefined;displayedPermission=undefined;return route.fulfill({json:{ok:true}});} if(path==='/refresh'){refreshes++;return route.fulfill({json:{ok:true}});} if(path==='/delete'){deletes++;return route.fulfill({json:{ok:true}});} if(path==='/')return route.fulfill({contentType:'text/html; charset=utf-8',body:'
Fixture connector
'}); - if(path.endsWith('/permissions')){permissionVisits++;return route.fulfill({contentType:'text/html; charset=utf-8',body:`

Permissions

${['Preguntar','Solo lectura','Bajo riesgo','Permitir todo'].map((label,index)=>`
${label}
`).join('')}`});} - return route.fulfill({contentType:'text/html; charset=utf-8',body:`

Fixture connector

${permissionLabel}Elegir permisos${permission==='allow_all'?allowLabel:'Solo lectura'}
Nombre
Descripción
Actualizar herramientas
Eliminar
`}); + if(path.endsWith('/permissions')){permissionVisits++;const choices=['Preguntar','Solo lectura','Bajo riesgo','Permitir todo'].map((label,index)=>`
${label}
`).join('');return route.fulfill({contentType:'text/html; charset=utf-8',body:`

Permissions

${collapsedPermissions?'':''}`});} + return route.fulfill({contentType:'text/html; charset=utf-8',body:`

Fixture connector

${permissionLabel}Elegir permisos${displayedPermission??(permission==='allow_all'?allowLabel:'Solo lectura')}
Nombre
Descripción
Actualizar herramientas
Eliminar
`}); }); await page.goto('https://chatgpt.com/c/original'); const plan=await readBillingPlan(page);expect(plan.label).toBe('Pro 20x'); @@ -62,7 +63,7 @@ test.skipIf(process.env.CODEXIFY_TEST_BROWSER_COMPANION_CHROME!=="1")("passive p expect(permission).toBe('allow_all');expect(refreshes).toBe(1);expect(deletes).toBe(0); const beforePermission=permissionVisits;visits.length=0; const again=await refreshConnectorTools(page,'Fixture connector',undefined,undefined,'asdk_app_fixture',witness);expect(again.permissionChanged).toBeFalse();expect(refreshes).toBe(2);expect(deletes).toBe(0); - expect(permissionVisits).toBe(beforePermission);expect(visits).toEqual([]); // Already on the verified settings page. + expect(permissionVisits).toBe(beforePermission);expect(visits).toEqual(['/settings/plugins-settings/plugin_asdk_app_fixture']); // A fresh settings document validates the grant. fastRefresh=true;replaceRefresh=true;await page.reload();await refreshConnectorTools(page,'Fixture connector',undefined,undefined,'asdk_app_fixture',witness);fastRefresh=false;replaceRefresh=false;expect(refreshes).toBe(3); await page.goto('https://chatgpt.com/c/original'); let owned=false,beginCalls=0,endCalls=0; @@ -77,14 +78,15 @@ test.skipIf(process.env.CODEXIFY_TEST_BROWSER_COMPANION_CHROME!=="1")("passive p await driver.accountPlan('startup-two');expect(billingReads-before).toBe(0);expect(page.url()).toBe(original); await driver.refreshConnector('Fixture connector');expect(page.url()).toBe(original);expect(refreshes).toBe(4); const permissionBeforeCached=permissionVisits;visits.length=0; - await driver.refreshConnector('Fixture connector');expect(visits).toEqual(['/settings/plugins-settings/plugin_asdk_app_fixture','/c/original']); + await driver.refreshConnector('Fixture connector');expect(visits).toEqual(['/settings/plugins-settings/plugin_asdk_app_fixture','/settings/plugins-settings/plugin_asdk_app_fixture','/c/original']); expect(permissionVisits).toBe(permissionBeforeCached);expect(refreshes).toBe(5); - // Completion can outlast one UI phase, while retaining exclusive ownership. - const coordinator=new SingleWindowCoordinator(driver,protocolBuild('queued-refresh-test'),{operationMs:1500,cleanupMs:100,hardStopMs:100}); + // Maintenance still owns the tab while refresh finishes. Give the fixture + // realistic Windows Chrome navigation budgets; ownership is the invariant. + const coordinator=new SingleWindowCoordinator(driver,protocolBuild('queued-refresh-test'),{operationMs:10_000,cleanupMs:500,hardStopMs:250}); refreshDelay=2200; const pendingRefresh=coordinator.refreshConnector('Fixture connector'); const duplicate=expectFailure(coordinator.refreshConnector('Fixture connector'),'busy'); - const waitStarted=async()=>{const started=Date.now();while(owned||!await page.evaluate(()=>document.querySelector('#refresh')?.matches(':disabled')===true)){if(Date.now()-started>1500)throw Error('Refresh did not start');await new Promise(resolve=>setTimeout(resolve,20));}}; + const waitStarted=async()=>{const started=Date.now();while(owned||!await page.evaluate(()=>document.querySelector('#refresh')?.matches(':disabled')===true)){if(Date.now()-started>8_000)throw Error('Refresh did not start');await new Promise(resolve=>setTimeout(resolve,20));}}; await waitStarted();await duplicate; await expectFailure(coordinator.refreshConnector('Other connector'),'busy'); expect(owned).toBeFalse();expect((await coordinator.health()).status).toBe('busy'); @@ -106,16 +108,30 @@ test.skipIf(process.env.CODEXIFY_TEST_BROWSER_COMPANION_CHROME!=="1")("passive p await page.goto(original); const cancel=new AbortController(),cancelled=coordinator.refreshConnector('Fixture connector',cancel.signal); const cancellation=expectFailure(cancelled,'cancelled');await waitStarted();cancel.abort();await cancellation; + // A cancellation may be reported before its separately bounded restoration + // finishes, especially when Windows Chrome has a slow navigation. + const restoredBy=Date.now()+8_000; + while(page.url()!==original&&Date.now()setTimeout(resolve,50)); expect(page.url()).toBe(original);expect((await coordinator.health()).status).toBe('idle');refreshDelay=300; permissionLabel='Autorisation';allowLabel='Tout autoriser';const beforeLocale=permissionVisits; - await driver.refreshConnector('Fixture connector');expect(permissionVisits).toBe(beforeLocale+1); // Learn the new locale from checked radio state. - await driver.refreshConnector('Fixture connector');expect(permissionVisits).toBe(beforeLocale+1); // Then the direct path needs no permissions visit. + await driver.refreshConnector('Fixture connector');expect(permissionVisits).toBe(beforeLocale); // The selected value proves permission without reopening radios. + await driver.refreshConnector('Fixture connector');expect(permissionVisits).toBe(beforeLocale); permissionLabel='Δικαιώματα';allowLabel='Να επιτρέπονται όλα';const beforeGreek=permissionVisits; - await driver.refreshConnector('Fixture connector');expect(permissionVisits).toBe(beforeGreek+1); - await driver.refreshConnector('Fixture connector');expect(permissionVisits).toBe(beforeGreek+1); + await driver.refreshConnector('Fixture connector');expect(permissionVisits).toBe(beforeGreek); + await driver.refreshConnector('Fixture connector');expect(permissionVisits).toBe(beforeGreek); permissionLabel='Autorizzazioni';allowLabel='Consenti tutto';const beforeItalian=permissionVisits; - await driver.refreshConnector('Fixture connector');expect(permissionVisits).toBe(beforeItalian+1); - await driver.refreshConnector('Fixture connector');expect(permissionVisits).toBe(beforeItalian+1); + await driver.refreshConnector('Fixture connector');expect(permissionVisits).toBe(beforeItalian); + await driver.refreshConnector('Fixture connector');expect(permissionVisits).toBe(beforeItalian); + // A cached allow-all summary must not override fresh read-only metadata, + // even when the visible last leaf misleadingly says "Allow all actions". + permission='read_only';permissionMetadata='read_only';displayedPermission='Allow all actions'; + permissionLabel='You can choose Allow all actions';collapsedPermissions=true; + const beforeCollapsed=permissionVisits,beforeRefresh=refreshes; + const recovered=await driver.refreshConnector('Fixture connector'); + expect(recovered.permissionChanged).toBeTrue(); + expect(permission).toBe('allow_all');expect(permissionVisits).toBe(beforeCollapsed+2); + expect(refreshes).toBe(beforeRefresh+1);expect(deletes).toBe(0); + collapsedPermissions=false;permissionLabel='Permiso'; expect(newPage).not.toHaveBeenCalled();expect(addedPages).toBe(0);expect(context.pages()).toEqual(initialPages);expect(page.isClosed()).toBeFalse(); // Passive account reads neither acquire a maintenance lease nor navigate. const beforePassive={beginCalls,endCalls,billingReads};visits.length=0; @@ -177,7 +193,7 @@ test.skipIf(process.env.CODEXIFY_TEST_BROWSER_COMPANION_CHROME!=="1")("passive p expect(beginCalls).toBe(endCalls);expect(owned).toBeFalse();expect(newPage).not.toHaveBeenCalled();expect(addedPages).toBe(0);expect(context.pages()).toEqual(initialPages); } finally {newPage.mockRestore();} }finally{await browser.close();} -},30000); +},90_000); test.skipIf(process.env.CODEXIFY_TEST_BROWSER_COMPANION_CHROME!=="1")("confirmed sign-out survives conversation errors while failed session reads remain unavailable",async()=>{ diff --git a/browser-companion/tests/connector-permission-regression.test.ts b/browser-companion/tests/connector-permission-regression.test.ts new file mode 100644 index 00000000..5277cf7a --- /dev/null +++ b/browser-companion/tests/connector-permission-regression.test.ts @@ -0,0 +1,93 @@ +import {test,expect} from "bun:test"; +import {chromium} from "patchright"; +import {join} from "node:path"; +import {readChatGptAccount} from "../src/account"; +import {inspectConnectorSettings,setConnectorAllowAll,verifyConnectorAllowAll} from "../src/account-settings"; +import {privateChromeExecutable} from "../src/chrome-executable"; + +test.skipIf(process.env.CODEXIFY_TEST_BROWSER_COMPANION_CHROME!=="1")( + "already-granted permission is proved on the app page; collapsed choices cannot be forged by a label", + async () => { + const executablePath=await privateChromeExecutable(join(import.meta.dirname,"../.browsers",`${process.platform}-${process.arch}`)); + const browser=await chromium.launch({executablePath,headless:true}); + try { + const page=await browser.newPage(); + const appId="asdk_app_fixture",name="Fixture connector"; + let mode:"allow_all"|"read_only"="allow_all"; + let permissionMetadata:string|null=null,selectedLabel="Allow all actions"; + let permissionVisits=0,permissionChanges=0,deleteRequests=0; + + await page.context().route("https://chatgpt.com/**",async route=>{ + const path=new URL(route.request().url()).pathname; + if(path==="/api/auth/session")return route.fulfill({json:{ + user:{id:"fixture-user"},account:{id:"fixture-account",planType:"pro",structure:"personal"}, + }}); + if(path==="/set-permission"){ + permissionChanges++;mode="allow_all";permissionMetadata=null;selectedLabel="Allow all actions"; + return route.fulfill({json:{ok:true}}); + } + if(path==="/delete"){deleteRequests++;return route.fulfill({json:{ok:true}});} + if(path.endsWith("/permissions")){ + permissionVisits++; + const options=["Ask every time","Read only","Low risk","Allow all actions"].map((label,index)=> + '
'+label+'
', + ).join(""); + const html='

Permissions

'+ + ''+ + ''+ + ''; + return route.fulfill({contentType:"text/html; charset=utf-8",body:html}); + } + if(path==="/settings/plugins-settings/plugin_"+appId){ + const meta=permissionMetadata===null?"":' data-permission="'+permissionMetadata+'"'; + const html='

'+name+'

'+ + '
'+ + ''+ + 'PermissionsChoose permissions'+selectedLabel+'
'+ + '
'+ + ''+ + '
'+ + '
'; + return route.fulfill({contentType:"text/html; charset=utf-8",body:html}); + } + return route.fulfill({contentType:"text/html; charset=utf-8",body:"
ChatGPT
"}); + }); + + await page.goto("https://chatgpt.com/"); + const account=(await readChatGptAccount(page)).fingerprint; + const granted=await inspectConnectorSettings(page,appId,name,account); + expect(granted?.allowAll).toBe(true); + expect(permissionVisits).toBe(0); + + // An explicit read-only marker defeats a misleading "Allow all" label. + mode="read_only";permissionMetadata="read_only";selectedLabel="Allow all actions"; + const denied=await inspectConnectorSettings(page,appId,name,account); + expect(denied?.allowAll).toBe(false); + + // An unknown label cannot silently become a permission proof. + permissionMetadata=null;selectedLabel="Allow all actions is an available option"; + const ambiguous=await inspectConnectorSettings(page,appId,name,account); + expect(ambiguous?.allowAll).toBe(false); + + // The collapsed picker must be opened explicitly, and the selected value + // must still be verified after a new server-backed document navigation. + const changed=await setConnectorAllowAll(page,appId,account); + expect(changed).toBe(true); + await verifyConnectorAllowAll(page,appId,account); + expect(permissionChanges).toBe(1); + expect(permissionVisits).toBe(2); + const verified=await inspectConnectorSettings(page,appId,name,account); + expect(verified?.allowAll).toBe(true); + expect(deleteRequests).toBe(0); + expect(page.context().pages()).toEqual([page]); + } finally { + await browser.close(); + } + }, + 60_000, +); From befca284297622ed2a56373140f53ae9a2ff1d76 Mon Sep 17 00:00:00 2001 From: tomi Date: Fri, 20 Nov 2026 01:19:52 +0100 Subject: [PATCH 083/118] fix(windows): compare orphan parent timestamps in UTC --- browser-companion/src/windows-chrome-recovery.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/browser-companion/src/windows-chrome-recovery.ts b/browser-companion/src/windows-chrome-recovery.ts index 8458b675..e5e79ec6 100644 --- a/browser-companion/src/windows-chrome-recovery.ts +++ b/browser-companion/src/windows-chrome-recovery.ts @@ -20,7 +20,8 @@ foreach($item in $all){ if($path -ine $expected -and (-not $runtime -or -not $path.StartsWith($runtime,[StringComparison]::OrdinalIgnoreCase))){continue} $parent=$parents[[int]$item.ParentProcessId] # A PID reused after Chrome was created is not its owner. - if($parent -and $parent.CreationDate -le $item.CreationDate){continue} + # Compare UTC instants: local wall-clock times repeat during the DST fold. + if($parent -and $parent.CreationDate.ToUniversalTime() -le $item.CreationDate.ToUniversalTime()){continue} $profiles=[regex]::Matches($item.CommandLine,'(?:^|\s)(?:"--user-data-dir=([^"]+)"|--user-data-dir="([^"]+)"|--user-data-dir=([^\s"]+))(?=\s|$)') if($profiles.Count -ne 1){continue} $value=@($profiles[0].Groups[1].Value,$profiles[0].Groups[2].Value,$profiles[0].Groups[3].Value | Where-Object {$_})[0] @@ -31,7 +32,7 @@ foreach($item in $all){ $current=Get-CimInstance Win32_Process -Filter ("ProcessId="+[int]$item.ProcessId) if(-not $current -or $current.CreationDate -ne $item.CreationDate -or $current.ExecutablePath -ine $item.ExecutablePath -or $current.CommandLine -cne $item.CommandLine){continue} $parent=Get-CimInstance Win32_Process -Filter ("ProcessId="+[int]$current.ParentProcessId) - if($parent -and $parent.CreationDate -le $current.CreationDate){continue} + if($parent -and $parent.CreationDate.ToUniversalTime() -le $current.CreationDate.ToUniversalTime()){continue} $process=Get-Process -Id $current.ProcessId -ErrorAction SilentlyContinue if(-not $process){continue} try { From aa84b644fae751702f81c91a430c9df48571951b Mon Sep 17 00:00:00 2001 From: tomi Date: Fri, 20 Nov 2026 01:38:11 +0100 Subject: [PATCH 084/118] fix(browser): log redacted permission control shape on selector timeout --- browser-companion/src/account-settings.ts | 34 ++++++++++++++++++- .../connector-permission-regression.test.ts | 18 +++++++++- 2 files changed, 50 insertions(+), 2 deletions(-) diff --git a/browser-companion/src/account-settings.ts b/browser-companion/src/account-settings.ts index 2da73d27..f297d9cc 100644 --- a/browser-companion/src/account-settings.ts +++ b/browser-companion/src/account-settings.ts @@ -195,7 +195,39 @@ async function allowAllChoice(page:Page,signal?:AbortSignal) { await trigger.click({timeout:3_000,signal}); } } - await radios.first().waitFor({state:"visible",timeout:10_000,signal}); + try{ + await radios.first().waitFor({state:"visible",timeout:10_000,signal}); + }catch(error){ + // Browser-side UI compatibility diagnostics, never account contents. This + // records only DOM control counts and fixed permission-option matches. + if(!signal?.aborted){ + try{ + const shape=await observeReadOnly(page.evaluate(()=>{ + const visible=(node:Element)=>node.getClientRects().length>0; + const count=(selector:string)=>[...document.querySelectorAll(selector)].filter(visible).length; + const labels=new Set(["allow all actions","allow all tools","never ask","permitir todo","tout autoriser","consenti tutto","dovoli vsa dejanja"]); + const choices=[...document.querySelectorAll('button,label,span,[role="radio"],[role="option"],[role="menuitemradio"]')].filter(visible) + .filter(node=>node.children.length<=2&&labels.has((node.textContent??"").normalize("NFKC").replace(/\s+/g," ").trim().toLowerCase())); + const path=location.pathname; + return { + pageType:path.endsWith("/permissions")?"permissions":path.includes("/settings/plugins-settings/")?"plugin-settings":"other", + visibleRadios:count('[role="radio"],input[type="radio"]'), + allRadios:document.querySelectorAll('[role="radio"],input[type="radio"]').length, + permissionTriggers:count('[data-action="plugin-permissions"],[data-testid="plugin-permission-trigger"]'), + menuItemRadios:count('[role="menuitemradio"]'), + ariaCheckedControls:count('[aria-checked]'), + ariaSelectedOptions:count('[role="option"][aria-selected]'), + visibleDialogs:count('[role="dialog"]'), + visibleButtons:count('button'), + recognizedAllowAllLabels:choices.length, + recognizedAllowAllSelected:choices.filter(node=>node.getAttribute("aria-checked")==="true"||node.getAttribute("aria-selected")==="true"||node.getAttribute("data-state")==="checked").length, + }; + }),signal,1_500); + console.warn(`[connector-permission-shape] ${JSON.stringify(shape)}`); + }catch{console.warn("[connector-permission-shape] observation unavailable");} + } + throw error; + } if(await observeReadOnly(radios.count(),signal)!==4)throw selectorDrift("ChatGPT permission choices changed; Allow all was not selected"); const choice=radios.nth(3); const checked=()=>observeReadOnly(choice.getAttribute("aria-checked").then(value=>value==="true").then(async value=>value||await choice.isChecked().catch(()=>false)),signal); diff --git a/browser-companion/tests/connector-permission-regression.test.ts b/browser-companion/tests/connector-permission-regression.test.ts index 5277cf7a..d31faa93 100644 --- a/browser-companion/tests/connector-permission-regression.test.ts +++ b/browser-companion/tests/connector-permission-regression.test.ts @@ -15,7 +15,7 @@ test.skipIf(process.env.CODEXIFY_TEST_BROWSER_COMPANION_CHROME!=="1")( const appId="asdk_app_fixture",name="Fixture connector"; let mode:"allow_all"|"read_only"="allow_all"; let permissionMetadata:string|null=null,selectedLabel="Allow all actions"; - let permissionVisits=0,permissionChanges=0,deleteRequests=0; + let permissionVisits=0,permissionChanges=0,deleteRequests=0,omitControls=false; await page.context().route("https://chatgpt.com/**",async route=>{ const path=new URL(route.request().url()).pathname; @@ -29,6 +29,8 @@ test.skipIf(process.env.CODEXIFY_TEST_BROWSER_COMPANION_CHROME!=="1")( if(path==="/delete"){deleteRequests++;return route.fulfill({json:{ok:true}});} if(path.endsWith("/permissions")){ permissionVisits++; + if(omitControls)return route.fulfill({contentType:"text/html; charset=utf-8", + body:'

Permissions

Private example description that must never be logged

'}); const options=["Ask every time","Read only","Low risk","Allow all actions"].map((label,index)=> '
'+label+'
', ).join(""); @@ -85,6 +87,20 @@ test.skipIf(process.env.CODEXIFY_TEST_BROWSER_COMPANION_CHROME!=="1")( expect(verified?.allowAll).toBe(true); expect(deleteRequests).toBe(0); expect(page.context().pages()).toEqual([page]); + // Unknown permission markup remains fail-closed and reports only a + // bounded structural shape, never arbitrary private page content. + omitControls=true; + const warnings:string[]=[]; + const originalWarn=console.warn; + console.warn=(...items:unknown[])=>{warnings.push(items.map(String).join(" "));}; + try{ + await expect(setConnectorAllowAll(page,appId,account)).rejects.toThrow("Timeout"); + }finally{console.warn=originalWarn;} + const diagnostic=warnings.find(line=>line.startsWith("[connector-permission-shape]")); + expect(diagnostic).toBeDefined(); + expect(diagnostic).toContain('"pageType":"permissions"'); + expect(diagnostic).toContain('"visibleRadios":0'); + expect(diagnostic).not.toContain("Private example description"); } finally { await browser.close(); } From bd53da4555085a0540c2923d792f0e9a97bc21fd Mon Sep 17 00:00:00 2001 From: tomi Date: Fri, 20 Nov 2026 02:13:04 +0100 Subject: [PATCH 085/118] fix(browser): refresh connector tools without changing app permissions --- browser-companion/src/account-settings.ts | 17 +++++---------- browser-companion/src/chatgpt-driver.ts | 19 +++++++---------- .../tests/account-settings.test.ts | 21 ++++++++++--------- 3 files changed, 24 insertions(+), 33 deletions(-) diff --git a/browser-companion/src/account-settings.ts b/browser-companion/src/account-settings.ts index f297d9cc..ab5c92d2 100644 --- a/browser-companion/src/account-settings.ts +++ b/browser-companion/src/account-settings.ts @@ -450,19 +450,12 @@ export async function prepareConnectorRefresh(page:Page,name:string,expectedAcco const account=expectedAccountFingerprint??(await readChatGptAccount(page,signal)).fingerprint; const appId=knownAppId??await identifyConnectorApp(page,name,account,signal); const before=await inspectConnectorSettings(page,appId,name,account,signal); - let permissionChanged=false; - if(!before?.allowAll&&(!witness?.summary||before?.summary!==witness.summary)) { - traceRefresh("permission needs selection"); - permissionChanged=await setConnectorAllowAll(page,appId,account,signal); - await connectorPage(page,appId,account,false,signal); - await page.getByText(name,{exact:true}).and(page.locator(':visible')).first().waitFor({state:"visible",timeout:5_000,signal}); - await markRefreshButton(page); - } - const verified=await connectorPermissionSummary(page); - if(verified?.summary)witness?.remember(verified.summary); - traceRefresh("permission allows all"); + // Tool refresh must not change the permission grant. The current UI may + // manage app/account permissions elsewhere or restrict them by policy. + if(before?.allowAll===true&&before.summary)witness?.remember(before.summary); + traceRefresh("refresh tools without changing ChatGPT-managed permissions"); const observation=await beginConnectorToolRefresh(page,appId,name,account,signal); - return {appId,permissionChanged,observation}; + return {appId,permissionChanged:false,observation}; } export async function refreshConnectorTools(page:Page,name:string,expectedAccountFingerprint?:string,signal?:AbortSignal,knownAppId?:string,witness?:PermissionWitness):Promise<{appId:string;refreshObserved:boolean;permissionChanged:boolean;schemaVerified:false}> { diff --git a/browser-companion/src/chatgpt-driver.ts b/browser-companion/src/chatgpt-driver.ts index 447aca9c..5a6f42cb 100644 --- a/browser-companion/src/chatgpt-driver.ts +++ b/browser-companion/src/chatgpt-driver.ts @@ -1,7 +1,7 @@ import {observeReadOnly,RendererProbeGate} from "./observation"; import type { Frame, Locator, Page } from "patchright"; import {completedHandoff,createCompletedHandoffVerifier} from "./turn-renewal"; -import {classifyPlan,identifyConnectorApp,observedConnectorApp,inspectConnectorSettings,setConnectorAllowAll,verifyConnectorAllowAll,beginConnectorToolRefresh,type ConnectorRefreshObservation,type AccountPlan} from "./account-settings"; +import {classifyPlan,identifyConnectorApp,observedConnectorApp,inspectConnectorSettings,beginConnectorToolRefresh,type ConnectorRefreshObservation,type AccountPlan} from "./account-settings"; import {ConnectorAppCache} from "./connector-cache"; import {DraftRecoveryJournal} from './draft-recovery'; import {approveConversationCard,latestConversationApprovalCards,throwIfConversationApproval} from "./conversation-approval"; @@ -631,23 +631,20 @@ export class ChatGptBrowserDriver implements BrowserDriver { }); void interrupted.catch(()=>{}); // Cancellation during preparation is handled by its bounded phase. try { - const before=await phase("Inspect connector settings",(page,account,operationSignal)=>inspectConnectorSettings(page,appId,name,account.fingerprint,operationSignal)); - // A cached label is only a hint for diagnostics, never an authorization - // proof. Require a fresh, unambiguous permission state on this account. - const needsVerification=before?.allowAll!==true; - let permissionChanged=false; - if(needsVerification)permissionChanged=await phase("Verify connector permission",(page,account,operationSignal)=>setConnectorAllowAll(page,appId,account.fingerprint,operationSignal)); + await phase("Inspect connector settings",(page,account,operationSignal)=>inspectConnectorSettings(page,appId,name,account.fingerprint,operationSignal)); + // Refreshing the tool schema is not a request to elevate app permissions. + // Permissions may be on a separate connected-account UI or enforced by + // workspace policy, and the legacy /permissions radio page is optional. + // Never change a user's grant just to refresh tool metadata. observation=await phase("Start connector refresh",async(page,account,operationSignal)=>{ - if(needsVerification)await verifyConnectorAllowAll(page,appId,account.fingerprint,operationSignal); const current=await inspectConnectorSettings(page,appId,name,account.fingerprint,operationSignal); - if(current?.allowAll!==true)throw new BrowserCompanionError("Connector permission could not be positively verified before refresh","external_interference"); - if(current.summary)this.connectorApps.rememberAllowAllSummary(account.fingerprint,name,current.summary); + if(current?.allowAll===true&¤t.summary)this.connectorApps.rememberAllowAllSummary(account.fingerprint,name,current.summary); return beginConnectorToolRefresh(page,appId,name,account.fingerprint,operationSignal); }); // The coordinator retains the shared window through confirmation and the // restoration below; other operations must not navigate away mid-refresh. const refreshObserved=await Promise.race([observation.wait(waitSignal),interrupted]); - return {appId,permissionChanged,refreshObserved,schemaVerified:false as const}; + return {appId,permissionChanged:false,refreshObserved,schemaVerified:false as const}; }catch(error){refreshFailure=error;throw error;} finally { waitSignal.removeEventListener("abort",onAbort); diff --git a/browser-companion/tests/account-settings.test.ts b/browser-companion/tests/account-settings.test.ts index d3dea8d5..e83ac5fd 100644 --- a/browser-companion/tests/account-settings.test.ts +++ b/browser-companion/tests/account-settings.test.ts @@ -41,7 +41,7 @@ test.skipIf(process.env.CODEXIFY_TEST_BROWSER_COMPANION_CHROME!=="1")("passive p const browser=await chromium.launch({executablePath,headless:true}); try { const context=await browser.newContext();const page=await context.newPage();let permission='read_only',refreshes=0,deletes=0,billingReads=0,failConnector=false,fastRefresh=false,replaceRefresh=false,refreshDelay=300,permissionVisits=0;const visits:string[]=[]; - let planAccount='fixture-account',permissionLabel='Permiso',allowLabel='Permitir todo',originalHtml='
',sessionAvailable=true,collapsedPermissions=false; + let planAccount='fixture-account',permissionLabel='Permiso',allowLabel='Permitir todo',originalHtml='
',sessionAvailable=true,collapsedPermissions=false,noPermissionControls=false; let permissionMetadata:string|undefined,displayedPermission:string|undefined; const witness:{summary?:string;remember:(summary:string)=>void}={remember:summary=>witness.summary=summary}; await page.context().route('https://chatgpt.com/**',async route=>{ @@ -55,12 +55,13 @@ test.skipIf(process.env.CODEXIFY_TEST_BROWSER_COMPANION_CHROME!=="1")("passive p if(path==='/delete'){deletes++;return route.fulfill({json:{ok:true}});} if(path==='/')return route.fulfill({contentType:'text/html; charset=utf-8',body:'
Fixture connector
'}); if(path.endsWith('/permissions')){permissionVisits++;const choices=['Preguntar','Solo lectura','Bajo riesgo','Permitir todo'].map((label,index)=>`
${label}
`).join('');return route.fulfill({contentType:'text/html; charset=utf-8',body:`

Permissions

${collapsedPermissions?'':''}`});} + if(noPermissionControls)return route.fulfill({contentType:'text/html; charset=utf-8',body:`

Fixture connector

`}); return route.fulfill({contentType:'text/html; charset=utf-8',body:`

Fixture connector

${permissionLabel}Elegir permisos${displayedPermission??(permission==='allow_all'?allowLabel:'Solo lectura')}
Nombre
Descripción
Actualizar herramientas
Eliminar
`}); }); await page.goto('https://chatgpt.com/c/original'); const plan=await readBillingPlan(page);expect(plan.label).toBe('Pro 20x'); - const result=await refreshConnectorTools(page,'Fixture connector',undefined,undefined,undefined,witness);expect(result.refreshObserved).toBeTrue();expect(result.permissionChanged).toBeTrue();expect(result.schemaVerified).toBeFalse(); - expect(permission).toBe('allow_all');expect(refreshes).toBe(1);expect(deletes).toBe(0); + const result=await refreshConnectorTools(page,'Fixture connector',undefined,undefined,undefined,witness);expect(result.refreshObserved).toBeTrue();expect(result.permissionChanged).toBeFalse();expect(result.schemaVerified).toBeFalse(); + expect(permission).toBe('read_only');expect(permissionVisits).toBe(0);expect(refreshes).toBe(1);expect(deletes).toBe(0); const beforePermission=permissionVisits;visits.length=0; const again=await refreshConnectorTools(page,'Fixture connector',undefined,undefined,'asdk_app_fixture',witness);expect(again.permissionChanged).toBeFalse();expect(refreshes).toBe(2);expect(deletes).toBe(0); expect(permissionVisits).toBe(beforePermission);expect(visits).toEqual(['/settings/plugins-settings/plugin_asdk_app_fixture']); // A fresh settings document validates the grant. @@ -114,7 +115,7 @@ test.skipIf(process.env.CODEXIFY_TEST_BROWSER_COMPANION_CHROME!=="1")("passive p while(page.url()!==original&&Date.now()setTimeout(resolve,50)); expect(page.url()).toBe(original);expect((await coordinator.health()).status).toBe('idle');refreshDelay=300; permissionLabel='Autorisation';allowLabel='Tout autoriser';const beforeLocale=permissionVisits; - await driver.refreshConnector('Fixture connector');expect(permissionVisits).toBe(beforeLocale); // The selected value proves permission without reopening radios. + await driver.refreshConnector('Fixture connector');expect(permissionVisits).toBe(beforeLocale); // Tool refresh never opens or changes the grant. await driver.refreshConnector('Fixture connector');expect(permissionVisits).toBe(beforeLocale); permissionLabel='Δικαιώματα';allowLabel='Να επιτρέπονται όλα';const beforeGreek=permissionVisits; await driver.refreshConnector('Fixture connector');expect(permissionVisits).toBe(beforeGreek); @@ -122,16 +123,16 @@ test.skipIf(process.env.CODEXIFY_TEST_BROWSER_COMPANION_CHROME!=="1")("passive p permissionLabel='Autorizzazioni';allowLabel='Consenti tutto';const beforeItalian=permissionVisits; await driver.refreshConnector('Fixture connector');expect(permissionVisits).toBe(beforeItalian); await driver.refreshConnector('Fixture connector');expect(permissionVisits).toBe(beforeItalian); - // A cached allow-all summary must not override fresh read-only metadata, - // even when the visible last leaf misleadingly says "Allow all actions". + // An obsolete selector and misleading cached label must not trigger + // permission elevation. Schema refresh remains a permission-neutral action. permission='read_only';permissionMetadata='read_only';displayedPermission='Allow all actions'; - permissionLabel='You can choose Allow all actions';collapsedPermissions=true; + permissionLabel='You can choose Allow all actions';collapsedPermissions=true;noPermissionControls=true; const beforeCollapsed=permissionVisits,beforeRefresh=refreshes; const recovered=await driver.refreshConnector('Fixture connector'); - expect(recovered.permissionChanged).toBeTrue(); - expect(permission).toBe('allow_all');expect(permissionVisits).toBe(beforeCollapsed+2); + expect(recovered.permissionChanged).toBeFalse(); + expect(permission).toBe('read_only');expect(permissionVisits).toBe(beforeCollapsed); expect(refreshes).toBe(beforeRefresh+1);expect(deletes).toBe(0); - collapsedPermissions=false;permissionLabel='Permiso'; + collapsedPermissions=false;permissionLabel='Permiso'; // The current app-manager view has no permission row. expect(newPage).not.toHaveBeenCalled();expect(addedPages).toBe(0);expect(context.pages()).toEqual(initialPages);expect(page.isClosed()).toBeFalse(); // Passive account reads neither acquire a maintenance lease nor navigate. const beforePassive={beginCalls,endCalls,billingReads};visits.length=0; From d8ebe53083a6fb4477a87bbab804496453f2b0f2 Mon Sep 17 00:00:00 2001 From: tomi Date: Fri, 20 Nov 2026 03:18:17 +0100 Subject: [PATCH 086/118] fix(automation): isolate missing historical worktrees from goal scans --- src/agent_automation/supervisor.rs | 71 +++++++++++++++++++++++++++--- 1 file changed, 65 insertions(+), 6 deletions(-) diff --git a/src/agent_automation/supervisor.rs b/src/agent_automation/supervisor.rs index 8d61e5a7..e00ba924 100644 --- a/src/agent_automation/supervisor.rs +++ b/src/agent_automation/supervisor.rs @@ -1083,12 +1083,17 @@ impl AgentAutomationSupervisor { { return Ok(false); } - let root = context - .bindings - .selected_project_root(&context.config, &task.task)? - .ok_or("The conversation continuation workspace is unavailable")? - .canonicalize() - .map_err(|_| "The conversation continuation workspace is unavailable")?; + // Historical chats can outlive ephemeral managed worktrees. A broken + // binding must fence *that* replacement, not abort the shared scan and + // starve unrelated, correctly bound automation goals. + let Some(root) = replacement_workspace_root( + task.task.stable_key(), + context + .bindings + .selected_project_root(&context.config, &task.task), + ) else { + return Ok(false); + }; let token = context.continuations.issue_token_for_owner( &task.task, task.owner_generation, @@ -4748,6 +4753,60 @@ fn failed_companion_status(code: &str) -> AutomationActionStatus { } } +/// An unavailable binding fences only this replacement. Treating it as a +/// global scan error would prevent every other healthy task from dispatching. +fn replacement_workspace_root( + task_key: &str, + selected: Result, String>, +) -> Option { + let selected = match selected { + Ok(Some(root)) => root, + Ok(None) => { + tracing::warn!( + task_key, + "deferred conversation replacement: no selected workspace" + ); + return None; + } + Err(error) => { + tracing::warn!(task_key, %error, "deferred conversation replacement: invalid workspace binding"); + return None; + } + }; + match selected.canonicalize() { + Ok(root) => Some(root), + Err(error) => { + tracing::warn!(task_key, %error, "deferred conversation replacement: workspace is unavailable"); + None + } + } +} + +#[cfg(test)] +mod replacement_workspace_isolation_tests { + use super::replacement_workspace_root; + #[test] + fn missing_historical_binding_is_deferred_without_losing_healthy_workspace() { + let healthy = tempfile::tempdir().unwrap(); + let valid = healthy.path().canonicalize().unwrap(); + let missing = healthy.path().join("removed-worktree"); + assert!( + replacement_workspace_root("old-chat", Err("missing historical binding".into())) + .is_none() + ); + assert!(replacement_workspace_root("old-chat", Ok(None)).is_none()); + assert!(replacement_workspace_root("old-chat", Ok(Some(missing.clone()))).is_none()); + assert!( + !missing.exists(), + "no placeholder worktree may be manufactured" + ); + assert_eq!( + replacement_workspace_root("valid-chat", Ok(Some(healthy.path().into()))), + Some(valid) + ); + } +} + fn blocks_automatic_requeue(status: AutomationActionStatus) -> bool { matches!( status, From 4df4f73b81b0d64087f93d447b7ee12b72494abd Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Fri, 20 Nov 2026 04:08:53 +0100 Subject: [PATCH 087/118] test(mcp): cover real GodPrompt 1.0.3 to 1.1.1 reload and rollback --- src/bridge/hot_reload_tests.rs | 115 +++++++++++++++++++++++++++++++++ 1 file changed, 115 insertions(+) diff --git a/src/bridge/hot_reload_tests.rs b/src/bridge/hot_reload_tests.rs index a029da4d..6425e9b5 100644 --- a/src/bridge/hot_reload_tests.rs +++ b/src/bridge/hot_reload_tests.rs @@ -810,3 +810,118 @@ async fn service_isolated_real_stdio_process_reload_preserves_unrelated_sources( gamma_pid ); } + + +/// Opt-in, isolated acceptance test using two real, read-only GodPrompt stdio +/// installs. Only initialize, tools/list, and ping are sent; no GodPrompt tool +/// calls, external APIs, operator configuration, or running service are touched. +/// +/// CI installs and selects the pinned published 1.0.3 / 1.1.1 npm versions. +/// A developer can instead supply two existing entrypoint paths locally. +#[tokio::test] +async fn service_local_godprompt_candidate_upgrade_and_failed_rollback() { + let old_entry = std::env::var_os("CODEXIFY_CANARY_OLD_GODPROMPT"); + let new_entry = std::env::var_os("CODEXIFY_CANARY_NEW_GODPROMPT"); + let (Some(old_entry), Some(new_entry)) = (old_entry, new_entry) else { + assert!( + std::env::var_os("CODEXIFY_CANARY_OLD_GODPROMPT").is_none() + && std::env::var_os("CODEXIFY_CANARY_NEW_GODPROMPT").is_none(), + "provide both isolated GodPrompt entrypoints, or neither" + ); + return; + }; + let node = std::env::var("CODEXIFY_CANARY_NODE").unwrap_or_else(|_| "node".into()); + for entry in [&old_entry, &new_entry] { + assert!( + std::path::Path::new(entry).is_file(), + "GodPrompt candidate stdio entrypoint does not exist" + ); + } + let make_candidate = |entry: &std::ffi::OsStr| crate::types::McpServerSpec { + command: Some(node.clone()), + args: vec![entry.to_string_lossy().into_owned()], + mode: Some(McpToolExposure::Direct), + startup_timeout_sec: Some(18.0), + ..Default::default() + }; + + let (beta_url, _, beta_server) = fixture("beta", false, Duration::ZERO, Duration::ZERO).await; + let (gamma_url, _, gamma_server) = + fixture("gamma", false, Duration::ZERO, Duration::ZERO).await; + let mut config = crate::config::default_config(std::env::temp_dir()); + config.mcp_servers.insert( + "godprompt_canary".into(), + make_candidate(old_entry.as_os_str()), + ); + config + .mcp_servers + .insert("beta".into(), spec(&beta_url, McpToolExposure::Direct)); + config + .mcp_servers + .insert("gamma".into(), spec(&gamma_url, McpToolExposure::Direct)); + + let bridge = connect_upstreams(&config).await; + assert_eq!( + bridge.runtime.snapshot().sources.len(), + 3, + "{:?}", + bridge.report + ); + let runtime = bridge.runtime.clone(); + drop(bridge); + let before = runtime.snapshot(); + let old = before.sources["godprompt_canary"].clone(); + let beta = before.sources["beta"].clone(); + let gamma = before.sources["gamma"].clone(); + let old_tool_count = old.tools.len(); + assert!(old_tool_count > 0, "old GodPrompt must advertise tools"); + drop(before); + + let result = runtime + .reload_with_spec( + "godprompt_canary", + make_candidate(new_entry.as_os_str()), + None, + ) + .await + .expect("replacement GodPrompt must initialize, discover tools and pass ping"); + assert_eq!(result["previousGeneration"], 1); + assert_eq!(result["replacementGeneration"], 2); + assert_eq!(result["ready"], true); + assert_eq!(result["previousVersion"], "1.0.3"); + assert_eq!(result["replacementVersion"], "1.1.1"); + let updated = runtime.snapshot(); + let new = updated.sources["godprompt_canary"].clone(); + assert!(!Arc::ptr_eq(&old, &new)); + assert!(Arc::ptr_eq(&beta, &updated.sources["beta"])); + assert!(Arc::ptr_eq(&gamma, &updated.sources["gamma"])); + assert!(new.tools.len() > 0, "new GodPrompt must advertise tools"); + println!( + "isolated GodPrompt {} -> {}: {} -> {} tools; timings {:?}; testing rollback", + result["previousVersion"], + result["replacementVersion"], + old_tool_count, + new.tools.len(), + result["timingsMs"] + ); + drop(updated); + + let mut broken = make_candidate(new_entry.as_os_str()); + broken.command = Some("codexify-nonexistent-godprompt-canary".into()); + assert_eq!( + runtime + .reload_with_spec("godprompt_canary", broken, None) + .await + .err(), + Some("INITIALIZE_FAILED") + ); + let after_rollback = runtime.snapshot(); + assert!(Arc::ptr_eq( + &new, + &after_rollback.sources["godprompt_canary"] + )); + assert!(Arc::ptr_eq(&beta, &after_rollback.sources["beta"])); + assert!(Arc::ptr_eq(&gamma, &after_rollback.sources["gamma"])); + beta_server.abort(); + gamma_server.abort(); +} From 39c21894922ddff44c28c77b0b971d432d32da37 Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Fri, 20 Nov 2026 04:09:00 +0100 Subject: [PATCH 088/118] ci(mcp): run isolated real GodPrompt npm version switch as required gate --- .github/workflows/ci.yml | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e2f87694..09bec8e9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -102,6 +102,17 @@ jobs: - name: Test run: cargo test --all + - name: Test actual GodPrompt 1.0.3 to 1.1.1 hot reload and rollback + env: + CODEXIFY_CANARY_OLD_GODPROMPT: ${{ runner.temp }}/godprompt-old/node_modules/god-prompt-mcp/dist/stdio.js + CODEXIFY_CANARY_NEW_GODPROMPT: ${{ runner.temp }}/godprompt-new/node_modules/god-prompt-mcp/dist/stdio.js + run: | + npm install --prefix "$RUNNER_TEMP/godprompt-old" --no-save --no-package-lock --ignore-scripts --no-audit --no-fund god-prompt-mcp@1.0.3 + npm install --prefix "$RUNNER_TEMP/godprompt-new" --no-save --no-package-lock --ignore-scripts --no-audit --no-fund god-prompt-mcp@1.1.1 + test -f "$CODEXIFY_CANARY_OLD_GODPROMPT" + test -f "$CODEXIFY_CANARY_NEW_GODPROMPT" + cargo test --locked --lib service_local_godprompt_candidate_upgrade_and_failed_rollback -- --nocapture + - name: Test Rust and TypeScript browser companion contract env: CODEXIFY_TEST_BROWSER_COMPANION_BUN: ${{ steps.browser-bun.outputs.bun-path }} From eb029f3d8e571d28ce0605304adc357a350723da Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Fri, 20 Nov 2026 04:16:26 +0100 Subject: [PATCH 089/118] style(mcp): apply exact Rustfmt spacing in GodPrompt canary --- src/bridge/hot_reload_tests.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/bridge/hot_reload_tests.rs b/src/bridge/hot_reload_tests.rs index 6425e9b5..5560dc4a 100644 --- a/src/bridge/hot_reload_tests.rs +++ b/src/bridge/hot_reload_tests.rs @@ -811,7 +811,6 @@ async fn service_isolated_real_stdio_process_reload_preserves_unrelated_sources( ); } - /// Opt-in, isolated acceptance test using two real, read-only GodPrompt stdio /// installs. Only initialize, tools/list, and ping are sent; no GodPrompt tool /// calls, external APIs, operator configuration, or running service are touched. From 91cd90b3faf8e7e00c8947f05f2c156bd44b79ea Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Fri, 20 Nov 2026 04:25:23 +0100 Subject: [PATCH 090/118] style(mcp): satisfy strict Clippy in real GodPrompt canary --- src/bridge/hot_reload_tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/bridge/hot_reload_tests.rs b/src/bridge/hot_reload_tests.rs index 5560dc4a..38b5d4d1 100644 --- a/src/bridge/hot_reload_tests.rs +++ b/src/bridge/hot_reload_tests.rs @@ -894,7 +894,7 @@ async fn service_local_godprompt_candidate_upgrade_and_failed_rollback() { assert!(!Arc::ptr_eq(&old, &new)); assert!(Arc::ptr_eq(&beta, &updated.sources["beta"])); assert!(Arc::ptr_eq(&gamma, &updated.sources["gamma"])); - assert!(new.tools.len() > 0, "new GodPrompt must advertise tools"); + assert!(!new.tools.is_empty(), "new GodPrompt must advertise tools"); println!( "isolated GodPrompt {} -> {}: {} -> {} tools; timings {:?}; testing rollback", result["previousVersion"], From 1a6deb5272571718d161d3f7c46d94b6177f6a17 Mon Sep 17 00:00:00 2001 From: tomi Date: Fri, 20 Nov 2026 04:39:36 +0100 Subject: [PATCH 091/118] fix(owner-chat): use fresh browser readiness for manual refresh --- src/owner_chat/settings.rs | 40 +++++++++++++++++++++++++++++++++++--- 1 file changed, 37 insertions(+), 3 deletions(-) diff --git a/src/owner_chat/settings.rs b/src/owner_chat/settings.rs index 6d2217d6..b1922cfe 100644 --- a/src/owner_chat/settings.rs +++ b/src/owner_chat/settings.rs @@ -504,7 +504,10 @@ async fn run_manual_refresh(state: OwnerState, id: String, retry_after: Duration loop { let result = async { let client = super::schema_refresh::refresh_client(&state.config).await?; - let health = client.health(&CancellationToken::new()).await?; + // Passive health is deliberately short-budgeted and may say `busy` + // while Chrome is warming. The refresh scheduler needs the fresh + // idle/account observation before deciding to requeue this job. + let health = client.ready_health(&CancellationToken::new()).await?; if health.active_action_id.is_some() || health.status == crate::agent_automation::CompanionSessionStatus::Busy { @@ -568,14 +571,19 @@ mod tests { successes: Arc, release: Arc, } - async fn refresh_health(State(fixture): State) -> Json { + async fn refresh_health( + State(fixture): State, + uri: axum::http::Uri, + ) -> Json { use std::sync::atomic::Ordering; fixture.health_calls.fetch_add(1, Ordering::SeqCst); + let mode = fixture.mode.load(Ordering::SeqCst); + let ready = uri.query().is_some_and(|query| query == "ready=1"); Json( json!({"protocolVersion":1,"kind":"codexify-browser-companion", "build":format!("{}{}",env!("CARGO_PKG_VERSION"),crate::agent_automation::PROTOCOL_BUILD_SUFFIX), "authenticated":true,"accountFingerprint":"fixture-account","activeActionId":null, - "status":if fixture.mode.load(Ordering::SeqCst)==0 {"busy"} else {"idle"}}), + "status":if mode==0 || (mode==5 && !ready) {"busy"} else {"idle"}}), ) } async fn fixture_refresh( @@ -776,6 +784,32 @@ mod tests { companion.abort(); } #[tokio::test] + async fn manual_refresh_does_not_starve_on_a_warming_passive_health_result() { + use std::sync::atomic::Ordering; + let root = tempfile::tempdir().unwrap(); + let (state, fixture, base, owner, companion) = refresh_fixture(root.path()).await; + // Chrome can be idle and authenticated while the passive health probe + // returns `busy` because its short observation budget expired. + fixture.mode.store(5, Ordering::SeqCst); + let receipt: Value = reqwest::Client::new() + .post(format!("{base}/api/settings/refresh-connector")) + .bearer_auth("owner-test-token") + .send() + .await + .unwrap() + .json() + .await + .unwrap(); + assert_eq!(receipt["phase"], "queued"); + let done = wait_refresh_phase(&state, "completed").await; + assert_eq!(done["refreshId"], receipt["refreshId"]); + assert_eq!(done["result"]["refreshObserved"], true); + assert_eq!(fixture.calls.load(Ordering::SeqCst), 1); + assert!(fixture.health_calls.load(Ordering::SeqCst) >= 1); + owner.abort(); + companion.abort(); + } + #[tokio::test] async fn manual_refresh_reports_real_failure_and_allows_a_new_retry() { use std::sync::atomic::Ordering; let root = tempfile::tempdir().unwrap(); From d91e73d974f9131bc569181d2b62d8b92eb10f8e Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Fri, 20 Nov 2026 05:04:58 +0100 Subject: [PATCH 092/118] ci: build isolated Windows hot reload preview artifact without deployment --- .../workflows/preview-hot-reload-windows.yml | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 .github/workflows/preview-hot-reload-windows.yml diff --git a/.github/workflows/preview-hot-reload-windows.yml b/.github/workflows/preview-hot-reload-windows.yml new file mode 100644 index 00000000..3b2b44bf --- /dev/null +++ b/.github/workflows/preview-hot-reload-windows.yml @@ -0,0 +1,46 @@ +name: Build experimental Codexify hot reload for Windows + +on: + push: + branches: + - feat/per-mcp-hot-reload-20261119 + paths: + - .github/workflows/preview-hot-reload-windows.yml + +permissions: + contents: read + +jobs: + preview-windows: + name: Package pinned Windows feature binary + runs-on: windows-latest + timeout-minutes: 45 + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - uses: dtolnay/rust-toolchain@stable + - uses: Swatinem/rust-cache@v2 + - name: Build from exact branch commit + shell: pwsh + run: | + $ErrorActionPreference = 'Stop' + cargo build --release --locked --bin codexify + if ($LASTEXITCODE -ne 0) { throw 'Cargo build failed' } + $out = Join-Path $env:RUNNER_TEMP 'codexify-hot-reload-preview' + New-Item -ItemType Directory -Force -Path $out | Out-Null + $binary = Join-Path (Get-Location) 'target\release\codexify.exe' + if (!(Test-Path -LiteralPath $binary -PathType Leaf)) { throw 'Expected executable missing' } + Copy-Item -LiteralPath $binary -Destination (Join-Path $out 'codexify.exe') + & (Join-Path $out 'codexify.exe') --help | Out-Null + if ($LASTEXITCODE -ne 0) { throw 'Preview binary self-probe failed' } + $hash = (Get-FileHash -LiteralPath (Join-Path $out 'codexify.exe') -Algorithm SHA256).Hash.ToLowerInvariant() + Set-Content -LiteralPath (Join-Path $out 'SHA256SUMS.txt') -Value ("$hash codexify.exe") -Encoding ascii + Set-Content -LiteralPath (Join-Path $out 'SOURCE_COMMIT.txt') -Value "${{ github.sha }}" -Encoding ascii + Set-Content -LiteralPath (Join-Path $out 'PREVIEW_NOTICE.txt') -Value 'EXPERIMENTAL binary from feature branch PR #11. Not an official release. Activate only after backing up the existing executable; coordinate with other Codexify workers.' -Encoding ascii + - uses: actions/upload-artifact@v4 + with: + name: codexify-pr11-windows-preview + path: ${{ runner.temp }}/codexify-hot-reload-preview/* + if-no-files-found: error + retention-days: 7 From e0670de5f45928ac4ebc8a00bdfdbfe268321caa Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Fri, 20 Nov 2026 05:17:20 +0100 Subject: [PATCH 093/118] test(mcp): allow Windows runner stdio startup under resource contention --- src/bridge/hot_reload_tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/bridge/hot_reload_tests.rs b/src/bridge/hot_reload_tests.rs index 38b5d4d1..5dc8b3e3 100644 --- a/src/bridge/hot_reload_tests.rs +++ b/src/bridge/hot_reload_tests.rs @@ -611,7 +611,7 @@ fn isolated_stdio_spec(version: &str) -> crate::types::McpServerSpec { command: Some("node".into()), args: vec![fixture.to_string_lossy().into_owned(), version.into()], mode: Some(McpToolExposure::Direct), - startup_timeout_sec: Some(8.0), + startup_timeout_sec: Some(25.0), ..Default::default() } } From ce590c5206717216c1ce9f1251c4dc7e8df5bf29 Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Fri, 20 Nov 2026 12:38:33 +0100 Subject: [PATCH 094/118] fix(mcp): parse and validate existing browser Send gate config in preview --- src/markdown_chat/mod.rs | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/src/markdown_chat/mod.rs b/src/markdown_chat/mod.rs index 5e11b839..76e6b01b 100644 --- a/src/markdown_chat/mod.rs +++ b/src/markdown_chat/mod.rs @@ -178,6 +178,9 @@ pub struct AgentAutomationConfig { #[serde(skip_serializing_if = "Option::is_none")] pub browser_simplicity: Option, pub recovery_enhancements: bool, + /// Preserve the operator-configured browser Send gate in the v2.4 preview. + #[serde(skip_serializing_if = "Option::is_none")] + pub provider_send_gate_path: Option, } impl Default for AgentAutomationConfig { @@ -204,6 +207,7 @@ impl Default for AgentAutomationConfig { minimal_ui: false, browser_simplicity: None, recovery_enhancements: false, + provider_send_gate_path: None, } } } @@ -227,6 +231,13 @@ impl AgentAutomationConfig { fn validate(&self) -> Result<(), String> { self.retry_timings.validate()?; + if let Some(path) = &self.provider_send_gate_path + && (path.len() > 4096 + || !std::path::Path::new(path).is_absolute() + || path.contains('\0')) + { + return Err("agentChat.automation.providerSendGatePath must be an absolute path".into()); + } if !(1..=4).contains(&self.browser_action_lanes) { return Err("agentChat.automation.browserActionLanes must be between 1 and 4".into()); } @@ -1051,6 +1062,27 @@ mod tests { } } + #[test] + fn browser_send_gate_path_round_trips_and_rejects_relative_paths() { + let absolute = if cfg!(windows) { + r"C:\codexify\browser-send-gate.json" + } else { + "/tmp/codexify/browser-send-gate.json" + }; + let config: AgentAutomationConfig = + serde_json::from_value(serde_json::json!({"providerSendGatePath": absolute})).unwrap(); + assert_eq!(config.provider_send_gate_path.as_deref(), Some(absolute)); + assert!(config.validate().is_ok()); + let encoded = serde_json::to_value(&config).unwrap(); + assert_eq!(encoded["providerSendGatePath"], absolute); + for invalid in ["", "relative/send-gate.json"] { + let config: AgentAutomationConfig = + serde_json::from_value(serde_json::json!({"providerSendGatePath": invalid})) + .unwrap(); + assert!(config.validate().is_err()); + } + } + #[test] fn new_chat_project_configuration_is_optional_and_validated() { assert!(AgentAutomationConfig::default().validate().is_ok()); From 29650c5b479349a5e14e4d446c85fcd79fa78023 Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Fri, 20 Nov 2026 12:38:47 +0100 Subject: [PATCH 095/118] fix(mcp): preserve existing Send-gate environment for browser companion --- src/agent_automation/install.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/agent_automation/install.rs b/src/agent_automation/install.rs index 05c9a0a3..87357e53 100644 --- a/src/agent_automation/install.rs +++ b/src/agent_automation/install.rs @@ -326,6 +326,9 @@ impl BrowserCompanionManager { .stdin(Stdio::null()) .stdout(Stdio::from(log)) .stderr(Stdio::from(stderr)); + if let Some(path) = &self.config.provider_send_gate_path { + command.env("CODEXIFY_BROWSER_SEND_GATE_PATH", path); + } configure_detached_process(&mut command); let mut child = command .spawn() From 85a6608e85e86c705a482064681c9e97c54a5055 Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Fri, 20 Nov 2026 12:39:01 +0100 Subject: [PATCH 096/118] ci(mcp): rebuild Windows preview when browser Send-gate compatibility changes --- .github/workflows/preview-hot-reload-windows.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/preview-hot-reload-windows.yml b/.github/workflows/preview-hot-reload-windows.yml index 3b2b44bf..16ca2cfa 100644 --- a/.github/workflows/preview-hot-reload-windows.yml +++ b/.github/workflows/preview-hot-reload-windows.yml @@ -6,6 +6,8 @@ on: - feat/per-mcp-hot-reload-20261119 paths: - .github/workflows/preview-hot-reload-windows.yml + - src/markdown_chat/mod.rs + - src/agent_automation/install.rs permissions: contents: read From 8c305401150f9641d4db7ffc32e1c950503f6b4b Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Fri, 20 Nov 2026 12:54:54 +0100 Subject: [PATCH 097/118] style(mcp): apply CI Rustfmt for browser Send-gate compatibility --- src/markdown_chat/mod.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/markdown_chat/mod.rs b/src/markdown_chat/mod.rs index 76e6b01b..2104b2ba 100644 --- a/src/markdown_chat/mod.rs +++ b/src/markdown_chat/mod.rs @@ -236,7 +236,9 @@ impl AgentAutomationConfig { || !std::path::Path::new(path).is_absolute() || path.contains('\0')) { - return Err("agentChat.automation.providerSendGatePath must be an absolute path".into()); + return Err( + "agentChat.automation.providerSendGatePath must be an absolute path".into(), + ); } if !(1..=4).contains(&self.browser_action_lanes) { return Err("agentChat.automation.browserActionLanes must be between 1 and 4".into()); From e69e3932625718d157ce3094ddfde9c3c39faca2 Mon Sep 17 00:00:00 2001 From: tomi Date: Fri, 20 Nov 2026 13:17:19 +0100 Subject: [PATCH 098/118] fix(owner-chat): show manual connector retry over stale failure Report queued manual refresh despite an older durable schema failure, avoid claiming permissions were verified, and log only safe typed connector-conflict categories. --- browser-companion/src/chatgpt-driver.ts | 5 ++ src/global_settings_ui.js | 2 +- src/owner_chat/settings.rs | 85 ++++++++++++++++++++----- 3 files changed, 74 insertions(+), 18 deletions(-) diff --git a/browser-companion/src/chatgpt-driver.ts b/browser-companion/src/chatgpt-driver.ts index 5a6f42cb..b7e8e226 100644 --- a/browser-companion/src/chatgpt-driver.ts +++ b/browser-companion/src/chatgpt-driver.ts @@ -602,6 +602,11 @@ export class ChatGptBrowserDriver implements BrowserDriver { console.error(`[connector-maintenance] ${label}: ${error.name}: ${detail}`); } const failure=asCompanionError(error); + // Typed browser conflicts previously disappeared behind a generic + // native HTTP 409. Record only the fixed phase label and failure code: + // never a tab URL, account identifier, connector name, or page text. + if(error instanceof BrowserCompanionError) + console.warn(`[connector-maintenance] ${label}: code=${failure.code}`); throw new BrowserCompanionError(`${label}: ${failure.message}`,failure.code,{cause:error}); }); const appId=await step("Identify connector",async(page,account,signal)=>{ diff --git a/src/global_settings_ui.js b/src/global_settings_ui.js index 77db0df6..4722a10a 100644 --- a/src/global_settings_ui.js +++ b/src/global_settings_ui.js @@ -556,7 +556,7 @@ body.system-progress-visible{height:100dvh;display:flex;flex-direction:column}bo else if(refresh?.phase==='failed')message(refresh.source==='manual'||refresh.source==='settings' ?refresh.result?.error||'Connector refresh failed. Use Refresh connector to retry.' :'Codexify updated, but connector refresh failed. Use Refresh connector to retry.',true); - else if(refresh?.phase==='completed')message('Connector refresh completed; Allow all tools is selected.'); + else if(refresh?.phase==='completed')message('Connector refresh completed. Check readiness for schema verification; permissions were not changed.'); } function renderPlan(plan) { const label=plan?.label?.trim()||'',node=byId('account-plan'); diff --git a/src/owner_chat/settings.rs b/src/owner_chat/settings.rs index b1922cfe..8980fa94 100644 --- a/src/owner_chat/settings.rs +++ b/src/owner_chat/settings.rs @@ -223,6 +223,36 @@ fn update_progress(current: Option<&Value>, intent: Option<&Value>) -> Option, + manual: Option, + recent: Option, + after_update: Option, +) -> Option { + let in_progress = |value: &Value| { + matches!( + value["phase"].as_str(), + Some("queued" | "running" | "starting_browser" | "waiting_for_restart") + ) + }; + if let Some(value) = manual.as_ref().filter(|value| in_progress(value)) { + return Some(value.clone()); + } + if let Some(value) = schema.as_ref().filter(|value| in_progress(value)) { + return Some(value.clone()); + } + if let Some(value) = manual.as_ref().filter(|value| value["phase"] == "failed") { + return Some(value.clone()); + } + if let Some(value) = schema.as_ref().filter(|value| value["phase"] == "failed") { + return Some(value.clone()); + } + manual.or(recent).or(after_update).or(schema) +} + pub(super) async fn status(State(state): State) -> ApiResult { let latest = crate::self_update::inspect_latest_version().await; let latest = match latest { @@ -235,23 +265,12 @@ pub(super) async fn status(State(state): State) -> ApiResult { let global = state.global.lock().await; let update_intent = crate::global_settings::read_refresh_intent(); let update = update_progress(global.update.as_ref(), update_intent.as_ref()); - let refresh = schema - .as_ref() - .filter(|value| { - matches!( - value["phase"].as_str(), - Some("queued" | "running" | "starting_browser" | "waiting_for_restart" | "failed") - ) - }) - .cloned() - .or_else(|| { - global - .manual_refresh - .clone() - .or_else(|| global.refresh.clone()) - .or_else(crate::global_settings::read_refresh_intent) - }) - .or(schema); + let refresh = visible_connector_refresh( + schema, + global.manual_refresh.clone(), + global.refresh.clone(), + crate::global_settings::read_refresh_intent(), + ); let plan = global.plan.clone(); drop(global); let (_, readiness) = super::readiness::snapshot(&state, refresh.as_ref()).await; @@ -563,6 +582,38 @@ mod tests { ); assert_eq!(update_progress(None, None), None); } + #[test] + fn manual_connector_retry_is_not_masked_by_old_schema_failure() { + let schema = json!({"phase":"failed","refreshId":"settings-old", + "result":{"error":"Old browser state changed"}}); + let manual = json!({"phase":"queued","refreshId":"manual-new","source":"manual"}); + assert_eq!( + visible_connector_refresh(Some(schema.clone()), Some(manual.clone()), None, None), + Some(manual.clone()), + ); + let running = json!({"phase":"running","refreshId":"manual-new","source":"manual"}); + assert_eq!( + visible_connector_refresh(Some(schema.clone()), Some(running.clone()), None, None), + Some(running), + ); + let new_failure = json!({"phase":"failed","refreshId":"manual-new","source":"manual", + "result":{"error":"Current refresh failed"}}); + assert_eq!( + visible_connector_refresh(Some(schema), Some(new_failure.clone()), None, None), + Some(new_failure), + ); + } + + #[test] + fn manual_completion_does_not_hide_an_unresolved_schema_barrier() { + let schema = json!({"phase":"failed","refreshId":"settings-old"}); + let manual = json!({"phase":"completed","refreshId":"manual-new", + "result":{"refreshObserved":true,"schemaVerified":false}}); + assert_eq!( + visible_connector_refresh(Some(schema.clone()), Some(manual), None, None), + Some(schema), + ); + } #[derive(Clone, Default)] struct RefreshFixture { mode: Arc, From 4a3c179b7286335c497843673cf626c0a3c3a35e Mon Sep 17 00:00:00 2001 From: tomi Date: Fri, 20 Nov 2026 13:53:54 +0100 Subject: [PATCH 099/118] fix(browser): reserve idle windows between handoff inspections Expose private authenticated lease diagnostics, prevent repeated handoff navigation from starving connector maintenance, and provide verified rollback-safe browser archive activation. --- .gitignore | 2 + .../scripts/activate-readiness-diagnostic.ps1 | 108 ++++++++++++++++++ browser-companion/src/browser-pool.ts | 37 ++++-- browser-companion/src/browser-window.ts | 16 +++ browser-companion/src/control-server.ts | 8 +- .../tests/control-server.test.ts | 93 +++++++++++++++ 6 files changed, 252 insertions(+), 12 deletions(-) create mode 100644 browser-companion/scripts/activate-readiness-diagnostic.ps1 diff --git a/.gitignore b/.gitignore index fdeb8f49..548ced1e 100644 --- a/.gitignore +++ b/.gitignore @@ -13,3 +13,5 @@ node_modules/ # Source archive drops (reference material, not part of the repo) *.zip /browser-companion/.browsers/ +/browser-companion/dist/ +/browser-companion/artifacts/ diff --git a/browser-companion/scripts/activate-readiness-diagnostic.ps1 b/browser-companion/scripts/activate-readiness-diagnostic.ps1 new file mode 100644 index 00000000..c7e2e6d6 --- /dev/null +++ b/browser-companion/scripts/activate-readiness-diagnostic.ps1 @@ -0,0 +1,108 @@ +# Deploy only the verified Codexify browser ASAR. Never replace the native service or Chrome profile. +$ErrorActionPreference = 'Stop' +$project = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '..')) +$receiptPath = Join-Path $project 'artifacts\runtime-patch-ready.json' +$receipt = Get-Content -LiteralPath $receiptPath -Raw | ConvertFrom-Json +$version = [string]$receipt.version +if ($version -ne '2.4.0') { throw 'Unexpected runtime version' } +$artifactRoot = [IO.Path]::GetFullPath((Join-Path $project 'artifacts')) + [IO.Path]::DirectorySeparatorChar +$candidate = [IO.Path]::GetFullPath([string]$receipt.candidate) +if (-not $candidate.StartsWith($artifactRoot, [StringComparison]::OrdinalIgnoreCase)) { + throw 'Candidate is outside verified project artifact root' +} +$resources = Join-Path $env:USERPROFILE ('.codexify\browser\runtime\' + $version + '\app\resources') +$live = Join-Path $resources 'app.asar' +$exe = Join-Path $env:USERPROFILE '.codexify\bin\codexify.exe' +if (-not (Test-Path -LiteralPath $candidate -PathType Leaf) -or -not (Test-Path -LiteralPath $live -PathType Leaf) -or -not (Test-Path -LiteralPath $exe -PathType Leaf)) { + throw 'Expected candidate, installed archive or CLI missing' +} +function Sha256([string]$path) { return (Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash.ToLowerInvariant() } +$beforeSha = Sha256 $live +$wantedSha = [string]$receipt.sha256 +if ($beforeSha -ne [string]$receipt.previousSha256 -or (Sha256 $candidate) -ne $wantedSha) { + throw 'Preimage or candidate hash does not match the verified receipt' +} +$stamp = [DateTime]::UtcNow.ToString('yyyyMMddTHHmmssZ') +$backupDir = Join-Path $env:USERPROFILE ('.codexify\backups\browser-readiness-diagnostic-' + $stamp) +[void](New-Item -ItemType Directory -Path $backupDir) +$backup = Join-Path $backupDir 'app.asar.original' +Copy-Item -LiteralPath $live -Destination $backup -ErrorAction Stop +if ((Sha256 $backup) -ne $beforeSha) { throw 'Rollback archive could not be verified' } +function Invoke-CompanionCommand([string]$verb) { + if ($verb -notin @('stop','start')) { throw 'Unsupported companion operation' } + $output = Join-Path $backupDir ($verb + '-stdout.log') + $errors = Join-Path $backupDir ($verb + '-stderr.log') + # The companion may inherit stdout from its launcher. Wait for the launcher + # process, not an open PowerShell pipeline attached to a long-lived browser. + $process = Start-Process -FilePath $exe -ArgumentList @('browser', $verb) -PassThru -WindowStyle Hidden -RedirectStandardOutput $output -RedirectStandardError $errors + if (-not $process.WaitForExit(45000)) { throw ('Companion ' + $verb + ' launcher did not exit') } + # Some Windows PowerShell process wrappers report a null ExitCode even after + # WaitForExit succeeds. Subsequent process/hash/HTTP checks prove the result. + if ($null -ne $process.ExitCode -and [int]$process.ExitCode -ne 0) { + if ($verb -eq 'start') { + # A busy but live companion sometimes returns a nonzero launcher status. + # Accept it only if the *new* private endpoint responds with liveness. + $descriptorFile = Join-Path $env:USERPROFILE '.codexify\browser\descriptor.json' + if (Test-Path -LiteralPath $descriptorFile) { + $descriptor = Get-Content -LiteralPath $descriptorFile -Raw | ConvertFrom-Json + try { + $liveness = Invoke-RestMethod -Uri ($descriptor.endpoint.TrimEnd('/') + '/v1/liveness') -Headers @{ Authorization = 'Bearer ' + $descriptor.token } -TimeoutSec 6 + if ($liveness.available -eq $true) { return } + } catch { } + } + } + throw ('Companion ' + $verb + ' launcher returned a failure') + } +} +$replaced = $false +$oldDesc = Join-Path $env:USERPROFILE '.codexify\browser\descriptor.json' +$oldPid = $null +if (Test-Path -LiteralPath $oldDesc) { + $previous = Get-Content -LiteralPath $oldDesc -Raw | ConvertFrom-Json + $oldPid = $previous.pid + $health = Invoke-RestMethod -Method Get -Uri ($previous.endpoint.TrimEnd('/') + '/v1/health') -Headers @{ Authorization = 'Bearer ' + $previous.token } -TimeoutSec 8 + if ($health.activeActionId -or @($health.activeActionIds).Count -gt 0) { + throw 'A browser action is active; companion replacement deferred' + } +} +Write-Output 'BACKUP_VERIFIED=true' +try { + Invoke-CompanionCommand 'stop' + if ($oldPid) { + for ($i=0;$i -lt 15;$i++) { + if (-not (Get-Process -Id $oldPid -ErrorAction SilentlyContinue)) { break } + Start-Sleep -Milliseconds 500 + } + if (Get-Process -Id $oldPid -ErrorAction SilentlyContinue) { throw 'Old browser companion process did not exit' } + } + $staging = Join-Path $resources ('app.asar.staged-' + $stamp) + Copy-Item -LiteralPath $candidate -Destination $staging -ErrorAction Stop + if ((Sha256 $staging) -ne $wantedSha) { throw 'Staged archive hash mismatch' } + $preimageAtomic = Join-Path $backupDir 'app.asar.atomic-original' + [IO.File]::Replace($staging, $live, $preimageAtomic, $true) + $replaced = $true + if ((Sha256 $live) -ne $wantedSha) { throw 'Installed archive verification failed' } + Invoke-CompanionCommand 'start' + Start-Sleep -Seconds 3 + $descriptor = Get-Content -LiteralPath $oldDesc -Raw | ConvertFrom-Json + $headers = @{ Authorization = 'Bearer ' + $descriptor.token } + $state = Invoke-RestMethod -Method Get -Uri ($descriptor.endpoint.TrimEnd('/') + '/v1/diagnostics/readiness') -Headers $headers -TimeoutSec 8 + Write-Output ('BROWSER_READINESS=' + ($state | ConvertTo-Json -Depth 6 -Compress)) + Write-Output 'INSTALLED_AND_DIAGNOSTIC_VERIFIED=true' + Write-Output ('ROLLBACK_LOCATION=' + $backupDir) +} catch { + Write-Output ('ACTIVATION_FAILED=' + $_.Exception.GetType().Name) + if ($replaced) { + try { + Invoke-CompanionCommand 'stop' + $restore = Join-Path $resources ('app.asar.restore-' + $stamp) + Copy-Item -LiteralPath $backup -Destination $restore -ErrorAction Stop + if ((Sha256 $restore) -ne $beforeSha) { throw 'Rollback archive hash mismatch' } + [IO.File]::Replace($restore, $live, (Join-Path $backupDir 'app.asar.rejected'), $true) + if ((Sha256 $live) -ne $beforeSha) { throw 'Rollback validation failed' } + Write-Output 'ROLLBACK_VERIFIED=true' + } catch { Write-Output ('ROLLBACK_FAILED=' + $_.Exception.GetType().Name) } + } + Invoke-CompanionCommand 'start' + throw +} diff --git a/browser-companion/src/browser-pool.ts b/browser-companion/src/browser-pool.ts index 26308ddd..7c81512d 100644 --- a/browser-companion/src/browser-pool.ts +++ b/browser-companion/src/browser-pool.ts @@ -5,7 +5,7 @@ import {canonicalChatGptConversationUrl,executeActionRequestSchema,cancelActionR COMPANION_KIND,PROTOCOL_VERSION,type CompanionHealth,type ActionSnapshot,type ExecuteActionRequest} from "./protocol"; type Coordinator = SingleWindowCoordinator; -type Lane = {coordinator:Coordinator;reserved:boolean;lastUsed:number}; +type Lane = {coordinator:Coordinator;reserved:boolean;reservationPurpose:"approval"|"handoff"|"action"|null;lastUsed:number}; type OwnedAction = {lane:Lane;digest:string;key:string;conversation:string}; /** Fixed pages share one private profile, while action state and DOM ownership @@ -20,13 +20,17 @@ export class PooledWindowCoordinator { private dispatchTail:Promise=Promise.resolve(); private maintenance=false; private closed=false; + private nextHandoffEligibleAt=0; - constructor(coordinators:readonly Coordinator[],readonly build:string,private readonly closeContext?:()=>Promise) { + constructor(coordinators:readonly Coordinator[],readonly build:string,private readonly closeContext?:()=>Promise,private readonly handoffGapMs=8_000) { if(coordinators.length<1||coordinators.length>4)throw new Error("Browser action pages must be between one and four"); - this.lanes=coordinators.map(coordinator=>({coordinator,reserved:false,lastUsed:0})); + if(!Number.isInteger(handoffGapMs)||handoffGapMs<0||handoffGapMs>30_000)throw new Error("Invalid browser handoff inspection gap"); + this.lanes=coordinators.map(coordinator=>({coordinator,reserved:false,reservationPurpose:null,lastUsed:0})); } private free(lane:Lane):boolean {return !lane.reserved&&!lane.coordinator.busy;} + /** Keep passive approval monitoring out of an already owned browser lane. */ + get busy():boolean {return this.closed||this.maintenance||this.lanes.some(l=>!this.free(l));} private capacity(health:CompanionHealth,available:number):CompanionHealth { const activeActionIds=this.lanes.map(l=>l.coordinator.ownedActionId).filter((id):id is string=>id!==null); return {...health,actionCapacity:this.lanes.length,availableActionSlots:available,activeActionIds, @@ -49,6 +53,12 @@ export class PooledWindowCoordinator { } health=()=>this.observe(false); readyHealth=()=>this.observe(true); + /** Authenticated local diagnostic; never read a page or expose account details. */ + readinessSnapshot() { + return {maintenance:this.maintenance,closed:this.closed, + handoffCooldownRemainingMs:Math.max(0,this.nextHandoffEligibleAt-Date.now()), + lanes:this.lanes.map(l=>({reserved:l.reserved,reservationPurpose:l.reservationPurpose,...l.coordinator.readinessSnapshot()}))}; + } async liveness() { const results=await Promise.all(this.lanes.map(l=>l.coordinator.liveness())); return {protocolVersion:PROTOCOL_VERSION,build:this.build,available:!this.closed&&results.some(r=>r.available)}; @@ -67,7 +77,11 @@ export class PooledWindowCoordinator { const entry=[...this.actions.values()].reverse().find(a=>a.conversation===key); return entry?.lane; } - private async onConversation(url:string,operation:(coordinator:Coordinator)=>Promise):Promise { + private async onConversation(url:string,operation:(coordinator:Coordinator)=>Promise,purpose:"approval"|"handoff"):Promise { + // Repeated unfinished handoff probes can otherwise monopolize the one + // shared browser tab. Deferral is an error, never a fake negative proof. + if(purpose==="handoff"&&Date.now()this.free(l)); if(this.closed||this.maintenance||!lane)throw new BrowserCompanionError("Browser companion action pages are busy"); - lane.reserved=true; + lane.reserved=true;lane.reservationPurpose=purpose; this.observations.add(key); - try {return await operation(lane.coordinator);}finally{this.observations.delete(key);lane.reserved=false;} + try {return await operation(lane.coordinator);}finally{ + if(purpose==="handoff")this.nextHandoffEligibleAt=Date.now()+this.handoffGapMs; + this.observations.delete(key);lane.reserved=false;lane.reservationPurpose=null; + } } login:Coordinator["login"]=signal=>this.exclusive(c=>c.login(signal)); capabilities:Coordinator["capabilities"]=signal=>this.exclusive(c=>c.capabilities(signal)); @@ -87,8 +104,8 @@ export class PooledWindowCoordinator { setPresentationStyle:Coordinator["setPresentationStyle"]=(css,signal)=>this.exclusive(c=>c.setPresentationStyle(css,signal)); presentation:Coordinator["presentation"]=(signal,screenshot)=>this.exclusive(c=>c.presentation(signal,screenshot)); reveal:Coordinator["reveal"]=(url,signal)=>this.exclusive(c=>c.reveal(url,signal)); - turnHandoffComplete:Coordinator["turnHandoffComplete"]=(url,account,id,signal)=>this.onConversation(url,c=>c.turnHandoffComplete(url,account,id,signal)); - approvePendingConversation:Coordinator["approvePendingConversation"]=(request,signal,navigate,once)=>this.onConversation(request.url,c=>c.approvePendingConversation(request,signal,navigate,once)); + turnHandoffComplete:Coordinator["turnHandoffComplete"]=(url,account,id,signal)=>this.onConversation(url,c=>c.turnHandoffComplete(url,account,id,signal),"handoff"); + approvePendingConversation:Coordinator["approvePendingConversation"]=(request,signal,navigate,once)=>this.onConversation(request.url,c=>c.approvePendingConversation(request,signal,navigate,once),"approval"); // Navigation budgets are shared by every page in the profile. navigationAvailability:Coordinator["navigationAvailability"]=url=>(this.laneFor(url)??this.lanes[0]!).coordinator.navigationAvailability(url); // A retained pairing window belongs to the page that created the chat. @@ -138,7 +155,7 @@ export class PooledWindowCoordinator { } if(this.actions.size>=this.lanes.length*1100)throw new Error("Browser action history is full"); } - lane.reserved=true;lane.lastUsed=Date.now(); + lane.reserved=true;lane.reservationPurpose="action";lane.lastUsed=Date.now(); // Persist pool ownership before any asynchronous page preflight. Failed // preflight can be retried only if the single-page coordinator recorded it. const owned={lane,digest,key:request.idempotencyKey,conversation}; @@ -149,7 +166,7 @@ export class PooledWindowCoordinator { this.actions.delete(request.actionId);this.keys.delete(request.idempotencyKey); } throw error; - } finally {lane.reserved=false;} + } finally {lane.reserved=false;lane.reservationPurpose=null;} } finally {release();} } private async owner(actionId:string):Promise { diff --git a/browser-companion/src/browser-window.ts b/browser-companion/src/browser-window.ts index fce87b83..707c67be 100644 --- a/browser-companion/src/browser-window.ts +++ b/browser-companion/src/browser-window.ts @@ -292,6 +292,22 @@ export class SingleWindowCoordinator { || this.actionCleanupPending || this.observationCleanupPending; } + /** Private, browser-free evidence for diagnosing a stuck lease. No page or account data. */ + readinessSnapshot() { + return { + busy:this.busy, + retired:this.retired, + activeAction:this.activeActionId !== null, + pendingAction:this.pendingActionId !== null, + windowOperationActive:this.windowOperationActive, + observationCleanupPending:this.observationCleanupPending, + actionCleanupPending:this.actionCleanupPending, + connectorRefreshPending:this.connectorRefreshPending, + driverClosed:this.driverClosed, + closing:this.closing, + }; + } + // An admitted action owns its page before its asynchronous preflight starts. get ownedActionId():string | null { return this.activeActionId ?? this.pendingActionId; } get retiredWindow():boolean {return this.retired;} diff --git a/browser-companion/src/control-server.ts b/browser-companion/src/control-server.ts index 01503b34..e8eb0f6c 100644 --- a/browser-companion/src/control-server.ts +++ b/browser-companion/src/control-server.ts @@ -13,7 +13,7 @@ import { createServer, type IncomingMessage, type Server, type ServerResponse } import { basename, dirname, join } from "node:path"; import { z } from "zod"; import { SingleWindowCoordinator } from "./browser-window"; -type BrowserCoordinator = Pick; +type BrowserCoordinator = Pick & {readinessSnapshot:()=>unknown}; import {validateNewChatProjectUrl} from "./new-chat"; import { asCompanionError,type BrowserStage,type BrowserFailureCode } from "./errors"; import { @@ -172,6 +172,9 @@ async function route( if(request.method === "GET" && url.pathname === "/v1/liveness") { json(response,200,await coordinator.liveness());return; } + if(request.method === "GET" && url.pathname === "/v1/diagnostics/readiness") { + json(response,200,coordinator.readinessSnapshot());return; + } if(request.method === "GET" && url.pathname === "/v1/diagnostics/presentation") { const screenshot=z.enum(["0","1"]).parse(url.searchParams.get("screenshot")??"0")==="1"; json(response,200,await coordinator.presentation(operation.signal,screenshot));return; @@ -205,7 +208,8 @@ async function route( } if(request.method === "POST" && url.pathname === "/v1/turns/handoff") { const body=z.strictObject({url:chatGptUrlSchema,expectedAccountFingerprint:opaqueIdSchema,handoffId:z.string().regex(/^renew-[a-f0-9]{64}$/)}).parse(await readJson(request)); - json(response,200,await coordinator.turnHandoffComplete(body.url,body.expectedAccountFingerprint,body.handoffId,operation.signal));return; + try {json(response,200,await coordinator.turnHandoffComplete(body.url,body.expectedAccountFingerprint,body.handoffId,operation.signal));} + catch(error){if(error instanceof Error&&error.message.toLowerCase().includes("busy"))throw new ClientError(423,"Handoff inspection deferred while the shared browser is busy");throw error;}return; } if(request.method === "POST" && url.pathname === "/v1/approvals/conversation") { const body=conversationApprovalRequestSchema.parse(await readJson(request)); diff --git a/browser-companion/tests/control-server.test.ts b/browser-companion/tests/control-server.test.ts index 0ab884f5..4c61d630 100644 --- a/browser-companion/tests/control-server.test.ts +++ b/browser-companion/tests/control-server.test.ts @@ -5,6 +5,7 @@ import { mkdtemp } from "node:fs/promises"; import { expect, test } from "bun:test"; import type { CapabilityCatalog, ConversationApprovalRequest, ExecuteActionRequest } from "../src/protocol"; import { SingleWindowCoordinator, type BrowserDriver, type DriverExecution } from "../src/browser-window"; +import {PooledWindowCoordinator} from "../src/browser-pool"; import { startControlServer } from "../src/control-server"; import { protocolBuild } from "../src/protocol"; import { BrowserCompanionError } from "../src/errors"; @@ -75,6 +76,98 @@ class BlockingDriver extends ImmediateDriver { } } +test("private readiness diagnostic identifies maintenance without an action or account data",async()=>{ + let entered!:()=>void,release!:()=>void; + const enteredPromise=new Promise(resolve=>entered=resolve); + const gate=new Promise(resolve=>release=resolve); + class MaintenanceDriver extends ImmediateDriver { + override async capabilities():Promise { + entered(); + await gate; + return super.capabilities(); + } + } + const root=await mkdtemp(join(tmpdir(),"browser-readiness-")); + const coordinator=new PooledWindowCoordinator([new SingleWindowCoordinator(new MaintenanceDriver(),TEST_BUILD)],TEST_BUILD); + const server=await startControlServer(coordinator,join(root,"descriptor.json")); + try { + const url=server.endpoint+"/v1/diagnostics/readiness"; + expect((await fetch(url)).status).toBe(401); + const headers={Authorization:"Bearer "+server.token}; + expect(await(await fetch(url,{headers})).json()).toMatchObject({ + maintenance:false,closed:false,lanes:[{reserved:false,busy:false,windowOperationActive:false}], + }); + const task=coordinator.capabilities(); + await enteredPromise; + const blocked=await(await fetch(url,{headers})).json(); + expect(blocked).toMatchObject({ + maintenance:true,lanes:[{busy:true,windowOperationActive:true,activeAction:false,pendingAction:false}], + }); + expect(JSON.stringify(blocked)).not.toContain("account-test"); + expect(JSON.stringify(blocked)).not.toContain("chatgpt.com"); + release(); + await task; + expect(await(await fetch(url,{headers})).json()).toMatchObject({ + maintenance:false,lanes:[{busy:false,windowOperationActive:false}], + }); + }finally{release();await server.close();} +}); + +test("readiness identifies a handoff reservation without revealing conversation identifiers",async()=>{ + let entered!:()=>void,release!:()=>void; + const started=new Promise(resolve=>entered=resolve); + const gate=new Promise(resolve=>release=resolve); + class HandoffDriver extends ImmediateDriver { + async turnHandoffComplete(){ + entered(); + await gate; + return false; + } + } + const root=await mkdtemp(join(tmpdir(),"browser-handoff-readiness-")); + const coordinator=new PooledWindowCoordinator([new SingleWindowCoordinator(new HandoffDriver(),TEST_BUILD)],TEST_BUILD); + const server=await startControlServer(coordinator,join(root,"descriptor.json")); + const url="https://chatgpt.com/c/private-handoff"; + try { + const pending=coordinator.turnHandoffComplete(url,"account-test","renew-"+ "f".repeat(64)); + await started; + const state=await(await fetch(server.endpoint+"/v1/diagnostics/readiness",{headers:{Authorization:"Bearer "+server.token}})).json(); + expect(coordinator.busy).toBe(true); + expect(state).toMatchObject({maintenance:false,lanes:[{ + reserved:true,reservationPurpose:"handoff",activeAction:false,pendingAction:false,windowOperationActive:true, + }]}); + expect(JSON.stringify(state)).not.toContain("private-handoff"); + release(); + await pending; + expect(coordinator.busy).toBe(false); + }finally{release();await server.close();} +}); + +test("handoff probes defer with HTTP 423 instead of manufacturing a negative receipt",async()=>{ + let reads=0; + class HandoffDriver extends ImmediateDriver { + async turnHandoffComplete(){reads++;return false;} + } + const root=await mkdtemp(join(tmpdir(),"browser-handoff-gap-")); + const coordinator=new PooledWindowCoordinator([new SingleWindowCoordinator(new HandoffDriver(),TEST_BUILD)],TEST_BUILD,undefined,45); + const server=await startControlServer(coordinator,join(root,"descriptor.json")); + const headers={Authorization:"Bearer "+server.token,"Content-Type":"application/json"}; + const body=JSON.stringify({url:"https://chatgpt.com/c/handoff-gap",expectedAccountFingerprint:"account-test",handoffId:"renew-"+"f".repeat(64)}); + const request=()=>fetch(server.endpoint+"/v1/turns/handoff",{method:"POST",headers,body}); + try { + expect((await request()).status).toBe(200); + const deferred=await request(); + expect(deferred.status).toBe(423); + expect(reads).toBe(1); + expect((await coordinator.readinessSnapshot()).handoffCooldownRemainingMs).toBeGreaterThan(0); + // Delaying a handoff must leave exclusive maintenance and refresh free to run. + expect((await coordinator.capabilities()).models).toHaveLength(1); + await Bun.sleep(65); + expect((await request()).status).toBe(200); + expect(reads).toBe(2); + }finally{await server.close();} +}); + test("pairing lease renewal is authenticated and preserves the held page",async()=>{ class PairDriver extends ImmediateDriver { override async execute(execution:DriverExecution){ From 85d652f4de1fc2c8ac7c5fd2dd2b50abba72f4bb Mon Sep 17 00:00:00 2001 From: tomi Date: Fri, 20 Nov 2026 15:00:33 +0100 Subject: [PATCH 100/118] fix(owner-chat): require verified idle browser before connector refresh Show current manual refresh readiness in health and reject unsigned-in or unavailable browser sessions rather than treating them as refreshable. Cover action ownership and slot checks with regression cases. --- src/owner_chat/settings.rs | 80 +++++++++++++++++++++++++++++++++++--- 1 file changed, 74 insertions(+), 6 deletions(-) diff --git a/src/owner_chat/settings.rs b/src/owner_chat/settings.rs index 8980fa94..c401dc1c 100644 --- a/src/owner_chat/settings.rs +++ b/src/owner_chat/settings.rs @@ -201,7 +201,9 @@ pub(super) fn start(state: OwnerState) { pub(super) async fn health(State(state): State) -> ApiResult { let schema = crate::global_settings::read_schema_intent(&state.config); - let (mut body, readiness) = super::readiness::snapshot(&state, schema.as_ref()).await; + let manual = state.global.lock().await.manual_refresh.clone(); + let refresh = visible_connector_refresh(schema, manual, None, None); + let (mut body, readiness) = super::readiness::snapshot(&state, refresh.as_ref()).await; body["readiness"] = readiness; if let Some(automation) = &state.automation { body["automationActivity"] = @@ -519,6 +521,32 @@ async fn set_manual_refresh_phase( } } +fn check_manual_refresh_readiness( + health: &crate::agent_automation::CompanionHealth, +) -> Result<(), String> { + use crate::agent_automation::CompanionSessionStatus; + match health.status { + CompanionSessionStatus::Busy => Err("Browser companion is busy".into()), + CompanionSessionStatus::Unavailable => { + Err("Browser companion is unavailable; check Browser settings".into()) + } + CompanionSessionStatus::AuthenticationRequired => { + Err("ChatGPT sign-in is required in the browser companion".into()) + } + CompanionSessionStatus::Idle if !health.authenticated => { + Err("ChatGPT sign-in could not be verified in the browser companion".into()) + } + CompanionSessionStatus::Idle + if health.active_action_id.is_some() + || !health.active_action_ids.is_empty() + || health.free_action_slots() == 0 => + { + Err("Browser companion is busy".into()) + } + CompanionSessionStatus::Idle => Ok(()), + } +} + async fn run_manual_refresh(state: OwnerState, id: String, retry_after: Duration) { loop { let result = async { @@ -527,11 +555,7 @@ async fn run_manual_refresh(state: OwnerState, id: String, retry_after: Duration // while Chrome is warming. The refresh scheduler needs the fresh // idle/account observation before deciding to requeue this job. let health = client.ready_health(&CancellationToken::new()).await?; - if health.active_action_id.is_some() - || health.status == crate::agent_automation::CompanionSessionStatus::Busy - { - return Err("Browser companion is busy".to_string()); - } + check_manual_refresh_readiness(&health)?; set_manual_refresh_phase(&state, &id, "running", None).await; refresh_saved_connector(&state, &client).await } @@ -614,6 +638,50 @@ mod tests { Some(schema), ); } + #[test] + fn manual_refresh_requires_a_fresh_authenticated_free_browser_lane() { + let fixture = |status: &str, authenticated: bool, slots: usize, active: Vec<&str>| { + serde_json::from_value::(json!({ + "protocolVersion":1,"kind":"codexify-browser-companion", + "build":"test","status":status,"authenticated":authenticated, + "accountFingerprint":if authenticated {Some("account")} else {None}, + "activeActionId":null,"activeActionIds":active, + "availableActionSlots":slots,"actionCapacity":1, + })) + .unwrap() + }; + assert!(check_manual_refresh_readiness(&fixture("idle", true, 1, vec![])).is_ok()); + assert!( + check_manual_refresh_readiness(&fixture("busy", true, 0, vec![])) + .unwrap_err() + .contains("busy") + ); + assert!( + check_manual_refresh_readiness(&fixture("idle", true, 0, vec![])) + .unwrap_err() + .contains("busy") + ); + assert!( + check_manual_refresh_readiness(&fixture("idle", true, 1, vec!["owned"])) + .unwrap_err() + .contains("busy") + ); + assert!( + check_manual_refresh_readiness(&fixture("idle", false, 1, vec![])) + .unwrap_err() + .contains("sign-in") + ); + assert!( + check_manual_refresh_readiness(&fixture("authentication_required", false, 0, vec![])) + .unwrap_err() + .contains("sign-in") + ); + assert!( + check_manual_refresh_readiness(&fixture("unavailable", false, 0, vec![])) + .unwrap_err() + .contains("unavailable") + ); + } #[derive(Clone, Default)] struct RefreshFixture { mode: Arc, From 15bac7830549a6b220e058a34611d042471ba834 Mon Sep 17 00:00:00 2001 From: tomi Date: Fri, 20 Nov 2026 15:20:03 +0100 Subject: [PATCH 101/118] ops(windows): guard local native readiness deployment with rollback --- .../windows-deploy-native-readiness-fix.ps1 | 142 ++++++++++++++++++ 1 file changed, 142 insertions(+) create mode 100644 scripts/windows-deploy-native-readiness-fix.ps1 diff --git a/scripts/windows-deploy-native-readiness-fix.ps1 b/scripts/windows-deploy-native-readiness-fix.ps1 new file mode 100644 index 00000000..2841bf8d --- /dev/null +++ b/scripts/windows-deploy-native-readiness-fix.ps1 @@ -0,0 +1,142 @@ +param([Parameter(Mandatory=$true)][string]$Candidate,[switch]$Deploy) +$ErrorActionPreference='Stop' +$ProgressPreference='SilentlyContinue' +$root=Join-Path $env:USERPROFILE '.codexify' +$live=Join-Path $root 'bin\codexify.exe' +$rootFull=[IO.Path]::GetFullPath($root) +$candidateFull=[IO.Path]::GetFullPath($Candidate) +$project=[IO.Path]::GetFullPath((Join-Path $PSScriptRoot '..')) +if(-not $candidateFull.StartsWith((Join-Path $project 'target\debug\'),[StringComparison]::OrdinalIgnoreCase) -or + [IO.Path]::GetFileName($candidateFull) -cne 'codexify.exe'){ + throw 'Candidate must be the verified local Codexify debug executable' +} +foreach($p in @($live,$candidateFull)){ + if(-not(Test-Path -LiteralPath $p -PathType Leaf)){throw 'Required native executable missing'} + if((Get-Item -LiteralPath $p).Length -lt 10000000){throw 'Native binary unexpectedly small'} +} +function Hash([string]$path){return (Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash.ToLowerInvariant()} +$oldHash=Hash $live +$newHash=Hash $candidateFull +if($oldHash -eq $newHash){Write-Output 'ALREADY_INSTALLED=true';return} +if(-not $Deploy){ + Write-Output ('DRY_RUN_CANDIDATE_SHA='+$newHash) + Write-Output ('DRY_RUN_INSTALLED_SHA='+$oldHash) + Write-Output 'NO_SERVICE_OR_FILE_CHANGES=true' + return +} +$backup=Join-Path $root ('backups\native-readiness-fix-'+[DateTime]::UtcNow.ToString('yyyyMMddTHHmmssZ')) +[void](New-Item -ItemType Directory -Path $backup) +$old=Join-Path $backup 'codexify.before.exe' +$failed=Join-Path $backup 'codexify.failed.exe' +$stage=Join-Path $root 'bin\codexify.incoming-readiness.exe' +if(Test-Path -LiteralPath $stage){throw 'A staged native executable already exists; aborting'} +Copy-Item -LiteralPath $live -Destination $old +if((Hash $old) -ne $oldHash){throw 'Rollback executable hash mismatch'} +Copy-Item -LiteralPath $candidateFull -Destination $stage +if((Hash $stage) -ne $newHash){throw 'Staged executable hash mismatch'} +$oldReceipt=@{beforeSha=$oldHash;afterSha=$newHash;startUtc=[DateTime]::UtcNow.ToString('o');phase='prepared';backup=$backup} +$oldReceipt|ConvertTo-Json -Depth 5|Set-Content -LiteralPath (Join-Path $backup 'receipt.json') +function RunCli([string]$exe,[string[]]$arguments){ + $stdout=Join-Path $backup (($arguments -join '-')+'.stdout') + $stderr=Join-Path $backup (($arguments -join '-')+'.stderr') + $p=Start-Process -FilePath $exe -ArgumentList $arguments -WindowStyle Hidden -PassThru -RedirectStandardOutput $stdout -RedirectStandardError $stderr + $null=$p.Handle + if(-not $p.WaitForExit(60000)){throw 'Codexify CLI did not exit within deadline'} + $p.Refresh() + if($null -ne $p.ExitCode -and $p.ExitCode -ne 0){throw ('Codexify CLI failed; inspect '+$stderr)} +} +function Ready { + try { + $h=Invoke-RestMethod -Uri 'http://127.0.0.1:3000/health' -TimeoutSec 4 + return $h.status -eq 'ok' + } catch{return $false} +} +function Idle { + try { + $h=Invoke-RestMethod -Uri 'http://127.0.0.1:3000/health' -TimeoutSec 5 + if($h.status -ne 'ok' -or $h.filesystem.occupiedWorkerSlots -gt 0 -or $h.filesystem.queuedRequests -gt 0){return $false} + foreach($u in $h.upstreams.PSObject.Properties){if($u.Value.activeRequests -gt 0 -or $u.Value.queuedRequests -gt 0){return $false}} + $desc=Join-Path $root 'browser\descriptor.json' + if(Test-Path -LiteralPath $desc){ + $d=Get-Content -LiteralPath $desc -Raw|ConvertFrom-Json + $state=Invoke-RestMethod -Uri ($d.endpoint.TrimEnd('/')+'/v1/health') -Headers @{Authorization='Bearer '+$d.token} -TimeoutSec 5 + if($state.status -ne 'idle' -or -not $state.authenticated -or $state.availableActionSlots -lt 1 -or + $state.activeActionId -or @($state.activeActionIds).Count -gt 0){return $false} + } + return $true + }catch{return $false} +} +$stopped=$false +$replaced=$false +try { + Write-Output 'STAGE_VERIFIED=true' + $deadline=[DateTime]::UtcNow.AddMinutes(3) + while(-not(Idle) -and [DateTime]::UtcNow -lt $deadline){Start-Sleep -Seconds 3} + if(-not(Idle)){throw 'Native or browser activity remained busy; original service preserved'} + Write-Output 'IDLE_WINDOW_VERIFIED=true' + $stopped=$true + RunCli $live @('service','stop') + $deadline=[DateTime]::UtcNow.AddSeconds(45) + while([DateTime]::UtcNow -lt $deadline){ + $p=@(Get-CimInstance Win32_Process -Filter "Name='codexify.exe'"|Where-Object {$_.ExecutablePath -ieq $live}) + if($p.Count -eq 0){break} + Start-Sleep -Milliseconds 500 + } + if($p.Count -ne 0){throw 'Original Codexify service did not stop; binary untouched'} + if((Hash $live) -ne $oldHash){throw 'Installed binary changed after the preflight; refusing replacement'} + # File.Replace is an atomic same-volume swap; an interrupted copy cannot + # leave the only installed executable missing. + [IO.File]::Replace($stage,$live,(Join-Path $backup 'codexify.original-slot.exe'),$true) + $replaced=$true + if((Hash $live) -ne $newHash){throw 'Installed executable hash mismatch'} + RunCli $live @('service','start') + $deadline=[DateTime]::UtcNow.AddSeconds(80) + while(-not(Ready) -and [DateTime]::UtcNow -lt $deadline){Start-Sleep -Seconds 2} + if(-not(Ready)){throw 'Updated native service did not reach healthy status'} + $descriptorPath=Join-Path $root 'browser\descriptor.json' + $browserLive=$false + if(Test-Path -LiteralPath $descriptorPath){ + try { + $d=Get-Content -LiteralPath $descriptorPath -Raw|ConvertFrom-Json + $l=Invoke-RestMethod -Uri ($d.endpoint.TrimEnd('/')+'/v1/liveness') -Headers @{Authorization='Bearer '+$d.token} -TimeoutSec 6 + $browserLive=$l.available -eq $true + }catch{} + } + if(-not $browserLive){ + RunCli $live @('browser','start') + Start-Sleep -Seconds 3 + $d=Get-Content -LiteralPath $descriptorPath -Raw|ConvertFrom-Json + $l=Invoke-RestMethod -Uri ($d.endpoint.TrimEnd('/')+'/v1/liveness') -Headers @{Authorization='Bearer '+$d.token} -TimeoutSec 6 + if($l.available -ne $true){throw 'Browser companion liveness was not restored'} + } + $oldReceipt.phase='completed';$oldReceipt.endUtc=[DateTime]::UtcNow.ToString('o') + $oldReceipt|ConvertTo-Json -Depth 5|Set-Content -LiteralPath (Join-Path $backup 'receipt.json') + Write-Output ('NATIVE_INSTALLED_AND_HEALTHY=true;BACKUP='+$backup) +} catch { + $failure=$_.Exception.Message + Write-Output ('INSTALL_FAILURE='+$failure) + $oldReceipt.phase='failed';$oldReceipt.error=$failure + if($replaced){ + try { + try {RunCli $live @('service','stop')} catch {} + Start-Sleep -Seconds 2 + $alive=@(Get-CimInstance Win32_Process -Filter "Name='codexify.exe'"|Where-Object {$_.ExecutablePath -ieq $live}) + if($alive.Count){throw 'Replacement still executing; no overwrite performed'} + Move-Item -LiteralPath $live -Destination $failed + Copy-Item -LiteralPath $old -Destination $live + if((Hash $live) -ne $oldHash){throw 'Rollback verification failed'} + RunCli $live @('service','start') + Write-Output 'ROLLBACK_BINARY_VERIFIED=true' + $oldReceipt.phase='rolled_back' + }catch{ + $oldReceipt.rollbackError=$_.Exception.Message + Write-Output ('ROLLBACK_REQUIRES_ATTENTION='+$_.Exception.Message) + } + }elseif($stopped){ + try {RunCli $live @('service','start')}catch {Write-Output ('SERVICE_RESTART_FAILED='+$_.Exception.Message)} + } + $oldReceipt|ConvertTo-Json -Depth 5|Set-Content -LiteralPath (Join-Path $backup 'receipt.json') + throw +} finally{ + if(Test-Path -LiteralPath $stage){Remove-Item -LiteralPath $stage -Force -ErrorAction SilentlyContinue} +} From 4e9d8c64a546c844cdd9b8f9af9a79d3b0225a88 Mon Sep 17 00:00:00 2001 From: tomi Date: Fri, 20 Nov 2026 18:09:48 +0100 Subject: [PATCH 102/118] fix(windows): isolate native service replacement from its job Use an independent on-demand launcher, verify exact stale process ownership before any forced stop, and defer replacement while live tool child commands are still running. --- .../windows-deploy-native-readiness-fix.ps1 | 112 +++++++++++++++++- .../windows-native-readiness-task-wrapper.ps1 | 37 ++++++ 2 files changed, 146 insertions(+), 3 deletions(-) create mode 100644 scripts/windows-native-readiness-task-wrapper.ps1 diff --git a/scripts/windows-deploy-native-readiness-fix.ps1 b/scripts/windows-deploy-native-readiness-fix.ps1 index 2841bf8d..bcc7bd07 100644 --- a/scripts/windows-deploy-native-readiness-fix.ps1 +++ b/scripts/windows-deploy-native-readiness-fix.ps1 @@ -24,6 +24,20 @@ if(-not $Deploy){ Write-Output 'NO_SERVICE_OR_FILE_CHANGES=true' return } +# A native service replacement kills its owning Windows Job Object. When this +# installer is spawned by a Codexify tool, it belongs to the same tree and +# may be terminated halfway through the atomic swap. Require an independent +# launcher (for example, a temporary one-shot Task Scheduler task). +$ancestorPid=[int]$PID +for($depth=0;$depth -lt 16;$depth++){ + $ancestor=Get-CimInstance Win32_Process -Filter ('ProcessId='+$ancestorPid) + if(-not $ancestor){break} + if($ancestor.ExecutablePath -ieq $live){ + throw 'Refusing native replacement from inside its own service process tree; use independent maintenance launcher' + } + if(-not $ancestor.ParentProcessId -or [int]$ancestor.ParentProcessId -eq $ancestorPid){break} + $ancestorPid=[int]$ancestor.ParentProcessId +} $backup=Join-Path $root ('backups\native-readiness-fix-'+[DateTime]::UtcNow.ToString('yyyyMMddTHHmmssZ')) [void](New-Item -ItemType Directory -Path $backup) $old=Join-Path $backup 'codexify.before.exe' @@ -51,11 +65,42 @@ function Ready { return $h.status -eq 'ok' } catch{return $false} } +function Active-NativeChildCommands { + # Native /health can report zero occupied MCP slots while tool sessions still + # own long-running subprocesses (pytest, cargo, shell, etc.). Never terminate + # the listener in that state. Persistent upstream servers created during the + # native startup grace period are not treated as unfinished user commands. + $listenerId=Get-NetTCPConnection -State Listen -LocalPort 3000 -ErrorAction Stop | + Select-Object -First 1 -ExpandProperty OwningProcess + if(-not $listenerId){return $true} + $listener=Get-CimInstance Win32_Process -Filter ('ProcessId='+[int]$listenerId) + if(-not $listener){return $true} + $supervisor=Get-CimInstance Win32_Process -Filter ('ProcessId='+[int]$listener.ParentProcessId) + if(-not $supervisor -or $supervisor.ExecutablePath -ine $live){return $true} + $startupCutoff=$supervisor.CreationDate.AddMinutes(5) + $all=@(Get-CimInstance Win32_Process) + $descendants=[Collections.Generic.HashSet[int]]::new() + [void]$descendants.Add([int]$listenerId) + do { + $changed=$false + foreach($process in $all){ + if($descendants.Contains([int]$process.ParentProcessId) -and + $descendants.Add([int]$process.ProcessId)){$changed=$true} + } + }while($changed) + $commands=@($all | Where-Object { + $_.ProcessId -ne $listenerId -and $descendants.Contains([int]$_.ProcessId) -and + $_.CreationDate -ge $startupCutoff -and + $_.Name -match '^(powershell|pwsh|cmd|python|pytest|uv|cargo|rustc|git|node|bun|link|ninja|make|wsl)(\.exe)?$' + }) + return $commands.Count -gt 0 +} function Idle { try { $h=Invoke-RestMethod -Uri 'http://127.0.0.1:3000/health' -TimeoutSec 5 if($h.status -ne 'ok' -or $h.filesystem.occupiedWorkerSlots -gt 0 -or $h.filesystem.queuedRequests -gt 0){return $false} foreach($u in $h.upstreams.PSObject.Properties){if($u.Value.activeRequests -gt 0 -or $u.Value.queuedRequests -gt 0){return $false}} + if(Active-NativeChildCommands){return $false} $desc=Join-Path $root 'browser\descriptor.json' if(Test-Path -LiteralPath $desc){ $d=Get-Content -LiteralPath $desc -Raw|ConvertFrom-Json @@ -66,6 +111,48 @@ function Idle { return $true }catch{return $false} } +function Stop-VerifiedUnresponsiveNativePair { + # The installed service's Windows Stop-ScheduledTask script suppresses + # errors, so a successful CLI receipt does not prove that its processes quit. + # Only terminate the exact installed supervisor/listener pair that was + # verified *before* invoking service stop, and only if no work is active. + if(-not(Idle)){throw 'Native/browser work became active; refusing forced native stop'} + $task=Get-ScheduledTask -TaskName 'Codexify' -TaskPath '\' -ErrorAction Stop + if(-not $task.Settings.Enabled -or $task.Principal.LogonType -ne 'Interactive' -or + $task.Principal.RunLevel -ne 'Limited' -or + [IO.Path]::GetFullPath([string]$task.Actions[0].WorkingDirectory) -ine [IO.Path]::GetFullPath($root) -or + [IO.Path]::GetFullPath([string]$task.Actions[0].Execute) -ine (Join-Path $env:WINDIR 'System32\WindowsPowerShell\v1.0\powershell.exe')){ + throw 'Installed scheduled task identity is not trusted for a native stop' + } + $owners=@(Get-NetTCPConnection -State Listen -ErrorAction Stop | + Where-Object {$_.LocalPort -in @(3000,3120)} | Select-Object -ExpandProperty OwningProcess -Unique) + if($owners.Count -ne 1){throw 'Unexpected owner of Codexify listening ports'} + $listener=Get-CimInstance Win32_Process -Filter ('ProcessId='+[int]$owners[0]) + if(-not $listener -or $listener.ExecutablePath -ine $live){throw 'Listener executable changed'} + $supervisor=Get-CimInstance Win32_Process -Filter ('ProcessId='+[int]$listener.ParentProcessId) + if(-not $supervisor -or $supervisor.ExecutablePath -ine $live -or + $supervisor.CommandLine -notmatch 'service run --config'){ + throw 'Native supervisor identity changed' + } + $pair=@(Get-CimInstance Win32_Process -Filter "Name='codexify.exe'" | + Where-Object {$_.ExecutablePath -ieq $live}) + if($pair.Count -ne 2 -or ($pair.ProcessId -notcontains $listener.ProcessId) -or + ($pair.ProcessId -notcontains $supervisor.ProcessId)){ + throw 'More than the verified supervisor and listener are running' + } + # Verify PID ownership again immediately before termination. Never kill a + # later process that reused a PID. + foreach($verified in @($listener,$supervisor)){ + $current=Get-CimInstance Win32_Process -Filter ('ProcessId='+[int]$verified.ProcessId) + if(-not $current -or $current.ExecutablePath -ine $live -or + $current.CreationDate -ne $verified.CreationDate){ + throw 'Native process identity changed before stop' + } + } + Stop-Process -Id $supervisor.ProcessId -Force -ErrorAction Stop + Stop-Process -Id $listener.ProcessId -Force -ErrorAction Stop + Write-Output 'VERIFIED_STALE_NATIVE_PAIR_STOPPED=true' +} $stopped=$false $replaced=$false try { @@ -74,14 +161,30 @@ try { while(-not(Idle) -and [DateTime]::UtcNow -lt $deadline){Start-Sleep -Seconds 3} if(-not(Idle)){throw 'Native or browser activity remained busy; original service preserved'} Write-Output 'IDLE_WINDOW_VERIFIED=true' + $originalNative=@(Get-CimInstance Win32_Process -Filter "Name='codexify.exe'"| + Where-Object {$_.ExecutablePath -ieq $live}) $stopped=$true RunCli $live @('service','stop') - $deadline=[DateTime]::UtcNow.AddSeconds(45) + $deadline=[DateTime]::UtcNow.AddSeconds(9) while([DateTime]::UtcNow -lt $deadline){ $p=@(Get-CimInstance Win32_Process -Filter "Name='codexify.exe'"|Where-Object {$_.ExecutablePath -ieq $live}) if($p.Count -eq 0){break} Start-Sleep -Milliseconds 500 } + if($p.Count -gt 0){ + $currentIds=@($p | Select-Object -ExpandProperty ProcessId | Sort-Object) -join ',' + $originalIds=@($originalNative | Select-Object -ExpandProperty ProcessId | Sort-Object) -join ',' + if($currentIds -ne $originalIds){ + throw 'A new native process started during service stop; binary untouched' + } + Stop-VerifiedUnresponsiveNativePair + $deadline=[DateTime]::UtcNow.AddSeconds(12) + do { + $p=@(Get-CimInstance Win32_Process -Filter "Name='codexify.exe'"|Where-Object {$_.ExecutablePath -ieq $live}) + if($p.Count -eq 0){break} + Start-Sleep -Milliseconds 500 + }while([DateTime]::UtcNow -lt $deadline) + } if($p.Count -ne 0){throw 'Original Codexify service did not stop; binary untouched'} if((Hash $live) -ne $oldHash){throw 'Installed binary changed after the preflight; refusing replacement'} # File.Replace is an atomic same-volume swap; an interrupted copy cannot @@ -122,8 +225,11 @@ try { Start-Sleep -Seconds 2 $alive=@(Get-CimInstance Win32_Process -Filter "Name='codexify.exe'"|Where-Object {$_.ExecutablePath -ieq $live}) if($alive.Count){throw 'Replacement still executing; no overwrite performed'} - Move-Item -LiteralPath $live -Destination $failed - Copy-Item -LiteralPath $old -Destination $live + $restore=Join-Path $root 'bin\codexify.restore-readiness.exe' + if(Test-Path -LiteralPath $restore){throw 'A native rollback stage already exists'} + Copy-Item -LiteralPath $old -Destination $restore + if((Hash $restore) -ne $oldHash){throw 'Rollback stage hash mismatch'} + [IO.File]::Replace($restore,$live,$failed,$true) if((Hash $live) -ne $oldHash){throw 'Rollback verification failed'} RunCli $live @('service','start') Write-Output 'ROLLBACK_BINARY_VERIFIED=true' diff --git a/scripts/windows-native-readiness-task-wrapper.ps1 b/scripts/windows-native-readiness-task-wrapper.ps1 new file mode 100644 index 00000000..ab54deb8 --- /dev/null +++ b/scripts/windows-native-readiness-task-wrapper.ps1 @@ -0,0 +1,37 @@ +param( + [Parameter(Mandatory=$true)][string]$Candidate, + [Parameter(Mandatory=$true)][string]$ReportDirectory, + [switch]$Deploy +) +$ErrorActionPreference='Stop' +$ProgressPreference='SilentlyContinue' +$root=Join-Path $env:USERPROFILE '.codexify\backups' +$report=[IO.Path]::GetFullPath($ReportDirectory) +if(-not $report.StartsWith(([IO.Path]::GetFullPath($root).TrimEnd('\')+'\'),[StringComparison]::OrdinalIgnoreCase)){ + throw 'Maintenance report path is not under Codexify backups' +} +[void](New-Item -ItemType Directory -Path $report -Force) +$log=Join-Path $report ($(if($Deploy){'deploy'}else{'dryrun'})+'.log') +function Record([string]$message) { + $line=([DateTime]::UtcNow.ToString('o')+' '+$message) + Add-Content -LiteralPath $log -Value $line -Encoding UTF8 + Write-Output $line +} +$parent=Get-CimInstance Win32_Process -Filter ('ProcessId='+$PID) +$parentPid=if($parent){[int]$parent.ParentProcessId}else{0} +$ancestor=if($parentPid){Get-CimInstance Win32_Process -Filter ('ProcessId='+$parentPid)}else{$null} +Record ('MAINTENANCE_MODE='+$(if($Deploy){'deploy'}else{'dryrun'})+ + ' SCRIPT_PID='+$PID+' PARENT_PID='+$parentPid+ + ' PARENT_IMAGE='+$(if($ancestor){$ancestor.Name}else{'unknown'})) +$installer=Join-Path $PSScriptRoot 'windows-deploy-native-readiness-fix.ps1' +try { + & $installer -Candidate $Candidate -Deploy:$Deploy 2>&1 | ForEach-Object { + $line=($_|Out-String).Trim() + if($line){Record $line} + } + Record 'MAINTENANCE_RESULT=completed' + exit 0 +} catch { + Record ('MAINTENANCE_RESULT=failed ERROR='+$_.Exception.Message) + exit 1 +} From c4b311afc4f6a1c7e9376523cd1c06236216bdd2 Mon Sep 17 00:00:00 2001 From: tomi Date: Fri, 20 Nov 2026 18:28:41 +0100 Subject: [PATCH 103/118] ops(windows): allow expressly authorized native command interruption Use the existing independent maintenance task to restart safely after user authorization, retaining browser Send gates, hash backups and rollback. --- .../windows-deploy-native-readiness-fix.ps1 | 29 +++++++++++++++---- .../windows-native-readiness-task-wrapper.ps1 | 5 ++-- 2 files changed, 27 insertions(+), 7 deletions(-) diff --git a/scripts/windows-deploy-native-readiness-fix.ps1 b/scripts/windows-deploy-native-readiness-fix.ps1 index bcc7bd07..eac3c756 100644 --- a/scripts/windows-deploy-native-readiness-fix.ps1 +++ b/scripts/windows-deploy-native-readiness-fix.ps1 @@ -1,4 +1,4 @@ -param([Parameter(Mandatory=$true)][string]$Candidate,[switch]$Deploy) +param([Parameter(Mandatory=$true)][string]$Candidate,[switch]$Deploy,[switch]$InterruptNativeCommands) $ErrorActionPreference='Stop' $ProgressPreference='SilentlyContinue' $root=Join-Path $env:USERPROFILE '.codexify' @@ -98,9 +98,12 @@ function Active-NativeChildCommands { function Idle { try { $h=Invoke-RestMethod -Uri 'http://127.0.0.1:3000/health' -TimeoutSec 5 - if($h.status -ne 'ok' -or $h.filesystem.occupiedWorkerSlots -gt 0 -or $h.filesystem.queuedRequests -gt 0){return $false} - foreach($u in $h.upstreams.PSObject.Properties){if($u.Value.activeRequests -gt 0 -or $u.Value.queuedRequests -gt 0){return $false}} - if(Active-NativeChildCommands){return $false} + if($h.status -ne 'ok'){return $false} + if(-not $InterruptNativeCommands){ + if($h.filesystem.occupiedWorkerSlots -gt 0 -or $h.filesystem.queuedRequests -gt 0){return $false} + foreach($u in $h.upstreams.PSObject.Properties){if($u.Value.activeRequests -gt 0 -or $u.Value.queuedRequests -gt 0){return $false}} + if(Active-NativeChildCommands){return $false} + } $desc=Join-Path $root 'browser\descriptor.json' if(Test-Path -LiteralPath $desc){ $d=Get-Content -LiteralPath $desc -Raw|ConvertFrom-Json @@ -157,6 +160,7 @@ $stopped=$false $replaced=$false try { Write-Output 'STAGE_VERIFIED=true' + if($InterruptNativeCommands){Write-Output 'AUTHORIZED_NATIVE_COMMAND_INTERRUPTION=true'} $deadline=[DateTime]::UtcNow.AddMinutes(3) while(-not(Idle) -and [DateTime]::UtcNow -lt $deadline){Start-Sleep -Seconds 3} if(-not(Idle)){throw 'Native or browser activity remained busy; original service preserved'} @@ -165,12 +169,27 @@ try { Where-Object {$_.ExecutablePath -ieq $live}) $stopped=$true RunCli $live @('service','stop') - $deadline=[DateTime]::UtcNow.AddSeconds(9) + $deadline=[DateTime]::UtcNow.AddSeconds(7) while([DateTime]::UtcNow -lt $deadline){ $p=@(Get-CimInstance Win32_Process -Filter "Name='codexify.exe'"|Where-Object {$_.ExecutablePath -ieq $live}) if($p.Count -eq 0){break} Start-Sleep -Milliseconds 500 } + if($p.Count -gt 0){ + # The CLI currently suppresses Stop-ScheduledTask errors and can report + # success while the scheduled task remains running. A real failure should + # not be ignored; explicitly stop the existing task from this independent + # maintenance process before falling back to the verified process pair. + try { + $task=Get-ScheduledTask -TaskName 'Codexify' -TaskPath '\' -ErrorAction Stop + Stop-ScheduledTask -InputObject $task -ErrorAction Stop + Write-Output 'SCHEDULED_TASK_STOP_REQUESTED=true' + } catch { + Write-Output ('SCHEDULED_TASK_STOP_FAILED='+$_.Exception.GetType().Name) + } + Start-Sleep -Seconds 3 + $p=@(Get-CimInstance Win32_Process -Filter "Name='codexify.exe'"|Where-Object {$_.ExecutablePath -ieq $live}) + } if($p.Count -gt 0){ $currentIds=@($p | Select-Object -ExpandProperty ProcessId | Sort-Object) -join ',' $originalIds=@($originalNative | Select-Object -ExpandProperty ProcessId | Sort-Object) -join ',' diff --git a/scripts/windows-native-readiness-task-wrapper.ps1 b/scripts/windows-native-readiness-task-wrapper.ps1 index ab54deb8..1f34cc2c 100644 --- a/scripts/windows-native-readiness-task-wrapper.ps1 +++ b/scripts/windows-native-readiness-task-wrapper.ps1 @@ -1,7 +1,8 @@ param( [Parameter(Mandatory=$true)][string]$Candidate, [Parameter(Mandatory=$true)][string]$ReportDirectory, - [switch]$Deploy + [switch]$Deploy, + [switch]$InterruptNativeCommands ) $ErrorActionPreference='Stop' $ProgressPreference='SilentlyContinue' @@ -25,7 +26,7 @@ Record ('MAINTENANCE_MODE='+$(if($Deploy){'deploy'}else{'dryrun'})+ ' PARENT_IMAGE='+$(if($ancestor){$ancestor.Name}else{'unknown'})) $installer=Join-Path $PSScriptRoot 'windows-deploy-native-readiness-fix.ps1' try { - & $installer -Candidate $Candidate -Deploy:$Deploy 2>&1 | ForEach-Object { + & $installer -Candidate $Candidate -Deploy:$Deploy -InterruptNativeCommands:$InterruptNativeCommands 2>&1 | ForEach-Object { $line=($_|Out-String).Trim() if($line){Record $line} } From 1ebc7ca06a97d45d82ac4b5e48eaa8ed95d27280 Mon Sep 17 00:00:00 2001 From: tomi Date: Fri, 20 Nov 2026 18:34:59 +0100 Subject: [PATCH 104/118] fix(windows): suspend native task recovery during atomic upgrade --- .../windows-deploy-native-readiness-fix.ps1 | 43 ++++++++++++++++++- 1 file changed, 42 insertions(+), 1 deletion(-) diff --git a/scripts/windows-deploy-native-readiness-fix.ps1 b/scripts/windows-deploy-native-readiness-fix.ps1 index eac3c756..d1c35feb 100644 --- a/scripts/windows-deploy-native-readiness-fix.ps1 +++ b/scripts/windows-deploy-native-readiness-fix.ps1 @@ -121,7 +121,8 @@ function Stop-VerifiedUnresponsiveNativePair { # verified *before* invoking service stop, and only if no work is active. if(-not(Idle)){throw 'Native/browser work became active; refusing forced native stop'} $task=Get-ScheduledTask -TaskName 'Codexify' -TaskPath '\' -ErrorAction Stop - if(-not $task.Settings.Enabled -or $task.Principal.LogonType -ne 'Interactive' -or + if((-not $task.Settings.Enabled -and -not $script:taskTemporarilyDisabled) -or + $task.Principal.LogonType -ne 'Interactive' -or $task.Principal.RunLevel -ne 'Limited' -or [IO.Path]::GetFullPath([string]$task.Actions[0].WorkingDirectory) -ine [IO.Path]::GetFullPath($root) -or [IO.Path]::GetFullPath([string]$task.Actions[0].Execute) -ine (Join-Path $env:WINDIR 'System32\WindowsPowerShell\v1.0\powershell.exe')){ @@ -158,6 +159,15 @@ function Stop-VerifiedUnresponsiveNativePair { } $stopped=$false $replaced=$false +$script:taskTemporarilyDisabled=$false +function Restore-TaskEnablement { + if(-not $script:taskTemporarilyDisabled){return} + Enable-ScheduledTask -TaskName 'Codexify' -TaskPath '\' -ErrorAction Stop | Out-Null + $task=Get-ScheduledTask -TaskName 'Codexify' -TaskPath '\' -ErrorAction Stop + if(-not $task.Settings.Enabled){throw 'Existing Codexify task could not be re-enabled'} + $script:taskTemporarilyDisabled=$false + Write-Output 'ORIGINAL_CODEXIFY_TASK_REENABLED=true' +} try { Write-Output 'STAGE_VERIFIED=true' if($InterruptNativeCommands){Write-Output 'AUTHORIZED_NATIVE_COMMAND_INTERRUPTION=true'} @@ -165,6 +175,19 @@ try { while(-not(Idle) -and [DateTime]::UtcNow -lt $deadline){Start-Sleep -Seconds 3} if(-not(Idle)){throw 'Native or browser activity remained busy; original service preserved'} Write-Output 'IDLE_WINDOW_VERIFIED=true' + # Disable the existing task *temporarily* to prevent its one-minute failure + # recovery policy from racing the binary swap. Preserve task definition. + $existingTask=Get-ScheduledTask -TaskName 'Codexify' -TaskPath '\' -ErrorAction Stop + if(-not $existingTask.Settings.Enabled -or $existingTask.Principal.LogonType -ne 'Interactive' -or + $existingTask.Principal.RunLevel -ne 'Limited' -or + [IO.Path]::GetFullPath([string]$existingTask.Actions[0].WorkingDirectory) -ine [IO.Path]::GetFullPath($root)){ + throw 'Existing Codexify task identity or enabled state is unexpected' + } + Disable-ScheduledTask -TaskName 'Codexify' -TaskPath '\' -ErrorAction Stop | Out-Null + $script:taskTemporarilyDisabled=$true + $verifiedTask=Get-ScheduledTask -TaskName 'Codexify' -TaskPath '\' -ErrorAction Stop + if($verifiedTask.Settings.Enabled){throw 'Native task did not disable; aborting before shutdown'} + Write-Output 'NATIVE_TASK_TEMPORARILY_DISABLED=true' $originalNative=@(Get-CimInstance Win32_Process -Filter "Name='codexify.exe'"| Where-Object {$_.ExecutablePath -ieq $live}) $stopped=$true @@ -193,6 +216,18 @@ try { if($p.Count -gt 0){ $currentIds=@($p | Select-Object -ExpandProperty ProcessId | Sort-Object) -join ',' $originalIds=@($originalNative | Select-Object -ExpandProperty ProcessId | Sort-Object) -join ',' + # A scheduled-task stop can race a short-lived CLI helper. Wait for that + # helper to finish, but never terminate an unrecognized native process. + $helperDeadline=[DateTime]::UtcNow.AddSeconds(8) + while($currentIds -ne $originalIds -and [DateTime]::UtcNow -lt $helperDeadline){ + Start-Sleep -Milliseconds 400 + $p=@(Get-CimInstance Win32_Process -Filter "Name='codexify.exe'"|Where-Object {$_.ExecutablePath -ieq $live}) + if($p.Count -eq 0){break} + $currentIds=@($p | Select-Object -ExpandProperty ProcessId | Sort-Object) -join ',' + } + if($p.Count -eq 0){Write-Output 'NATIVE_PROCESSES_EXITED_DURING_HELPER_GRACE=true'} + } + if($p.Count -gt 0){ if($currentIds -ne $originalIds){ throw 'A new native process started during service stop; binary untouched' } @@ -211,6 +246,7 @@ try { [IO.File]::Replace($stage,$live,(Join-Path $backup 'codexify.original-slot.exe'),$true) $replaced=$true if((Hash $live) -ne $newHash){throw 'Installed executable hash mismatch'} + Restore-TaskEnablement RunCli $live @('service','start') $deadline=[DateTime]::UtcNow.AddSeconds(80) while(-not(Ready) -and [DateTime]::UtcNow -lt $deadline){Start-Sleep -Seconds 2} @@ -250,6 +286,7 @@ try { if((Hash $restore) -ne $oldHash){throw 'Rollback stage hash mismatch'} [IO.File]::Replace($restore,$live,$failed,$true) if((Hash $live) -ne $oldHash){throw 'Rollback verification failed'} + Restore-TaskEnablement RunCli $live @('service','start') Write-Output 'ROLLBACK_BINARY_VERIFIED=true' $oldReceipt.phase='rolled_back' @@ -258,10 +295,14 @@ try { Write-Output ('ROLLBACK_REQUIRES_ATTENTION='+$_.Exception.Message) } }elseif($stopped){ + try {Restore-TaskEnablement}catch {Write-Output ('TASK_REENABLE_FAILED='+$_.Exception.Message)} try {RunCli $live @('service','start')}catch {Write-Output ('SERVICE_RESTART_FAILED='+$_.Exception.Message)} } $oldReceipt|ConvertTo-Json -Depth 5|Set-Content -LiteralPath (Join-Path $backup 'receipt.json') throw } finally{ + if($script:taskTemporarilyDisabled){ + try {Restore-TaskEnablement}catch {Write-Output ('TASK_RESTORE_REQUIRES_ATTENTION='+$_.Exception.Message)} + } if(Test-Path -LiteralPath $stage){Remove-Item -LiteralPath $stage -Force -ErrorAction SilentlyContinue} } From 980c9e596a71aa8dbaaf1f7aaba56f74e230baf4 Mon Sep 17 00:00:00 2001 From: tomi Date: Fri, 20 Nov 2026 18:40:27 +0100 Subject: [PATCH 105/118] fix(windows): require administrator consent for native service swap --- scripts/windows-deploy-native-readiness-fix.ps1 | 16 +++++++++++++++- .../windows-native-readiness-task-wrapper.ps1 | 5 +++-- 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/scripts/windows-deploy-native-readiness-fix.ps1 b/scripts/windows-deploy-native-readiness-fix.ps1 index d1c35feb..32d3ae09 100644 --- a/scripts/windows-deploy-native-readiness-fix.ps1 +++ b/scripts/windows-deploy-native-readiness-fix.ps1 @@ -1,8 +1,17 @@ -param([Parameter(Mandatory=$true)][string]$Candidate,[switch]$Deploy,[switch]$InterruptNativeCommands) +param( + [Parameter(Mandatory=$true)][string]$Candidate, + [switch]$Deploy, + [switch]$InterruptNativeCommands, + [string]$ExpectedProfile +) $ErrorActionPreference='Stop' $ProgressPreference='SilentlyContinue' $root=Join-Path $env:USERPROFILE '.codexify' $live=Join-Path $root 'bin\codexify.exe' +if($ExpectedProfile -and + [IO.Path]::GetFullPath($env:USERPROFILE) -ine [IO.Path]::GetFullPath($ExpectedProfile)){ + throw 'Administrator approval used a different Windows account; refusing to modify that profile' +} $rootFull=[IO.Path]::GetFullPath($root) $candidateFull=[IO.Path]::GetFullPath($Candidate) $project=[IO.Path]::GetFullPath((Join-Path $PSScriptRoot '..')) @@ -24,6 +33,11 @@ if(-not $Deploy){ Write-Output 'NO_SERVICE_OR_FILE_CHANGES=true' return } +$identity=[Security.Principal.WindowsIdentity]::GetCurrent() +$principal=[Security.Principal.WindowsPrincipal]::new($identity) +if(-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)){ + throw 'Administrator approval is required to manage the existing Codexify scheduled task' +} # A native service replacement kills its owning Windows Job Object. When this # installer is spawned by a Codexify tool, it belongs to the same tree and # may be terminated halfway through the atomic swap. Require an independent diff --git a/scripts/windows-native-readiness-task-wrapper.ps1 b/scripts/windows-native-readiness-task-wrapper.ps1 index 1f34cc2c..d2e973ef 100644 --- a/scripts/windows-native-readiness-task-wrapper.ps1 +++ b/scripts/windows-native-readiness-task-wrapper.ps1 @@ -2,7 +2,8 @@ param( [Parameter(Mandatory=$true)][string]$Candidate, [Parameter(Mandatory=$true)][string]$ReportDirectory, [switch]$Deploy, - [switch]$InterruptNativeCommands + [switch]$InterruptNativeCommands, + [string]$ExpectedProfile ) $ErrorActionPreference='Stop' $ProgressPreference='SilentlyContinue' @@ -26,7 +27,7 @@ Record ('MAINTENANCE_MODE='+$(if($Deploy){'deploy'}else{'dryrun'})+ ' PARENT_IMAGE='+$(if($ancestor){$ancestor.Name}else{'unknown'})) $installer=Join-Path $PSScriptRoot 'windows-deploy-native-readiness-fix.ps1' try { - & $installer -Candidate $Candidate -Deploy:$Deploy -InterruptNativeCommands:$InterruptNativeCommands 2>&1 | ForEach-Object { + & $installer -Candidate $Candidate -Deploy:$Deploy -InterruptNativeCommands:$InterruptNativeCommands -ExpectedProfile $ExpectedProfile 2>&1 | ForEach-Object { $line=($_|Out-String).Trim() if($line){Record $line} } From e5797753a5a769222edb00ebae8352f28de4bbb5 Mon Sep 17 00:00:00 2001 From: tomi Date: Fri, 20 Nov 2026 18:44:06 +0100 Subject: [PATCH 106/118] fix(windows): allow guarded stop after native health becomes unavailable Use private browser lease evidence instead of native health to rule out active Sends after scheduler shutdown; read-only handoffs no longer invalidate the already-authorized native restart. --- .../windows-deploy-native-readiness-fix.ps1 | 30 ++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/scripts/windows-deploy-native-readiness-fix.ps1 b/scripts/windows-deploy-native-readiness-fix.ps1 index 32d3ae09..8b8b566a 100644 --- a/scripts/windows-deploy-native-readiness-fix.ps1 +++ b/scripts/windows-deploy-native-readiness-fix.ps1 @@ -128,12 +128,40 @@ function Idle { return $true }catch{return $false} } +function Browser-Has-No-Active-Send { + # During a native stop, its /health may legitimately stop responding and a + # read-only turn-handoff can reserve the only browser lane. Neither condition + # is proof of an in-flight Send. Fail closed on any unobservable browser lane + # or on an owned/pending Send or action cleanup. + try { + $path=Join-Path $root 'browser\descriptor.json' + if(-not(Test-Path -LiteralPath $path -PathType Leaf)){return $false} + $descriptor=Get-Content -LiteralPath $path -Raw|ConvertFrom-Json + $headers=@{Authorization='Bearer '+$descriptor.token} + $snapshot=Invoke-RestMethod -Uri ($descriptor.endpoint.TrimEnd('/')+'/v1/diagnostics/readiness') -Headers $headers -TimeoutSec 5 + if($snapshot.closed -or $snapshot.maintenance -or -not $snapshot.lanes){return $false} + foreach($lane in $snapshot.lanes){ + if($lane.activeAction -or $lane.pendingAction -or + $lane.actionCleanupPending -or $lane.connectorRefreshPending -or $lane.retired){ + return $false + } + } + return $true + }catch{return $false} +} function Stop-VerifiedUnresponsiveNativePair { # The installed service's Windows Stop-ScheduledTask script suppresses # errors, so a successful CLI receipt does not prove that its processes quit. # Only terminate the exact installed supervisor/listener pair that was # verified *before* invoking service stop, and only if no work is active. - if(-not(Idle)){throw 'Native/browser work became active; refusing forced native stop'} + if($InterruptNativeCommands){ + if(-not(Browser-Has-No-Active-Send)){ + throw 'Browser action ownership could not be ruled out; refusing forced native stop' + } + Write-Output 'NO_BROWSER_SEND_OWNERSHIP_VERIFIED=true' + } elseif(-not(Idle)){ + throw 'Native/browser work became active; refusing forced native stop' + } $task=Get-ScheduledTask -TaskName 'Codexify' -TaskPath '\' -ErrorAction Stop if((-not $task.Settings.Enabled -and -not $script:taskTemporarilyDisabled) -or $task.Principal.LogonType -ne 'Interactive' -or From d67274f4e7d0b9a5fd029d018bc081910814c8d9 Mon Sep 17 00:00:00 2001 From: tomi Date: Fri, 20 Nov 2026 18:50:01 +0100 Subject: [PATCH 107/118] fix(windows): tolerate supervised listener exit during restart --- scripts/windows-deploy-native-readiness-fix.ps1 | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/scripts/windows-deploy-native-readiness-fix.ps1 b/scripts/windows-deploy-native-readiness-fix.ps1 index 8b8b566a..e1a20671 100644 --- a/scripts/windows-deploy-native-readiness-fix.ps1 +++ b/scripts/windows-deploy-native-readiness-fix.ps1 @@ -195,8 +195,15 @@ function Stop-VerifiedUnresponsiveNativePair { throw 'Native process identity changed before stop' } } - Stop-Process -Id $supervisor.ProcessId -Force -ErrorAction Stop - Stop-Process -Id $listener.ProcessId -Force -ErrorAction Stop + foreach($verified in @($supervisor,$listener)){ + $current=Get-CimInstance Win32_Process -Filter ('ProcessId='+[int]$verified.ProcessId) + if(-not $current){continue} # Supervisor exit can close the listener too. + if($current.ExecutablePath -ine $live -or + $current.CreationDate -ne $verified.CreationDate){ + throw 'Native process identity changed during stop; refusing unrelated process' + } + Stop-Process -Id $verified.ProcessId -Force -ErrorAction Stop + } Write-Output 'VERIFIED_STALE_NATIVE_PAIR_STOPPED=true' } $stopped=$false From de37d35f9fd758ceaf6457086508a4b15e86c718 Mon Sep 17 00:00:00 2001 From: tomi Date: Fri, 20 Nov 2026 20:01:20 +0100 Subject: [PATCH 108/118] fix(windows): fail closed when native service processes survive task stop Stop and restart now surface scheduler errors, wait for the exact installed native processes to exit, and refuse duplicate starts when a supervisor/listener remains. --- src/service.rs | 47 ++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 44 insertions(+), 3 deletions(-) diff --git a/src/service.rs b/src/service.rs index fbea5d2c..5c7d555a 100644 --- a/src/service.rs +++ b/src/service.rs @@ -1042,15 +1042,40 @@ fn windows_start_script() -> String { fn windows_stop_script() -> String { let task = powershell_quote(WINDOWS_TASK); format!( - "$ErrorActionPreference = 'Stop'\n$task = Get-ScheduledTask -TaskName {task} -ErrorAction Stop\nStop-ScheduledTask -InputObject $task -ErrorAction SilentlyContinue\n" + "$ErrorActionPreference = 'Stop'\n$task = Get-ScheduledTask -TaskName {task} -ErrorAction Stop\nif ([string]$task.State -eq 'Running') {{ Stop-ScheduledTask -InputObject $task -ErrorAction Stop }}\n{}", + windows_verify_native_stopped_script() ) } +#[cfg(any(target_os = "windows", test))] +fn windows_verify_native_stopped_script() -> &'static str { + // Task Scheduler may mark the task Ready while the script's native + // supervisor and listener are still running. Never report a successful + // stop or launch another instance until the exact installed pair exits. + r#"$taskRoot = [string]$task.Actions[0].WorkingDirectory +if ([string]::IsNullOrWhiteSpace($taskRoot) -or -not [IO.Path]::IsPathRooted($taskRoot)) { + throw 'Codexify scheduled task has no trusted working directory' +} +$nativeExecutable = [IO.Path]::GetFullPath((Join-Path $taskRoot 'bin\codexify.exe')) +$stopDeadline = [DateTime]::UtcNow.AddSeconds(15) +do { + $remainingNative = @(Get-CimInstance Win32_Process -Filter "Name='codexify.exe'" -ErrorAction Stop | + Where-Object { $_.ExecutablePath -ieq $nativeExecutable }) + if ($remainingNative.Count -eq 0) { break } + Start-Sleep -Milliseconds 500 +} while ([DateTime]::UtcNow -lt $stopDeadline) +if ($remainingNative.Count -gt 0) { + $remainingIds = ($remainingNative.ProcessId -join ',') + throw "Codexify scheduled task stopped but native processes remain (PIDs: $remainingIds); refusing to report success or start a duplicate" +} +"# +} + #[cfg(any(target_os = "windows", test))] fn windows_restart_script() -> String { - let task = powershell_quote(WINDOWS_TASK); format!( - "$ErrorActionPreference = 'Stop'\n$task = Get-ScheduledTask -TaskName {task} -ErrorAction Stop\nStop-ScheduledTask -InputObject $task -ErrorAction SilentlyContinue\nStart-ScheduledTask -InputObject $task\n" + "{}Start-ScheduledTask -InputObject $task -ErrorAction Stop\n", + windows_stop_script() ) } @@ -2622,10 +2647,26 @@ mod tests { let stop = windows_stop_script(); assert!(stop.contains("Stop-ScheduledTask")); assert!(!stop.contains("Start-ScheduledTask")); + assert!(stop.contains("if ([string]$task.State -eq 'Running')")); + assert!(stop.contains("Stop-ScheduledTask -InputObject $task -ErrorAction Stop")); + assert!(stop.contains("Get-CimInstance Win32_Process")); + assert!(stop.contains("native processes remain")); + assert!( + !stop.contains("Stop-ScheduledTask -InputObject $task -ErrorAction SilentlyContinue") + ); let restart = windows_restart_script(); assert!(restart.contains("Stop-ScheduledTask")); assert!(restart.contains("Start-ScheduledTask")); + let stop_check = restart.find("if ($remainingNative.Count -gt 0)").unwrap(); + let start_task = restart + .find("Start-ScheduledTask -InputObject $task") + .unwrap(); + assert!( + stop_check < start_task, + "restart must validate native exit first" + ); + assert!(restart.contains("refusing to report success or start a duplicate")); for script in [start, stop, restart] { assert!(!script.contains("Enable-ScheduledTask"), "{script}"); From 2b83d26e54c72f2996013d7ec0ccd0d7e29adff5 Mon Sep 17 00:00:00 2001 From: tomi Date: Fri, 20 Nov 2026 23:03:21 +0100 Subject: [PATCH 109/118] test(windows): exercise generated service lifecycle scripts offline Extract actual Rust generator code with standalone rustc, parse the output PowerShell, and mock nine stop/restart scenarios without touching the native task. --- ...est-windows-service-lifecycle-contract.ps1 | 152 ++++++++++++++++++ 1 file changed, 152 insertions(+) create mode 100644 scripts/test-windows-service-lifecycle-contract.ps1 diff --git a/scripts/test-windows-service-lifecycle-contract.ps1 b/scripts/test-windows-service-lifecycle-contract.ps1 new file mode 100644 index 00000000..fbf1b9f3 --- /dev/null +++ b/scripts/test-windows-service-lifecycle-contract.ps1 @@ -0,0 +1,152 @@ +# Offline contract verification for generated Windows Codexify service scripts. +# This extracts the actual Rust generator functions, compiles only those with +# rustc (not the heavy workspace test target), and executes PowerShell scripts +# against local mocks. It NEVER operates on the real Scheduled Task or processes. +param() +$ErrorActionPreference = 'Stop' +$ProgressPreference = 'SilentlyContinue' +$sourcePath = Join-Path $PSScriptRoot '..\src\service.rs' +$source = [IO.File]::ReadAllText([IO.Path]::GetFullPath($sourcePath)) +$functions = @( + 'powershell_quote', + 'windows_stop_script', + 'windows_verify_native_stopped_script', + 'windows_restart_script' +) +$definitions = foreach ($name in $functions) { + $pattern = if ($name -eq 'windows_verify_native_stopped_script') { + "(?ms)^fn $name\([^\r\n]*\) -> [^\r\n]+ \{.*?^\x22#\r?\n^\}" + } else { + "(?ms)^fn $name\([^\r\n]*\) -> [^\r\n]+ \{.*?^\}" + } + $match = [regex]::Match($source, $pattern) + if (-not $match.Success) { + throw "Could not isolate source function $name" + } + $match.Value +} +$root = Join-Path ([IO.Path]::GetTempPath()) ('codexify-windows-contract-' + [guid]::NewGuid().ToString('N')) +[void](New-Item -Path $root -ItemType Directory -ErrorAction Stop) +try { + $rust = 'const WINDOWS_TASK: &str = "Codexify";' + [Environment]::NewLine + + ($definitions -join ([Environment]::NewLine + [Environment]::NewLine)) + [Environment]::NewLine + + @' +fn main() { + let output = std::env::args().nth(1).expect("temp path"); + std::fs::write(format!("{output}/stop.ps1"), windows_stop_script()).unwrap(); + std::fs::write(format!("{output}/restart.ps1"), windows_restart_script()).unwrap(); +} +'@ + $rustPath = Join-Path $root 'lifecycle.rs' + [IO.File]::WriteAllText($rustPath, $rust, [Text.UTF8Encoding]::new($false)) + $program = Join-Path $root 'lifecycle.exe' + $compiler = (Get-Command rustc -ErrorAction Stop).Source + & $compiler --edition=2021 $rustPath -o $program + if ($LASTEXITCODE -ne 0) { throw "Isolated rustc compile failed ($LASTEXITCODE)" } + & $program $root + if ($LASTEXITCODE -ne 0) { throw "Generator execution failed ($LASTEXITCODE)" } + + $stopText = [IO.File]::ReadAllText((Join-Path $root 'stop.ps1')) + $restartText = [IO.File]::ReadAllText((Join-Path $root 'restart.ps1')) + foreach ($name in @('stop','restart')) { + $path = Join-Path $root "$name.ps1" + $tokens = $null + $errors = $null + [void][Management.Automation.Language.Parser]::ParseFile($path, [ref]$tokens, [ref]$errors) + if (@($errors).Count -gt 0) { + throw ("Generated $name script has syntax errors: " + (@($errors) | ForEach-Object Message) -join '; ') + } + } + Write-Output 'GENERATED_POWERSHELL_PARSE=2/2_PASS' + + # Test-only reduction of the deadline avoids making each mock negative case + # wait 15 seconds. The actual generated scripts are parsed above unmodified. + if (-not $stopText.Contains('AddSeconds(15)') -or + -not $restartText.Contains('AddSeconds(15)')) { + throw 'Missing source stop timeout' + } + $stopText = $stopText.Replace('AddSeconds(15)','AddMilliseconds(30)') + $restartText = $restartText.Replace('AddSeconds(15)','AddMilliseconds(30)') + if ($restartText.IndexOf('if ($remainingNative.Count -gt 0)') -gt + $restartText.IndexOf('Start-ScheduledTask -InputObject $task')) { + throw 'Restart ordering is unsafe' + } + + $script:mockState = 'Ready' + $script:mockNativeRemains = $false + $script:mockDenyStop = $false + $script:mockStopped = 0 + $script:mockStarted = 0 + + # Local functions shadow the real Windows cmdlets inside this script's scope. + function Get-ScheduledTask { + param([string]$TaskName, [string]$ErrorAction) + if ($TaskName -ne 'Codexify') { throw 'Unexpected task name' } + [pscustomobject]@{ + State = $script:mockState + Actions = @([pscustomobject]@{WorkingDirectory='C:\CodexifySyntheticOnly'}) + } + } + function Stop-ScheduledTask { + param($InputObject, [string]$ErrorAction) + $script:mockStopped++ + if ($script:mockDenyStop) { throw 'Synthetic access denied' } + } + function Get-CimInstance { + param([string]$ClassName, [string]$Filter, [string]$ErrorAction) + if ($ClassName -ne 'Win32_Process') { throw 'Unexpected query' } + if ($script:mockNativeRemains) { + [pscustomobject]@{ProcessId=4382; ExecutablePath='C:\CodexifySyntheticOnly\bin\codexify.exe'} + } + } + function Start-ScheduledTask { + param($InputObject, [string]$ErrorAction) + $script:mockStarted++ + } + function Start-Sleep { param([int]$Milliseconds) } + + $cases = @( + @{name='stopped_no_process'; script=$stopText; state='Ready'; residual=$false; deny=$false; stops=0; starts=0; error=$null}, + @{name='running_stop_exits'; script=$stopText; state='Running'; residual=$false; deny=$false; stops=1; starts=0; error=$null}, + @{name='running_stop_orphan'; script=$stopText; state='Running'; residual=$true; deny=$false; stops=1; starts=0; error='native processes remain'}, + @{name='stopped_orphan'; script=$stopText; state='Ready'; residual=$true; deny=$false; stops=0; starts=0; error='native processes remain'}, + @{name='stop_denied'; script=$stopText; state='Running'; residual=$false; deny=$true; stops=1; starts=0; error='Synthetic access denied'}, + @{name='running_restart_exits'; script=$restartText; state='Running'; residual=$false; deny=$false; stops=1; starts=1; error=$null}, + @{name='stopped_restart_exits'; script=$restartText; state='Ready'; residual=$false; deny=$false; stops=0; starts=1; error=$null}, + @{name='restart_orphan_refuses_duplicate'; script=$restartText; state='Running'; residual=$true; deny=$false; stops=1; starts=0; error='native processes remain'}, + @{name='restart_denied_refuses_duplicate'; script=$restartText; state='Running'; residual=$false; deny=$true; stops=1; starts=0; error='Synthetic access denied'} + ) + $passed = 0 + foreach ($case in $cases) { + $script:mockState = $case.state + $script:mockNativeRemains = $case.residual + $script:mockDenyStop = $case.deny + $script:mockStopped = 0 + $script:mockStarted = 0 + $caught = $null + try { + & ([scriptblock]::Create($case.script)) | Out-Null + } catch { + $caught = $_.Exception.Message + } + if ($case.error -and (-not $caught -or -not $caught.Contains($case.error))) { + throw "CASE $($case.name): wanted '$($case.error)', got '$caught'" + } + if (-not $case.error -and $caught) { + throw "CASE $($case.name): unexpected error '$caught'" + } + if ($script:mockStopped -ne $case.stops -or $script:mockStarted -ne $case.starts) { + throw "CASE $($case.name): stop/start $script:mockStopped/$script:mockStarted expected $($case.stops)/$($case.starts)" + } + $passed++ + Write-Output "PASS $($case.name)" + } + Write-Output "MOCK_CASES=$passed/$($cases.Count) PASS" + Write-Output 'LIVE_TASK_OR_SERVICE_MUTATIONS=0' +} finally { + $tempBase = [IO.Path]::GetFullPath([IO.Path]::GetTempPath()).TrimEnd('\') + '\' + if ([IO.Path]::GetFullPath($root).StartsWith($tempBase, [StringComparison]::OrdinalIgnoreCase) -and + [IO.Path]::GetFileName($root).StartsWith('codexify-windows-contract-', [StringComparison]::Ordinal)) { + Remove-Item -LiteralPath $root -Recurse -Force -ErrorAction SilentlyContinue + } +} From c818c4cab031cfc5028ddf29969c29beb5d88e4e Mon Sep 17 00:00:00 2001 From: tomi Date: Fri, 20 Nov 2026 23:08:32 +0100 Subject: [PATCH 110/118] ops(windows): require detached elevated task for native replacement Reject direct elevated wrappers that can die with the native job and provide an on-demand highest-privilege Scheduled Task launcher with source freshness, SHA, browser and task gates. --- .../windows-native-readiness-task-wrapper.ps1 | 26 +++++ ...egister-independent-native-maintenance.ps1 | 105 ++++++++++++++++++ 2 files changed, 131 insertions(+) create mode 100644 scripts/windows-register-independent-native-maintenance.ps1 diff --git a/scripts/windows-native-readiness-task-wrapper.ps1 b/scripts/windows-native-readiness-task-wrapper.ps1 index d2e973ef..e5f0d5db 100644 --- a/scripts/windows-native-readiness-task-wrapper.ps1 +++ b/scripts/windows-native-readiness-task-wrapper.ps1 @@ -25,6 +25,32 @@ $ancestor=if($parentPid){Get-CimInstance Win32_Process -Filter ('ProcessId='+$pa Record ('MAINTENANCE_MODE='+$(if($Deploy){'deploy'}else{'dryrun'})+ ' SCRIPT_PID='+$PID+' PARENT_PID='+$parentPid+ ' PARENT_IMAGE='+$(if($ancestor){$ancestor.Name}else{'unknown'})) +$taskName='Codexify-Native-Readiness-Maintenance' +if($Deploy){ + # Start-Process -Verb RunAs from a Codexify tool can still belong to the + # service's Windows job. That elevated helper can die when the native server + # stops, leaving Task Scheduler disabled. Only an independently launched + # on-demand, highest-privilege Scheduled Task is allowed to deploy. + $identity=[Security.Principal.WindowsIdentity]::GetCurrent() + $principal=[Security.Principal.WindowsPrincipal]::new($identity) + if(-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)){ + throw 'Deployment requires an elevated independent Task Scheduler launcher' + } + $task=Get-ScheduledTask -TaskName $taskName -TaskPath '\' -ErrorAction Stop + $taskArguments=[string]$task.Actions[0].Arguments + if(-not $ancestor -or $ancestor.Name -ine 'svchost.exe' -or + $task.State -ne 'Running' -or $task.Principal.RunLevel -ne 'Highest' -or + @($task.Triggers|Where-Object {$_}).Count -ne 0 -or + @($task.Actions).Count -ne 1 -or + $taskArguments -notlike '*windows-native-readiness-task-wrapper.ps1*' -or + $taskArguments -notlike '*-Deploy*' -or + $taskArguments -notlike '*-InterruptNativeCommands*' -or + $taskArguments -notlike ('*'+$ReportDirectory+'*') -or + $taskArguments -notlike ('*'+$Candidate+'*')){ + throw 'Unverified task origin; refusing deployment from a direct elevated process' + } + Record 'INDEPENDENT_ELEVATED_TASK_ORIGIN_VERIFIED=true' +} $installer=Join-Path $PSScriptRoot 'windows-deploy-native-readiness-fix.ps1' try { & $installer -Candidate $Candidate -Deploy:$Deploy -InterruptNativeCommands:$InterruptNativeCommands -ExpectedProfile $ExpectedProfile 2>&1 | ForEach-Object { diff --git a/scripts/windows-register-independent-native-maintenance.ps1 b/scripts/windows-register-independent-native-maintenance.ps1 new file mode 100644 index 00000000..efd2426e --- /dev/null +++ b/scripts/windows-register-independent-native-maintenance.ps1 @@ -0,0 +1,105 @@ +# Safely launch an authorized native Codexify maintenance from an independent +# Administrator-level Windows Scheduled Task. Without -Deploy: read-only. +# Do not call the native installer directly from a Codexify tool or UAC child. +param( + [switch]$Deploy, + [string]$ExpectedCandidateSha256 +) +$ErrorActionPreference = 'Stop' +$ProgressPreference = 'SilentlyContinue' + +$project = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '..')) +$profile = [IO.Path]::GetFullPath($env:USERPROFILE) +$root = Join-Path $profile '.codexify' +$installed = Join-Path $root 'bin\codexify.exe' +$candidate = Join-Path $project 'target\debug\codexify.exe' +$wrapper = Join-Path $PSScriptRoot 'windows-native-readiness-task-wrapper.ps1' +$taskName = 'Codexify-Native-Readiness-Maintenance' +$gitExe = (Get-Command git -ErrorAction Stop).Source + +foreach($path in @($installed,$candidate,$wrapper)){ + if(-not(Test-Path -LiteralPath $path -PathType Leaf)){ + throw "Missing local maintenance prerequisite: $path" + } +} +$sha = (Get-FileHash -LiteralPath $candidate -Algorithm SHA256).Hash.ToLowerInvariant() +$installedSha = (Get-FileHash -LiteralPath $installed -Algorithm SHA256).Hash.ToLowerInvariant() +$head = (& $gitExe -C $project rev-parse HEAD).Trim() +if($LASTEXITCODE -ne 0 -or $head -notmatch '^[0-9a-f]{40}$'){ + throw 'Cannot verify local source commit' +} +$commitSeconds = (& $gitExe -C $project show -s --format=%ct HEAD).Trim() +if($LASTEXITCODE -ne 0 -or $commitSeconds -notmatch '^\d+$'){ + throw 'Cannot verify commit timestamp' +} +$commitTime = [DateTimeOffset]::FromUnixTimeSeconds([long]$commitSeconds).UtcDateTime +$candidateTime = (Get-Item -LiteralPath $candidate).LastWriteTimeUtc +$sourceDirty = -not [string]::IsNullOrWhiteSpace(((& $gitExe -C $project status --porcelain) -join '')) +if($LASTEXITCODE -ne 0){throw 'Cannot verify source cleanliness'} +$candidateFresh = $candidateTime -gt $commitTime + +'HEAD='+$head +'CANDIDATE_SHA='+$sha +'INSTALLED_SHA='+$installedSha +'CANDIDATE_NEWER_THAN_HEAD='+$candidateFresh +'SOURCE_CLEAN='+(-not $sourceDirty) + +if(-not $Deploy){ + 'DRY_RUN_ONLY=true' + 'WINDOWS_TASK_AND_NATIVE_EXECUTABLE_UNCHANGED=true' + return +} +if($sourceDirty){throw 'Worktree has uncommitted changes; cannot deploy'} +if(-not $candidateFresh){throw 'Candidate was built before the current source commit; rebuild first'} +if([string]::IsNullOrWhiteSpace($ExpectedCandidateSha256) -or + $ExpectedCandidateSha256 -notmatch '^[A-Fa-f0-9]{64}$' -or + $sha -ne $ExpectedCandidateSha256.ToLowerInvariant()){ + throw 'Candidate SHA must be explicitly confirmed before elevated deployment' +} +if($sha -eq $installedSha){throw 'Candidate is already installed; no restart needed'} +$identity = [Security.Principal.WindowsIdentity]::GetCurrent() +$principal = [Security.Principal.WindowsPrincipal]::new($identity) +if(-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)){ + throw 'Run as Administrator to register the independent highest-privilege maintenance task' +} +if(Get-ScheduledTask -TaskName $taskName -TaskPath '\' -ErrorAction SilentlyContinue){ + throw 'Maintenance task already exists; refusing duplicate' +} +$nativeTask = Get-ScheduledTask -TaskName 'Codexify' -TaskPath '\' -ErrorAction Stop +if($nativeTask.State -ne 'Running' -or -not $nativeTask.Settings.Enabled){ + throw 'Existing native scheduled task is not healthy and enabled' +} +try{ + $health = Invoke-RestMethod 'http://127.0.0.1:3000/health' -TimeoutSec 5 + if($health.status -ne 'ok'){throw 'Native health is not ok'} +}catch{throw 'Native HTTP health is unavailable; refusing restart'} +$descriptor = Get-Content -LiteralPath (Join-Path $root 'browser\descriptor.json') -Raw | + ConvertFrom-Json +$browser = Invoke-RestMethod ($descriptor.endpoint.TrimEnd('/')+'/v1/health?ready=1') -Headers @{ + Authorization='Bearer '+$descriptor.token +} -TimeoutSec 5 +if($browser.status -ne 'idle' -or -not $browser.authenticated -or + $browser.availableActionSlots -lt 1 -or + @($browser.activeActionIds|Where-Object {$_}).Count -ne 0){ + throw 'Browser is busy or unverified; refusing native maintenance' +} + +$report = Join-Path $root ('backups\native-readiness-task-'+[DateTime]::UtcNow.ToString('yyyyMMddTHHmmssZ')) +[void](New-Item -Path $report -ItemType Directory) +$engine = Join-Path $env:WINDIR 'System32\WindowsPowerShell\v1.0\powershell.exe' +$arguments = '-NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass -WindowStyle Hidden -File "'+ + $wrapper+'" -Candidate "'+$candidate+'" -ReportDirectory "'+$report+ + '" -ExpectedProfile "'+$profile+'" -Deploy -InterruptNativeCommands' +$action = New-ScheduledTaskAction -Execute $engine -Argument $arguments -WorkingDirectory $PSScriptRoot +$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit (New-TimeSpan -Minutes 12) -MultipleInstances IgnoreNew +$taskPrincipal = New-ScheduledTaskPrincipal -UserId $identity.Name -LogonType Interactive -RunLevel Highest +$registered = Register-ScheduledTask -TaskName $taskName -TaskPath '\' -Action $action -Settings $settings -Principal $taskPrincipal -Description 'Explicit one-time native maintenance; zero automatic triggers' -ErrorAction Stop +if(@($registered.Triggers|Where-Object {$_}).Count -ne 0 -or + $registered.Principal.RunLevel -ne 'Highest'){ + throw 'Unexpected task privileges or triggers; task not started' +} +Start-ScheduledTask -TaskName $taskName -TaskPath '\' -ErrorAction Stop +'INDEPENDENT_ELEVATED_MAINTENANCE_STARTED=true' +'RECEIPT_PATH='+$report +'NO_AUTOMATIC_TRIGGERS=true' +'FOLLOW_DEPLOYMENT_LOG_AND_REMOVE_TASK_AFTER_COMPLETION=true' From c332ad7f1b2114c8417a8248c350b0ce00635399 Mon Sep 17 00:00:00 2001 From: tomi Date: Fri, 20 Nov 2026 23:14:44 +0100 Subject: [PATCH 111/118] ops(windows): preserve active native commands during maintenance by default --- scripts/windows-native-readiness-task-wrapper.ps1 | 1 - scripts/windows-register-independent-native-maintenance.ps1 | 4 +++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/scripts/windows-native-readiness-task-wrapper.ps1 b/scripts/windows-native-readiness-task-wrapper.ps1 index e5f0d5db..55a45d3c 100644 --- a/scripts/windows-native-readiness-task-wrapper.ps1 +++ b/scripts/windows-native-readiness-task-wrapper.ps1 @@ -44,7 +44,6 @@ if($Deploy){ @($task.Actions).Count -ne 1 -or $taskArguments -notlike '*windows-native-readiness-task-wrapper.ps1*' -or $taskArguments -notlike '*-Deploy*' -or - $taskArguments -notlike '*-InterruptNativeCommands*' -or $taskArguments -notlike ('*'+$ReportDirectory+'*') -or $taskArguments -notlike ('*'+$Candidate+'*')){ throw 'Unverified task origin; refusing deployment from a direct elevated process' diff --git a/scripts/windows-register-independent-native-maintenance.ps1 b/scripts/windows-register-independent-native-maintenance.ps1 index efd2426e..05ba097e 100644 --- a/scripts/windows-register-independent-native-maintenance.ps1 +++ b/scripts/windows-register-independent-native-maintenance.ps1 @@ -3,6 +3,7 @@ # Do not call the native installer directly from a Codexify tool or UAC child. param( [switch]$Deploy, + [switch]$InterruptNativeCommands, [string]$ExpectedCandidateSha256 ) $ErrorActionPreference = 'Stop' @@ -89,7 +90,8 @@ $report = Join-Path $root ('backups\native-readiness-task-'+[DateTime]::UtcNow.T $engine = Join-Path $env:WINDIR 'System32\WindowsPowerShell\v1.0\powershell.exe' $arguments = '-NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass -WindowStyle Hidden -File "'+ $wrapper+'" -Candidate "'+$candidate+'" -ReportDirectory "'+$report+ - '" -ExpectedProfile "'+$profile+'" -Deploy -InterruptNativeCommands' + '" -ExpectedProfile "'+$profile+'" -Deploy' +if($InterruptNativeCommands){$arguments += ' -InterruptNativeCommands'} $action = New-ScheduledTaskAction -Execute $engine -Argument $arguments -WorkingDirectory $PSScriptRoot $settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit (New-TimeSpan -Minutes 12) -MultipleInstances IgnoreNew $taskPrincipal = New-ScheduledTaskPrincipal -UserId $identity.Name -LogonType Interactive -RunLevel Highest From 0ecad14fef7f1f68f65755c9b3172045854690bd Mon Sep 17 00:00:00 2001 From: tomi Date: Fri, 20 Nov 2026 23:32:31 +0100 Subject: [PATCH 112/118] ops(windows): guard offline native build against memory pressure Require clean source and healthy native service, start only with 5GB free RAM, monitor and abort own Cargo/Rust compiler below 1.75GB, preserve installed executable. --- scripts/windows-build-native-memory-guard.ps1 | 124 ++++++++++++++++++ 1 file changed, 124 insertions(+) create mode 100644 scripts/windows-build-native-memory-guard.ps1 diff --git a/scripts/windows-build-native-memory-guard.ps1 b/scripts/windows-build-native-memory-guard.ps1 new file mode 100644 index 00000000..867fe9d7 --- /dev/null +++ b/scripts/windows-build-native-memory-guard.ps1 @@ -0,0 +1,124 @@ +# Bounded offline Codexify build. Never touches the installed native service. +param([switch]$Build) +$ErrorActionPreference = 'Stop' +$ProgressPreference = 'SilentlyContinue' +$minimumStartGb = 5.0 +$abortBelowGb = 1.75 +$maximumMinutes = 12 +$project = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '..')) +$native = Join-Path $env:USERPROFILE '.codexify\bin\codexify.exe' +$candidate = Join-Path $project 'target\debug\codexify.exe' +$git = (Get-Command git -ErrorAction Stop).Source +$cargo = (Get-Command cargo -ErrorAction Stop).Source +function FreeRamGb { + $os = Get-CimInstance Win32_OperatingSystem -ErrorAction Stop + return [math]::Round(([double]$os.FreePhysicalMemory / 1MB), 2) +} +if(-not(Test-Path -LiteralPath $native -PathType Leaf)){ + throw 'Installed native executable is missing' +} +$head = (& $git -C $project rev-parse HEAD).Trim() +if($LASTEXITCODE -ne 0 -or $head -notmatch '^[a-f0-9]{40}$'){ + throw 'Source HEAD is not verified' +} +$dirty = ((& $git -C $project status --porcelain) -join '') +if($LASTEXITCODE -ne 0 -or $dirty){throw 'Source tree is not clean'} +$task = Get-ScheduledTask -TaskName 'Codexify' -TaskPath '\' -ErrorAction Stop +if($task.State -ne 'Running' -or -not $task.Settings.Enabled){ + throw 'The installed native task is not running/enabled' +} +$health = Invoke-RestMethod 'http://127.0.0.1:3000/health' -TimeoutSec 5 +if($health.status -ne 'ok'){throw 'Native service is not healthy'} +$activeCompilers = @(Get-CimInstance Win32_Process -ErrorAction Stop | + Where-Object {$_.Name -in @('cargo.exe','rustc.exe')}) +$free = FreeRamGb +'CURRENT_RAM_FREE_GB='+$free +'MINIMUM_START_GB='+$minimumStartGb +'ABORT_BELOW_GB='+$abortBelowGb +'HEAD='+$head +'OTHER_COMPILERS='+$activeCompilers.Count +if(-not $Build) { + 'DRY_RUN_ONLY=true' + 'NATIVE_BINARY_UNCHANGED=true' + return +} +if($free -lt $minimumStartGb){ + throw ("Build not started: only " + $free + " GB free RAM; require " + $minimumStartGb + " GB") +} +if($activeCompilers.Count -ne 0){throw 'Other Rust compiler tasks are running'} +if((Get-PSDrive -Name C).Free -lt 6GB){throw 'Not enough free disk for offline build'} +$report = Join-Path $env:USERPROFILE ('.codexify\backups\guarded-native-build-' + [DateTime]::UtcNow.ToString('yyyyMMddTHHmmssZ')) +[void](New-Item -Path $report -ItemType Directory -ErrorAction Stop) +$stdout = Join-Path $report 'stdout.log' +$stderr = Join-Path $report 'stderr.log' +$receipt = Join-Path $report 'receipt.txt' +$startTime = [DateTime]::UtcNow +$env:CARGO_BUILD_JOBS = '1' +$env:CARGO_NET_OFFLINE = 'true' +$proc = $null +$originalSha = (Get-FileHash -LiteralPath $native -Algorithm SHA256).Hash.ToLowerInvariant() +function StopOwnCompiler([int]$cargoPid,[datetime]$creationTime) { + # Only the Cargo process launched here and its immediate Rust children. + $children = @(Get-CimInstance Win32_Process -ErrorAction Stop | Where-Object { + $_.ParentProcessId -eq $cargoPid -and $_.Name -eq 'rustc.exe' -and + [datetime]$_.CreationDate -ge $creationTime + }) + foreach($child in $children) { + $again = Get-CimInstance Win32_Process -Filter ('ProcessId='+[int]$child.ProcessId) + if($again -and $again.Name -eq 'rustc.exe' -and + $again.ParentProcessId -eq $cargoPid -and + $again.CreationDate -eq $child.CreationDate){ + Stop-Process -Id $child.ProcessId -Force -ErrorAction SilentlyContinue + } + } + $cargoProcess = Get-CimInstance Win32_Process -Filter ('ProcessId='+$cargoPid) + if($cargoProcess -and $cargoProcess.Name -eq 'cargo.exe' -and + [math]::Abs((([datetime]$cargoProcess.CreationDate)-$creationTime).TotalSeconds) -lt 2){ + Stop-Process -Id $cargoPid -Force -ErrorAction SilentlyContinue + } +} +try { + $proc = Start-Process -FilePath $cargo -ArgumentList 'build','--bin','codexify','--offline','--jobs','1' -WorkingDirectory $project -PassThru -WindowStyle Hidden -RedirectStandardOutput $stdout -RedirectStandardError $stderr -ErrorAction Stop + $creation = (Get-CimInstance Win32_Process -Filter ('ProcessId='+[int]$proc.Id)).CreationDate + 'BUILD_STARTED_PID='+$proc.Id + 'BUILD_RECEIPT='+$receipt + $deadline = [DateTime]::UtcNow.AddMinutes($maximumMinutes) + while(-not $proc.HasExited) { + Start-Sleep -Seconds 4 + $proc.Refresh() + if($proc.HasExited){break} + $free = FreeRamGb + if($free -lt $abortBelowGb -or [DateTime]::UtcNow -ge $deadline) { + StopOwnCompiler $proc.Id $creation + $reason = if($free -lt $abortBelowGb){'low_memory'}else{'timeout'} + Set-Content -LiteralPath $receipt -Value ("status=aborted;reason="+$reason+";freeGb="+$free+";head="+$head) + throw ("Build aborted safely: " + $reason + ", free RAM " + $free + " GB") + } + } + $proc.Refresh() + if($proc.ExitCode -ne 0){ + Set-Content -LiteralPath $receipt -Value ("status=failed;exit="+$proc.ExitCode+";head="+$head) + throw ('Cargo returned exit code '+$proc.ExitCode) + } + if(-not(Test-Path -LiteralPath $candidate -PathType Leaf)){ + throw 'Build reported success but candidate is missing' + } + $newSha = (Get-FileHash -LiteralPath $candidate -Algorithm SHA256).Hash.ToLowerInvariant() + if((Get-FileHash -LiteralPath $native -Algorithm SHA256).Hash.ToLowerInvariant() -ne $originalSha){ + throw 'Installed executable unexpectedly changed' + } + $commitSeconds = (& $git -C $project show -s --format=%ct HEAD).Trim() + if($LASTEXITCODE -ne 0){throw 'Unable to verify commit freshness'} + $commitTime = [DateTimeOffset]::FromUnixTimeSeconds([long]$commitSeconds).UtcDateTime + if((Get-Item -LiteralPath $candidate).LastWriteTimeUtc -le $commitTime){ + throw 'Candidate was not freshly built for current HEAD' + } + Set-Content -LiteralPath $receipt -Value ("status=built;head="+$head+";sha256="+$newSha) + 'BUILD_SUCCESS=true' + 'CANDIDATE_SHA='+$newSha + 'BUILD_RECEIPT='+$receipt +} finally { + if($proc -and -not $proc.HasExited) { + try {StopOwnCompiler $proc.Id $creation}catch{} + } +} From 29d4b37cb152fb84a5573c82979dc6af74a12227 Mon Sep 17 00:00:00 2001 From: Tommy <104433268+AKzar1el@users.noreply.github.com> Date: Sat, 21 Nov 2026 00:53:17 +0100 Subject: [PATCH 113/118] docs(mcp): clarify exact config source keys for hot reload --- docs/MCP_HOT_RELOAD.md | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/docs/MCP_HOT_RELOAD.md b/docs/MCP_HOT_RELOAD.md index a2feb807..75b2476d 100644 --- a/docs/MCP_HOT_RELOAD.md +++ b/docs/MCP_HOT_RELOAD.md @@ -6,10 +6,15 @@ service without separate approval and validation. ## Scope -`reload_mcp` reloads exactly one existing upstream source, identified by the -key in the resolved `mcpServers` configuration. A caller provides -`{"source":"god_prompt_mcp"}`; it cannot provide a command, executable, -working directory, URL, environment variables, or credentials. +`reload_mcp` reloads exactly one existing upstream source. Its `source` +argument must match the **exact configured MCP server key** from the resolved +`mcpServers` configuration (including inherited Codex MCP sources). For example, +if the configured key is `god-prompt-mcp`, call +`{"source":"god-prompt-mcp"}`. Do not substitute a normalized catalog source ID +such as `god_prompt_mcp` from `mcp_list_sources`: it is not necessarily the +configuration key and can return `SOURCE_UNKNOWN` without changing the running +connection. The call cannot supply a command, executable, working directory, +URL, environment variables, or credentials. The server rereads its operator configuration (including inherited Codex MCP sources) **read-only** using its startup CLI selection. A target that was @@ -77,8 +82,9 @@ and generated skill after reload. ## Failure and boundary conditions -- `SOURCE_UNKNOWN` / `SOURCE_REMOVED` / `SOURCE_DISABLED`: do not spawn - an arbitrary process or reinterpret the input as a path. +- `SOURCE_UNKNOWN` / `SOURCE_REMOVED` / `SOURCE_DISABLED`: verify the + exact configured MCP key, not a normalized catalog ID. Do not spawn an + arbitrary process or reinterpret the input as a path. - `RELOAD_IN_PROGRESS`: no duplicate replacement of the same source. - `CONFIG_INVALID`, `CONFIG_CLI_INVALID`, `INITIALIZE_FAILED`, `READINESS_FAILED`: old healthy generation is retained. From cd6600ce2618e9ff9991e6905490578281042a55 Mon Sep 17 00:00:00 2001 From: tomi Date: Sun, 22 Nov 2026 01:29:01 +0100 Subject: [PATCH 114/118] ci: build scoped Playwright and hot reload Windows candidate --- .github/workflows/preview-hot-reload-windows.yml | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/.github/workflows/preview-hot-reload-windows.yml b/.github/workflows/preview-hot-reload-windows.yml index 16ca2cfa..37029728 100644 --- a/.github/workflows/preview-hot-reload-windows.yml +++ b/.github/workflows/preview-hot-reload-windows.yml @@ -4,10 +4,15 @@ on: push: branches: - feat/per-mcp-hot-reload-20261119 + - fix/per-chat-playwright-hotreload-20261122 paths: - .github/workflows/preview-hot-reload-windows.yml - src/markdown_chat/mod.rs - src/agent_automation/install.rs + - src/bridge.rs + - src/bridge/** + - src/mcp_catalog.rs + - src/playwright_sessions.rs permissions: contents: read @@ -39,10 +44,10 @@ jobs: $hash = (Get-FileHash -LiteralPath (Join-Path $out 'codexify.exe') -Algorithm SHA256).Hash.ToLowerInvariant() Set-Content -LiteralPath (Join-Path $out 'SHA256SUMS.txt') -Value ("$hash codexify.exe") -Encoding ascii Set-Content -LiteralPath (Join-Path $out 'SOURCE_COMMIT.txt') -Value "${{ github.sha }}" -Encoding ascii - Set-Content -LiteralPath (Join-Path $out 'PREVIEW_NOTICE.txt') -Value 'EXPERIMENTAL binary from feature branch PR #11. Not an official release. Activate only after backing up the existing executable; coordinate with other Codexify workers.' -Encoding ascii + Set-Content -LiteralPath (Join-Path $out 'PREVIEW_NOTICE.txt') -Value 'EXPERIMENTAL binary from integration branch PR #12. Not an official release. Activate only after backing up the existing executable; coordinate with other Codexify workers.' -Encoding ascii - uses: actions/upload-artifact@v4 with: - name: codexify-pr11-windows-preview + name: codexify-pr12-perchat-hotreload-windows-preview path: ${{ runner.temp }}/codexify-hot-reload-preview/* if-no-files-found: error retention-days: 7 From a15e6cba3e139f50b578f81cbd7edaca09ca7d57 Mon Sep 17 00:00:00 2001 From: tomi Date: Sun, 22 Nov 2026 01:30:35 +0100 Subject: [PATCH 115/118] ci: verify per-task Playwright and hot reload remotely --- .../perchat-integration-validation.yml | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 .github/workflows/perchat-integration-validation.yml diff --git a/.github/workflows/perchat-integration-validation.yml b/.github/workflows/perchat-integration-validation.yml new file mode 100644 index 00000000..47f014ac --- /dev/null +++ b/.github/workflows/perchat-integration-validation.yml @@ -0,0 +1,42 @@ +name: Scoped Playwright and hot-reload integration checks + +on: + push: + branches: + - fix/per-chat-playwright-hotreload-20261122 + paths: + - .github/workflows/perchat-integration-validation.yml + - src/bridge.rs + - src/bridge/** + - src/playwright_sessions.rs + - src/mcp_catalog.rs + - src/upstream_control.rs + +permissions: + contents: read + +env: + CARGO_TERM_COLOR: always + CARGO_PROFILE_TEST_DEBUG: line-tables-only + +jobs: + scoped-ownership: + runs-on: ubuntu-latest + timeout-minutes: 35 + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - uses: dtolnay/rust-toolchain@stable + with: + components: rustfmt + - uses: Swatinem/rust-cache@v2 + - uses: actions/setup-node@v4 + with: + node-version: '22' + - name: Rust formatting + run: cargo fmt --all -- --check + - name: Per-task browser session tests + run: cargo test --locked --lib playwright_sessions:: -- --test-threads=1 + - name: Hot reload and real two-owner stdio tests + run: cargo test --locked --lib bridge::hot_reload_tests:: -- --test-threads=1 From b6f3072ec2b754e0af2915dadc5fb2cd8b474034 Mon Sep 17 00:00:00 2001 From: tomi Date: Sun, 22 Nov 2026 01:34:08 +0100 Subject: [PATCH 116/118] ci: parse scoped browser test commands as YAML block scalars --- .github/workflows/perchat-integration-validation.yml | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/.github/workflows/perchat-integration-validation.yml b/.github/workflows/perchat-integration-validation.yml index 47f014ac..6b4a46b2 100644 --- a/.github/workflows/perchat-integration-validation.yml +++ b/.github/workflows/perchat-integration-validation.yml @@ -37,6 +37,8 @@ jobs: - name: Rust formatting run: cargo fmt --all -- --check - name: Per-task browser session tests - run: cargo test --locked --lib playwright_sessions:: -- --test-threads=1 + run: | + cargo test --locked --lib playwright_sessions:: -- --test-threads=1 - name: Hot reload and real two-owner stdio tests - run: cargo test --locked --lib bridge::hot_reload_tests:: -- --test-threads=1 + run: | + cargo test --locked --lib bridge::hot_reload_tests:: -- --test-threads=1 From 1fb868d95bb5eb4f9a21822ac35abb6018917fb8 Mon Sep 17 00:00:00 2001 From: tomi Date: Sun, 22 Nov 2026 01:39:29 +0100 Subject: [PATCH 117/118] fix: preserve bounded parallel MCP startup with hot reload registry --- src/bridge.rs | 45 +++++++++++++++++++++++++++++++++++++++------ 1 file changed, 39 insertions(+), 6 deletions(-) diff --git a/src/bridge.rs b/src/bridge.rs index 5f0d48fa..15013058 100644 --- a/src/bridge.rs +++ b/src/bridge.rs @@ -729,16 +729,49 @@ pub async fn connect_upstreams(config: &AppConfig) -> Bridge { let resources = Arc::new(BridgedResourceStore::new(config.artifact_egress.clone())); let mut sources = HashMap::new(); let mut report = Vec::new(); - let mut names: Vec<_> = config.mcp_servers.keys().collect(); + // Preserve the scoped branch's bounded concurrent cold-start behavior; + // hot-reload registry construction only happens after each result is + // received, in deterministic source-name order. + const MAX_PARALLEL_UPSTREAM_STARTS: usize = 3; + let mut names: Vec = config.mcp_servers.keys().cloned().collect(); names.sort(); - - for name in names { - let spec = &config.mcp_servers[name]; + let source_config = Arc::new(config.clone()); + let startup_slots = Arc::new(tokio::sync::Semaphore::new(MAX_PARALLEL_UPSTREAM_STARTS)); + let mut joins = tokio::task::JoinSet::new(); + for (index, name) in names.iter().cloned().enumerate() { + let source_config = Arc::clone(&source_config); + let startup_slots = Arc::clone(&startup_slots); + joins.spawn(async move { + let spec = &source_config.mcp_servers[&name]; + if spec.disabled { + return (index, Err("MCP source is disabled".to_string())); + } + let connected = match startup_slots.acquire_owned().await { + Ok(_permit) => connect_owned_source(&name, spec, &source_config).await, + Err(_) => Err("upstream startup limiter closed".to_string()), + }; + (index, connected) + }); + } + let mut results: Vec<_> = std::iter::repeat_with(|| None).take(names.len()).collect(); + while let Some(joined) = joins.join_next().await { + match joined { + Ok((index, result)) => results[index] = Some(result), + Err(error) => { + tracing::warn!("upstream initialization task failed without a result: {error}") + } + } + } + for (index, name) in names.into_iter().enumerate() { + let spec = &config.mcp_servers[&name]; if spec.disabled { report.push(format!("{name} -> disabled")); continue; } - match connect_owned_source(name, spec, config).await { + let result = results[index] + .take() + .unwrap_or_else(|| Err("upstream startup task failed".to_string())); + match result { Ok((service, tools, timeout, scoped)) => { let count = tools.len(); let mode = spec.exposure(); @@ -3384,7 +3417,7 @@ mod tests { } let bridge = connect_upstreams(&config).await; assert_eq!( - bridge.services.len(), + bridge.runtime.snapshot().sources.len(), 4, "all four MCP sources should connect" ); From bf04c4f5851724d4acc283f1d646d4c3f14ffd65 Mon Sep 17 00:00:00 2001 From: tomi Date: Sun, 22 Nov 2026 01:42:47 +0100 Subject: [PATCH 118/118] fix: borrow source names in parallel MCP initialization --- src/bridge.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/bridge.rs b/src/bridge.rs index 15013058..889c7e4a 100644 --- a/src/bridge.rs +++ b/src/bridge.rs @@ -777,10 +777,10 @@ pub async fn connect_upstreams(config: &AppConfig) -> Bridge { let mode = spec.exposure(); if mode == McpToolExposure::Gateway { let functions = gateway_functions(&tools); - write_gateway_skill(config, name, &sanitize(name), &functions); + write_gateway_skill(config, &name, &sanitize(&name), &functions); } let generation = hot_reload::Generation::for_source( - name, + &name, spec.clone(), service, tools,