Skip to content

Make Codex and Claude Code subscriptions go further: a local model router that gives routine agent work to economical models and keeps your strongest model for the hard parts.

feat: add Qoder routing, native Agent context, and engineering code map (#42)

澄潭ddede06436a4
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 792ca5ac..c1f6379d 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -4,6 +4,11 @@ HiRoute accepts issues and pull requests through
[higress-group/HiRoute](https://github.com/higress-group/HiRoute). Please search existing
issues before opening a new one and keep each pull request focused on one coherent change.
+Use the [code map](docs/code-map/README.md) to find each capability's production
+owner and representative tests. Read [tests as product documentation](docs/code-map/testing.md)
+before reorganizing coverage; preserve unique failure assertions while reducing
+coupling to internal file layout.
+
## Development environment
The Rust version is pinned by `rust-toolchain.toml`. The Desktop UI uses Node.js 24 and
diff --git a/Cargo.lock b/Cargo.lock
index f0f5ba3c..c19066e4 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2313,6 +2313,7 @@ dependencies = [
"thiserror 2.0.20",
"tokio",
"tokio-util",
+ "unicode-normalization",
"zeroize",
]
@@ -2488,6 +2489,7 @@ dependencies = [
"http",
"nix",
"reqwest",
+ "rustix",
"serde",
"serde_json",
"tempfile",
diff --git a/README.md b/README.md
index 746b36ed..2feb2327 100644
--- a/README.md
+++ b/README.md
@@ -152,6 +152,9 @@ respective environments; a source build alone is not product acceptance.
### Repository map
+The [code map](docs/code-map/README.md) connects user capabilities to architecture,
+production owners and representative tests.
+
| Path | Responsibility |
| --- | --- |
| `apps/desktop` | Desktop UI and Tauri host |
diff --git a/apps/desktop/src-tauri/build.rs b/apps/desktop/src-tauri/build.rs
index 4bd9b275..fd6c679a 100644
--- a/apps/desktop/src-tauri/build.rs
+++ b/apps/desktop/src-tauri/build.rs
@@ -55,6 +55,7 @@ fn main() {
"preview_agent_settings",
"retry_agent_settings",
"check_agent_authentication",
+ "check_agent_live",
"worker_settings_get",
"worker_settings_set",
"worker_task_plans",
diff --git a/apps/desktop/src-tauri/capabilities/main.json b/apps/desktop/src-tauri/capabilities/main.json
index d98eb222..9c107c8c 100644
--- a/apps/desktop/src-tauri/capabilities/main.json
+++ b/apps/desktop/src-tauri/capabilities/main.json
@@ -51,6 +51,7 @@
"allow-preview-agent-settings",
"allow-retry-agent-settings",
"allow-check-agent-authentication",
+ "allow-check-agent-live",
"allow-worker-settings-get",
"allow-worker-settings-set",
"allow-worker-task-plans",
diff --git a/apps/desktop/src-tauri/permissions/autogenerated/check_agent_live.toml b/apps/desktop/src-tauri/permissions/autogenerated/check_agent_live.toml
new file mode 100644
index 00000000..a68aedbc
--- /dev/null
+++ b/apps/desktop/src-tauri/permissions/autogenerated/check_agent_live.toml
@@ -0,0 +1,11 @@
+# Automatically generated - DO NOT EDIT!
+
+[[permission]]
+identifier = "allow-check-agent-live"
+description = "Enables the check_agent_live command without any pre-configured scope."
+commands.allow = ["check_agent_live"]
+
+[[permission]]
+identifier = "deny-check-agent-live"
+description = "Denies the check_agent_live command without any pre-configured scope."
+commands.deny = ["check_agent_live"]
diff --git a/apps/desktop/src-tauri/src/agent_check_session.rs b/apps/desktop/src-tauri/src/agent_check_session.rs
index c117e0f3..fc7ba3dc 100644
--- a/apps/desktop/src-tauri/src/agent_check_session.rs
+++ b/apps/desktop/src-tauri/src/agent_check_session.rs
@@ -46,6 +46,48 @@ impl AgentCheckCompletion {
requested_call_count: 0,
}
}
+
+ fn from_live_result(
+ target: &AgentModelCheckTargetV2,
+ data: &Value,
+ ) -> Result<Self, DesktopFailure> {
+ let state = data["state"].as_str().ok_or("RESPONSE_DATA_INVALID")?;
+ let checked: Vec<String> = serde_json::from_value(data["checked_model_ids"].clone())
+ .map_err(|_| "RESPONSE_DATA_INVALID")?;
+ let call_count = data["call_count"]
+ .as_u64()
+ .and_then(|value| usize::try_from(value).ok())
+ .ok_or("RESPONSE_DATA_INVALID")?;
+ let requested_call_count = data["requested_call_count"]
+ .as_u64()
+ .and_then(|value| usize::try_from(value).ok())
+ .ok_or("RESPONSE_DATA_INVALID")?;
+ let valid = data["scope"] == "live"
+ && data["model_call"] == true
+ && data["surface"]
+ == serde_json::to_value(target.surface).map_err(|_| "RESPONSE_DATA_INVALID")?
+ && data["applied_revision"]
+ == serde_json::to_value(target.expected_applied_revision)
+ .map_err(|_| "RESPONSE_DATA_INVALID")?
+ && matches!(state, "passed" | "failed")
+ && call_count == checked.len()
+ && requested_call_count == target.client_model_ids.len()
+ && checked
+ .iter()
+ .all(|model| target.client_model_ids.contains(model))
+ && (state != "passed" || checked == target.client_model_ids);
+ if !valid {
+ return Err("RESPONSE_DATA_INVALID".into());
+ }
+ Ok(Self {
+ accepted: true,
+ scope: "live".into(),
+ model_call: true,
+ state: Some(state.into()),
+ call_count,
+ requested_call_count,
+ })
+ }
}
pub(crate) struct PendingAgentCheck {
@@ -77,10 +119,10 @@ impl AgentCheckConfirmation {
}
pub fn message(&self) -> String {
- let agent = if self.request.agent_id == "agent_claude_default" {
- "Claude Code"
- } else {
- "Codex"
+ let agent = match self.request.agent_id.as_str() {
+ "agent_claude_default" => "Claude Code",
+ "agent_qoder_default" => "Qoder",
+ _ => "Codex",
};
if self.request.scope == AgentCheckScopeV1::Live {
let target = self
@@ -92,9 +134,10 @@ impl AgentCheckConfirmation {
AgentModelSurfaceV2::CodexCli => "Codex CLI",
AgentModelSurfaceV2::CodexDesktop => "Codex Desktop",
AgentModelSurfaceV2::ClaudeCli => "Claude Code CLI",
+ AgentModelSurfaceV2::QoderCli => "Qoder CLI",
};
let models = target.client_model_ids.join(", ");
- return if self.english {
+ let message = if self.english {
format!(
"Verify {surface} model access?\n\nHiRoute will launch the actual configured client and make up to {} short model calls through applied revision {}. Provider usage may be charged.\n\nModels: {models}\n\nOnly complete responses with matching Gateway publication, grant, route, account and receipt evidence can pass.",
target.client_model_ids.len(),
@@ -107,6 +150,27 @@ impl AgentCheckConfirmation {
target.client_model_ids.len(),
)
};
+ return if target.surface == AgentModelSurfaceV2::QoderCli {
+ format!(
+ "{message}\n\n{}",
+ if self.english {
+ "This checks only the selected additional HiRoute routes. Your native models, current default model and login configuration stay unchanged."
+ } else {
+ "仅验证所选的附加 HiRoute 路由;原生模型、当前默认模型和登录配置保持不变。"
+ }
+ )
+ } else {
+ message
+ };
+ }
+ if self.request.scope == AgentCheckScopeV1::Collaboration
+ && self.request.agent_id == "agent_qoder_default"
+ {
+ return if self.english {
+ "Check Qoder task collaboration?\nUses the selected Qoder CLI with your normal login and user Skills. The verification uses a separate workspace and a local test endpoint; it does not call an upstream provider or execute a delegated task. If collaboration is enabled, it checks your installed collaboration Skill. Otherwise it checks the capability to enable it. Your daily configuration is not changed.".into()
+ } else {
+ "检查 Qoder 任务协作?\n使用所选 Qoder CLI 的正常登录状态和用户技能,在独立验证目录中访问本机测试端点,不调用上游提供方,也不执行委派任务。已启用协作时检查已安装的用户协作技能;尚未启用时检查启用能力。不改写日常配置。".into()
+ };
}
if self.request.scope == AgentCheckScopeV1::Collaboration && self.english {
return format!(
@@ -152,42 +216,7 @@ impl PendingAgentCheck {
let data = envelope.data.ok_or("RESPONSE_DATA_MISSING")?;
if scope == AgentCheckScopeV1::Live {
let target = target.ok_or("RESPONSE_DATA_INVALID")?;
- let state = data["state"].as_str().ok_or("RESPONSE_DATA_INVALID")?;
- let checked: Vec<String> = serde_json::from_value(data["checked_model_ids"].clone())
- .map_err(|_| "RESPONSE_DATA_INVALID")?;
- let call_count = data["call_count"]
- .as_u64()
- .and_then(|value| usize::try_from(value).ok())
- .ok_or("RESPONSE_DATA_INVALID")?;
- let requested_call_count = data["requested_call_count"]
- .as_u64()
- .and_then(|value| usize::try_from(value).ok())
- .ok_or("RESPONSE_DATA_INVALID")?;
- let valid = data["scope"] == "live"
- && data["model_call"] == true
- && data["surface"]
- == serde_json::to_value(target.surface).map_err(|_| "RESPONSE_DATA_INVALID")?
- && data["applied_revision"]
- == serde_json::to_value(target.expected_applied_revision)
- .map_err(|_| "RESPONSE_DATA_INVALID")?
- && matches!(state, "passed" | "failed")
- && call_count == checked.len()
- && requested_call_count == target.client_model_ids.len()
- && checked
- .iter()
- .all(|model| target.client_model_ids.contains(model))
- && (state != "passed" || checked == target.client_model_ids);
- if !valid {
- return Err("RESPONSE_DATA_INVALID".into());
- }
- return Ok(AgentCheckCompletion {
- accepted: true,
- scope: "live".into(),
- model_call: true,
- state: Some(state.into()),
- call_count,
- requested_call_count,
- });
+ return AgentCheckCompletion::from_live_result(&target, &data);
}
let valid = if scope == AgentCheckScopeV1::Collaboration {
data["scope"] == "collaboration"
@@ -213,57 +242,73 @@ impl PendingAgentCheck {
}
}
-impl Session {
- pub async fn prepare_agent_check(
- &mut self,
- input: AgentCheckInput,
- ) -> Result<AgentCheckConfirmation, DesktopFailure> {
- if !matches!(input.language.as_str(), "zh" | "en") {
+impl AgentCheckInput {
+ fn request(&self) -> Result<AgentCheckRequestV1, DesktopFailure> {
+ if !matches!(self.language.as_str(), "zh" | "en") {
return Err("AGENT_INPUT_INVALID".into());
}
- let scope = match input.scope.as_deref() {
+ let scope = match self.scope.as_deref() {
None | Some("native_authentication") => AgentCheckScopeV1::NativeAuthentication,
Some("collaboration") => AgentCheckScopeV1::Collaboration,
Some("live") => AgentCheckScopeV1::Live,
Some(_) => return Err("AGENT_INPUT_INVALID".into()),
};
- if !matches!(
- input.agent_id.as_str(),
- "agent_codex_default" | "agent_claude_default"
- ) {
+ let supported = match self.agent_id.as_str() {
+ "agent_codex_default" | "agent_claude_default" => true,
+ "agent_qoder_default" => matches!(
+ scope,
+ AgentCheckScopeV1::Collaboration | AgentCheckScopeV1::Live
+ ),
+ _ => false,
+ };
+ if !supported {
return Err("AGENT_INPUT_INVALID".into());
}
if scope == AgentCheckScopeV1::Live {
- let target = input.target.as_ref().ok_or("AGENT_INPUT_INVALID")?;
- let valid_surface = match input.agent_id.as_str() {
+ let target = self.target.as_ref().ok_or("AGENT_INPUT_INVALID")?;
+ let valid_surface = match self.agent_id.as_str() {
"agent_claude_default" => target.surface == AgentModelSurfaceV2::ClaudeCli,
- "agent_codex_default" => target.surface != AgentModelSurfaceV2::ClaudeCli,
+ "agent_codex_default" => matches!(
+ target.surface,
+ AgentModelSurfaceV2::CodexCli | AgentModelSurfaceV2::CodexDesktop
+ ),
+ "agent_qoder_default" => target.surface == AgentModelSurfaceV2::QoderCli,
_ => false,
};
if !valid_surface {
return Err("AGENT_INPUT_INVALID".into());
}
- } else if input.target.is_some() {
+ } else if self.target.is_some() {
return Err("AGENT_INPUT_INVALID".into());
}
- let snapshot = self.snapshot().await?;
- if !snapshot.trusted_authority || !snapshot.service.mutation_available {
- return Err("TRUSTED_AUTHORITY_UNAVAILABLE".into());
- }
- #[cfg(unix)]
- if !self.resident.has_authority() {
- return Err("TRUSTED_AUTHORITY_UNAVAILABLE".into());
- }
let request = AgentCheckRequestV1 {
- agent_id: input.agent_id,
+ agent_id: self.agent_id.clone(),
scope,
suite: AgentCheckSuiteV1::Quick,
allow_model_call: scope == AgentCheckScopeV1::Live,
- target: input.target,
+ target: self.target.clone(),
};
if !request.valid_target() {
return Err("AGENT_INPUT_INVALID".into());
}
+ Ok(request)
+ }
+}
+
+impl Session {
+ pub async fn prepare_agent_check(
+ &mut self,
+ input: AgentCheckInput,
+ ) -> Result<AgentCheckConfirmation, DesktopFailure> {
+ let request = input.request()?;
+ let snapshot = self.snapshot().await?;
+ if !snapshot.trusted_authority || !snapshot.service.mutation_available {
+ return Err("TRUSTED_AUTHORITY_UNAVAILABLE".into());
+ }
+ #[cfg(unix)]
+ if !self.resident.has_authority() {
+ return Err("TRUSTED_AUTHORITY_UNAVAILABLE".into());
+ }
let digest = CanonicalDigest::of(&request).map_err(|_| "AGENT_INPUT_INVALID")?;
Ok(AgentCheckConfirmation {
permit: self.confirmation.begin()?,
@@ -307,3 +352,203 @@ fn scope_name(scope: AgentCheckScopeV1) -> &'static str {
AgentCheckScopeV1::Live => "live",
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+
+ fn live_target() -> AgentModelCheckTargetV2 {
+ serde_json::from_value(json!({
+ "context_id": "agent-context/qoder/test",
+ "surface": "qoder_cli",
+ "expected_applied_revision": 7,
+ "client_model_ids": ["route-one", "route-two"]
+ }))
+ .unwrap()
+ }
+
+ #[test]
+ fn qoder_checks_keep_collaboration_independent_and_require_explicit_live_targets() {
+ let mut input = AgentCheckInput {
+ agent_id: "agent_qoder_default".into(),
+ language: "en".into(),
+ scope: Some("collaboration".into()),
+ target: None,
+ };
+ let request = input
+ .request()
+ .expect("Qoder collaboration can reach the protected check");
+ assert_eq!(request.scope, AgentCheckScopeV1::Collaboration);
+ assert!(!request.allow_model_call);
+ assert!(request.target.is_none());
+ input.target = Some(live_target());
+ assert!(
+ input.request().is_err(),
+ "Collaboration cannot borrow a model target"
+ );
+ input.target = None;
+ for scope in [None, Some("native_authentication"), Some("live")] {
+ input.scope = scope.map(str::to_owned);
+ assert!(input.request().is_err());
+ }
+ input.scope = Some("live".into());
+ input.target = Some(live_target());
+ let request = input.request().expect("Explicit Qoder Live target");
+ assert!(request.allow_model_call);
+ assert_eq!(request.target, input.target);
+ input
+ .target
+ .as_mut()
+ .unwrap()
+ .client_model_ids
+ .push("route-one".into());
+ assert!(
+ input.request().is_err(),
+ "Duplicate models are not an exact Live target"
+ );
+ input.target = None;
+ for agent in ["agent_codex_default", "agent_claude_default"] {
+ input.agent_id = agent.into();
+ input.scope = None;
+ assert!(
+ input.request().is_ok(),
+ "Existing clients keep native authentication"
+ );
+ }
+ }
+
+ #[test]
+ fn live_checks_accept_only_the_requested_agents_exact_surfaces() {
+ for (agent, allowed) in [
+ (
+ "agent_codex_default",
+ vec![
+ AgentModelSurfaceV2::CodexCli,
+ AgentModelSurfaceV2::CodexDesktop,
+ ],
+ ),
+ ("agent_claude_default", vec![AgentModelSurfaceV2::ClaudeCli]),
+ ("agent_qoder_default", vec![AgentModelSurfaceV2::QoderCli]),
+ ] {
+ for surface in [
+ AgentModelSurfaceV2::CodexCli,
+ AgentModelSurfaceV2::CodexDesktop,
+ AgentModelSurfaceV2::ClaudeCli,
+ AgentModelSurfaceV2::QoderCli,
+ ] {
+ let mut target = live_target();
+ target.surface = surface;
+ let input = AgentCheckInput {
+ agent_id: agent.into(),
+ language: "en".into(),
+ scope: Some("live".into()),
+ target: Some(target),
+ };
+ assert_eq!(
+ input.request().is_ok(),
+ allowed.contains(&surface),
+ "{agent}: {surface:?}"
+ );
+ }
+ }
+ }
+
+ #[test]
+ fn qoder_live_confirmation_describes_the_exact_paid_check_and_native_preservation() {
+ for (language, required) in [
+ (
+ "en",
+ [
+ "up to 2",
+ "revision 7",
+ "may be charged",
+ "additional HiRoute routes",
+ "current default model and login configuration stay unchanged",
+ ],
+ ),
+ (
+ "zh",
+ [
+ "最多发起 2 次",
+ "已应用版本 7",
+ "可能产生提供方费用",
+ "附加 HiRoute 路由",
+ "当前默认模型和登录配置保持不变",
+ ],
+ ),
+ ] {
+ let input = AgentCheckInput {
+ agent_id: "agent_qoder_default".into(),
+ language: language.into(),
+ scope: Some("live".into()),
+ target: Some(live_target()),
+ };
+ let request = input.request().unwrap();
+ let mut gate = ConfirmationGate::default();
+ let context = AgentCheckConfirmation {
+ permit: gate.begin().unwrap(),
+ digest: CanonicalDigest::of(&request).unwrap(),
+ request,
+ revisions: RevisionSetV1 {
+ target: 3,
+ dependencies: Default::default(),
+ },
+ english: language == "en",
+ };
+ assert!(context.requires_confirmation());
+ let message = context.message();
+ for text in required
+ .into_iter()
+ .chain(["Qoder CLI", "route-one", "route-two"])
+ {
+ assert!(message.contains(text), "Missing {text}: {message}");
+ }
+ assert_eq!(
+ context.revision(),
+ 3,
+ "Service revision remains separate from applied revision"
+ );
+ }
+ }
+
+ #[test]
+ fn qoder_live_completion_requires_the_confirmed_target_and_complete_success() {
+ let target = live_target();
+ let result = json!({
+ "scope": "live", "model_call": true, "surface": "qoder_cli",
+ "applied_revision": 7, "state": "passed",
+ "checked_model_ids": ["route-one", "route-two"],
+ "call_count": 2, "requested_call_count": 2
+ });
+ let completion = AgentCheckCompletion::from_live_result(&target, &result).unwrap();
+ assert!(completion.passed());
+ assert!(completion.model_call);
+ for (field, value) in [
+ ("surface", json!("codex_cli")),
+ ("applied_revision", json!(8)),
+ (
+ "checked_model_ids",
+ json!(["route-one", "unselected-route"]),
+ ),
+ ("call_count", json!(1)),
+ ("requested_call_count", json!(1)),
+ ("model_call", json!(false)),
+ ] {
+ let mut changed = result.clone();
+ changed[field] = value;
+ assert!(
+ AgentCheckCompletion::from_live_result(&target, &changed).is_err(),
+ "{field}"
+ );
+ }
+ let mut partial = result;
+ partial["checked_model_ids"] = json!(["route-one"]);
+ partial["call_count"] = json!(1);
+ assert!(AgentCheckCompletion::from_live_result(&target, &partial).is_err());
+ partial["state"] = json!("failed");
+ let failed = AgentCheckCompletion::from_live_result(&target, &partial).unwrap();
+ assert!(!failed.passed());
+ assert_eq!((failed.call_count, failed.requested_call_count), (1, 2));
+ }
+}
diff --git a/apps/desktop/src-tauri/src/agent_session.rs b/apps/desktop/src-tauri/src/agent_session.rs
index 169ef15b..f8dde1f7 100644
--- a/apps/desktop/src-tauri/src/agent_session.rs
+++ b/apps/desktop/src-tauri/src/agent_session.rs
@@ -1,5 +1,6 @@
//! Agent-specific native flow over shared Client Core and the existing confirmation/recovery.
use super::*;
+use hiroute_application_api::AgentSettingsStatusV2;
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
@@ -22,7 +23,7 @@ pub struct AgentEntry {
pub native_model_catalog: Option<Value>,
pub context_id: Option<String>,
#[serde(default)]
- pub settings: Option<AgentModelSettingsStatusV2>,
+ pub settings: Option<AgentSettingsStatusV2>,
#[serde(default)]
pub status_error: Option<String>,
}
@@ -109,7 +110,7 @@ fn trusted_preview_spec(requested: &AgentSettingsSpecV2, returned: &AgentSetting
pub struct AgentConfirmation {
plan_names: std::collections::BTreeMap<String, String>,
agent_name: String,
- previous: Option<AgentModelSettingsStatusV2>,
+ previous: Option<AgentSettingsStatusV2>,
permit: ConfirmationPermit,
input: AgentSettingsInput,
preview: AgentPreview,
@@ -130,10 +131,29 @@ impl AgentConfirmation {
self.input.language == "en"
}
pub fn message(&self) -> String {
+ let qoder_routes = self.agent_name == "Qoder"
+ || matches!(
+ &self.input.spec.model,
+ AgentFacetIntent::Configure {
+ settings: AgentModelSelectionV2::QoderAdditional { .. }
+ }
+ )
+ || self
+ .previous
+ .as_ref()
+ .and_then(AgentSettingsStatusV2::model)
+ .and_then(|status| status.current_selection.as_ref())
+ .is_some_and(|selection| {
+ matches!(selection, AgentModelSelectionV2::QoderAdditional { .. })
+ });
let action = if self.input.spec.is_restore_only()
&& matches!(&self.input.spec.model, AgentFacetIntent::Restore { .. })
{
- if self.english() {
+ if qoder_routes && self.english() {
+ "Remove additional HiRoute model routes"
+ } else if qoder_routes {
+ "移除附加 HiRoute 模型路由"
+ } else if self.english() {
"Restore owned model settings"
} else {
"恢复受管模型设置"
@@ -182,6 +202,24 @@ impl AgentConfirmation {
};
let effect = &self.preview.model_effect;
let details = match &self.input.spec.model {
+ AgentFacetIntent::Configure {
+ settings: AgentModelSelectionV2::QoderAdditional { allowed_plan_ids },
+ } => {
+ let routes = allowed_plan_ids
+ .iter()
+ .map(|id| route_name(id.as_str()))
+ .collect::<Vec<_>>()
+ .join(", ");
+ if self.english() {
+ format!(
+ "Additional HiRoute routes: {routes}\nChoose one of these routes explicitly in Qoder to use HiRoute. Your native models, current default model and login configuration stay unchanged."
+ )
+ } else {
+ format!(
+ "附加 HiRoute 路由:{routes}\n在 Qoder 中明确选择这些路由后才会使用 HiRoute;原生模型、当前默认模型和登录配置保持不变。"
+ )
+ }
+ }
AgentFacetIntent::Configure { settings } => format!(
"{}: {}\n{}: {}\n{}: {}\n{}",
if self.english() {
@@ -208,6 +246,22 @@ impl AgentConfirmation {
"认证将替换为仅此连接使用的本机凭据。"
}
),
+ AgentFacetIntent::Restore { .. } if qoder_routes => {
+ let mut details = if self.english() {
+ "Remove only HiRoute-owned additional model routes. Your native models, current default model and login configuration stay unchanged."
+ } else {
+ "仅移除 HiRoute 拥有的附加模型路由;原生模型、当前默认模型和登录配置保持不变。"
+ }
+ .to_owned();
+ if matches!(&self.input.spec.collaboration, AgentFacetIntent::Keep) {
+ details.push_str(if self.english() {
+ " Task collaboration stays unchanged."
+ } else {
+ "任务协作保持不变。"
+ });
+ }
+ details
+ }
AgentFacetIntent::Restore { .. } => if self.english() {
"Restore the previously saved model configuration."
} else {
@@ -231,10 +285,13 @@ impl AgentConfirmation {
}
.into(),
},
- AgentFacetIntent::Restore { .. } => if self.english() {
- "Disable task routing for this Agent. Model routing stays configured."
- } else {
- "停用此 Agent 的任务路由;模型路由保持原配置。"
+ AgentFacetIntent::Restore { .. } => match (self.english(), &self.input.spec.model) {
+ (true, AgentFacetIntent::Keep) => {
+ "Disable task routing for this Agent. Model configuration stays unchanged."
+ }
+ (false, AgentFacetIntent::Keep) => "停用此 Agent 的任务路由;模型配置保持不变。",
+ (true, _) => "Disable task routing for this Agent.",
+ (false, _) => "停用此 Agent 的任务路由。",
}
.into(),
AgentFacetIntent::Keep => String::new(),
@@ -244,6 +301,7 @@ impl AgentConfirmation {
&& let Some(before) = self
.previous
.as_ref()
+ .and_then(AgentSettingsStatusV2::model)
.and_then(|s| s.current_selection.as_ref())
{
let before_model = default_model(before);
@@ -285,6 +343,8 @@ impl AgentConfirmation {
}
let model_details = if changes.is_empty() {
details
+ } else if qoder_routes {
+ format!("{}\n{details}", changes.join("\n"))
} else {
format!(
"{}\n{}",
@@ -469,6 +529,7 @@ impl Session {
.map(|agent| match agent.agent_id.as_str() {
"agent_codex_default" => "Codex".to_owned(),
"agent_claude_default" => "Claude Code".to_owned(),
+ "agent_qoder_default" => "Qoder".to_owned(),
_ => if input.language == "en" {
"Scanned Agent"
} else {
@@ -626,6 +687,178 @@ mod tests {
use super::*;
use serde_json::json;
+ fn qoder_spec() -> AgentSettingsSpecV2 {
+ serde_json::from_value(json!({
+ "schema_version": {"major": 2, "minor": 0},
+ "context_id": "agent-context/qoder/test",
+ "model": {"intent": "configure", "settings": {
+ "mode": "qoder_additional", "allowed_plan_ids": ["plan/one", "plan/two"]
+ }}
+ }))
+ .unwrap()
+ }
+
+ fn qoder_confirmation(spec: AgentSettingsSpecV2, language: &str) -> AgentConfirmation {
+ let digest = CanonicalDigest::of(&spec).unwrap();
+ let model_action = match &spec.model {
+ AgentFacetIntent::Keep => "keep",
+ AgentFacetIntent::Configure { .. } => "configure",
+ AgentFacetIntent::Restore { .. } => "restore",
+ };
+ let preview = AgentPreview {
+ schema: "hiroute.agent-settings-preview/v2".into(),
+ spec: spec.clone(),
+ accept_digest: digest.clone(),
+ dependency_digest: digest.clone(),
+ expected_revisions: RevisionSetV1 {
+ target: 7,
+ dependencies: Default::default(),
+ },
+ applicable: true,
+ blockers: vec![],
+ model_effect: json!({"action": model_action}),
+ collaboration_effect: None,
+ resident_service: AgentResidentServicePreview::default(),
+ };
+ let request = AgentSettingsApplyV2 {
+ spec: spec.clone(),
+ accept_digest: preview.accept_digest.clone(),
+ dependency_digest: preview.dependency_digest.clone(),
+ expected_revisions: preview.expected_revisions.clone(),
+ idempotency_key: "qoder-settings-test".into(),
+ login_item: None,
+ };
+ AgentConfirmation {
+ plan_names: [
+ ("plan/one".into(), "Route one".into()),
+ ("plan/two".into(), "Route two".into()),
+ ]
+ .into(),
+ agent_name: "Qoder".into(),
+ previous: None,
+ permit: ConfirmationGate::default().begin().unwrap(),
+ input: AgentSettingsInput {
+ spec,
+ language: language.into(),
+ custom_token: None,
+ },
+ preview,
+ request,
+ intent: IntentEvidence {
+ schema: "hiroute.desktop-agent-settings-intent/v2".into(),
+ digest,
+ },
+ token_candidate: None,
+ }
+ }
+
+ #[test]
+ fn qoder_preview_cannot_change_the_exact_routes_context_or_other_facets() {
+ let requested = qoder_spec();
+ assert!(trusted_preview_spec(&requested, &requested));
+ let wire = serde_json::to_value(&requested).unwrap();
+ for routes in [
+ json!(["plan/one"]),
+ json!(["plan/one", "plan/two", "plan/three"]),
+ ] {
+ let mut changed = wire.clone();
+ changed["model"]["settings"]["allowed_plan_ids"] = routes;
+ let changed = serde_json::from_value(changed).unwrap();
+ assert!(!trusted_preview_spec(&requested, &changed));
+ }
+ for (field, value) in [
+ ("context_id", json!("agent-context/qoder/other")),
+ ("access_token", json!({"intent": "regenerate"})),
+ (
+ "collaboration",
+ json!({"intent": "configure", "settings": {"trigger_mode": "explicit"}}),
+ ),
+ (
+ "model",
+ json!({"intent": "configure", "settings": {
+ "mode": "codex_default", "native_model_mode": "preserve_available",
+ "fixed_models": [], "allowed_plan_ids": ["plan/one", "plan/two"],
+ "default_selection": {"kind": "preserve_native"}
+ }}),
+ ),
+ ] {
+ let mut changed = wire.clone();
+ changed[field] = value;
+ let changed = serde_json::from_value(changed).unwrap();
+ assert!(!trusted_preview_spec(&requested, &changed), "{field}");
+ }
+ }
+
+ #[test]
+ fn qoder_route_save_and_independent_restores_describe_only_their_owned_effects() {
+ let previous: AgentSettingsStatusV2 = serde_json::from_value(json!({
+ "schema": "hiroute.agent-model-settings-status/v2",
+ "context_id": "agent-context/qoder/test", "state": "configured",
+ "operation_id": "operation/qoder", "operation_state": "succeeded",
+ "restore_point_ref": "model-restore/qoder", "applied_revision": 7,
+ "surface_results": [], "model_verified": false,
+ "current_selection": {"mode": "qoder_additional", "allowed_plan_ids": ["plan/one"]}
+ }))
+ .unwrap();
+ for (language, preservation, collaboration_kept, models_kept) in [
+ (
+ "en",
+ "native models, current default model and login configuration stay unchanged",
+ "Task collaboration stays unchanged",
+ "Model configuration stays unchanged",
+ ),
+ (
+ "zh",
+ "原生模型、当前默认模型和登录配置保持不变",
+ "任务协作保持不变",
+ "模型配置保持不变",
+ ),
+ ] {
+ let mut configured = qoder_confirmation(qoder_spec(), language);
+ configured.previous = Some(previous.clone());
+ assert!(!configured.requires_confirmation());
+ let message = configured.message();
+ for text in ["Route one", "+ Route two", preservation] {
+ assert!(message.contains(text), "Missing {text}: {message}");
+ }
+
+ let mut spec = qoder_spec();
+ spec.model = AgentFacetIntent::Restore {
+ restore_point_ref: "model-restore/qoder".into(),
+ };
+ let mut restored = qoder_confirmation(spec, language);
+ restored.agent_name = "Agent identity unavailable".into();
+ restored.previous = Some(previous.clone());
+ assert!(restored.requires_confirmation());
+ assert_eq!(restored.revision(), 7);
+ let message = restored.message();
+ assert!(message.contains(preservation), "{message}");
+ assert!(message.contains(collaboration_kept), "{message}");
+ assert!(message.contains(if language == "en" {
+ "only HiRoute-owned additional model routes"
+ } else {
+ "仅移除 HiRoute 拥有的附加模型路由"
+ }));
+
+ let mut both = restored.input.spec.clone();
+ both.collaboration = AgentFacetIntent::Restore {
+ restore_point_ref: "skill-restore/qoder".into(),
+ };
+ let message = qoder_confirmation(both, language).message();
+ assert!(!message.contains(collaboration_kept));
+ assert!(!message.contains(models_kept));
+
+ let mut spec = qoder_spec();
+ spec.model = AgentFacetIntent::Keep;
+ spec.collaboration = AgentFacetIntent::Restore {
+ restore_point_ref: "skill-restore/qoder".into(),
+ };
+ let restored = qoder_confirmation(spec, language);
+ assert!(restored.requires_confirmation());
+ assert!(restored.message().contains(models_kept));
+ }
+ }
+
#[test]
fn preview_cannot_replace_the_requested_token_action() {
let requested: AgentSettingsSpecV2 = serde_json::from_value(json!({
diff --git a/apps/desktop/src-tauri/src/bridge/worker_dependencies_tests.rs b/apps/desktop/src-tauri/src/bridge/worker_dependencies_tests.rs
new file mode 100644
index 00000000..039a4215
--- /dev/null
+++ b/apps/desktop/src-tauri/src/bridge/worker_dependencies_tests.rs
@@ -0,0 +1,183 @@
+//! Native installation selection before protected Worker admission.
+use super::*;
+use hiroute_domain::delegation::WorkerHarnessV1;
+
+fn selection(root: &Path) -> WorkerDependenciesSelectRequestV1 {
+ WorkerDependenciesSelectRequestV1 {
+ harness: WorkerHarnessV1::CodexCli,
+ adapter_path: Some(root.join("adapter.js").to_string_lossy().into_owned()),
+ cli_path: root.join("codex").to_string_lossy().into_owned(),
+ node_path: Some(root.join("node").to_string_lossy().into_owned()),
+ expected_selection_revision: 3,
+ }
+}
+
+fn make_file(path: &Path, mode: u32) {
+ fs::write(path, b"fixture").unwrap();
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ fs::set_permissions(path, fs::Permissions::from_mode(mode)).unwrap();
+ }
+}
+
+fn native_selection(root: &Path) -> WorkerDependenciesSelectRequestV1 {
+ WorkerDependenciesSelectRequestV1 {
+ harness: WorkerHarnessV1::QoderCli,
+ adapter_path: None,
+ cli_path: root.join("./qodercli").to_string_lossy().into_owned(),
+ node_path: None,
+ expected_selection_revision: 3,
+ }
+}
+
+#[test]
+fn qoder_confirmation_retains_only_the_canonical_cli_and_revision() {
+ let root = tempfile::tempdir().unwrap();
+ make_file(&root.path().join("qodercli"), 0o700);
+ let normalized = normalize_worker_dependency_selection(&native_selection(root.path())).unwrap();
+ assert_eq!(
+ Path::new(&normalized.cli_path),
+ fs::canonicalize(root.path().join("qodercli")).unwrap()
+ );
+ let state = WorkerDependencyConfirmationState::default();
+ let confirmation = state.prepare("main", normalized.clone(), 1).unwrap();
+ let confirmed = state
+ .take("main", &confirmation.confirmation_id, 2)
+ .unwrap();
+ assert_eq!(confirmed, normalized);
+ let wire = serde_json::to_value(&confirmed).unwrap();
+ assert!(wire.get("adapter_path").is_none() && wire.get("node_path").is_none());
+ let plan = hiroute_application_api::plan_worker_dependency_selection(&confirmed).unwrap();
+ assert_eq!(plan.expected_revisions.target, 3);
+ assert_eq!(plan.change.after_selection.cli_path, normalized.cli_path);
+ assert!(
+ state
+ .take("main", &confirmation.confirmation_id, 3)
+ .is_err()
+ );
+}
+
+#[test]
+fn native_and_adapter_installations_cannot_borrow_each_others_shape() {
+ let root = tempfile::tempdir().unwrap();
+ let qoder = native_selection(root.path());
+ let absent = root
+ .path()
+ .join("not-installed")
+ .to_string_lossy()
+ .into_owned();
+ for request in [
+ WorkerDependenciesSelectRequestV1 {
+ adapter_path: Some(absent.clone()),
+ ..qoder.clone()
+ },
+ WorkerDependenciesSelectRequestV1 {
+ node_path: Some(absent),
+ ..qoder.clone()
+ },
+ WorkerDependenciesSelectRequestV1 {
+ harness: WorkerHarnessV1::CodexCli,
+ ..qoder.clone()
+ },
+ WorkerDependenciesSelectRequestV1 {
+ harness: WorkerHarnessV1::ClaudeCode,
+ ..qoder
+ },
+ ] {
+ assert!(matches!(
+ normalize_worker_dependency_selection(&request),
+ Err(DesktopFailure::Native { code }) if code == "REQUEST_INVALID"
+ ));
+ }
+}
+
+#[test]
+fn qoder_requires_an_existing_executable_file_before_confirmation() {
+ let root = tempfile::tempdir().unwrap();
+ let request = native_selection(root.path());
+ assert!(matches!(
+ normalize_worker_dependency_selection(&request),
+ Err(DesktopFailure::Native { code }) if code == "WORKER_DEPENDENCIES_MISSING"
+ ));
+ fs::create_dir(root.path().join("qodercli")).unwrap();
+ assert!(matches!(
+ normalize_worker_dependency_selection(&request),
+ Err(DesktopFailure::Native { code }) if code == "WORKER_DEPENDENCIES_INVALID"
+ ));
+ #[cfg(unix)]
+ {
+ fs::remove_dir(root.path().join("qodercli")).unwrap();
+ make_file(&root.path().join("qodercli"), 0o600);
+ assert!(matches!(
+ normalize_worker_dependency_selection(&request),
+ Err(DesktopFailure::Native { code }) if code == "WORKER_DEPENDENCIES_INVALID"
+ ));
+ }
+}
+
+#[test]
+fn preparation_canonicalizes_and_checks_each_selected_component() {
+ let root = tempfile::tempdir().unwrap();
+ make_file(&root.path().join("adapter.js"), 0o600);
+ make_file(&root.path().join("codex"), 0o700);
+ make_file(&root.path().join("node"), 0o700);
+ for harness in [WorkerHarnessV1::CodexCli, WorkerHarnessV1::ClaudeCode] {
+ let request = WorkerDependenciesSelectRequestV1 {
+ harness,
+ ..selection(root.path())
+ };
+ let normalized = normalize_worker_dependency_selection(&request).unwrap();
+ assert_eq!(
+ normalized.adapter_path,
+ Some(
+ fs::canonicalize(root.path().join("adapter.js"))
+ .unwrap()
+ .to_string_lossy()
+ .into_owned()
+ )
+ );
+ let native_adapter = WorkerDependenciesSelectRequestV1 {
+ node_path: None,
+ ..normalized
+ };
+ assert!(normalize_worker_dependency_selection(&native_adapter).is_err());
+ }
+}
+
+#[test]
+fn confirmation_is_window_bound_single_use_and_expiring() {
+ let root = tempfile::tempdir().unwrap();
+ make_file(&root.path().join("adapter.js"), 0o600);
+ make_file(&root.path().join("codex"), 0o700);
+ make_file(&root.path().join("node"), 0o700);
+ let state = WorkerDependencyConfirmationState::default();
+ let first = state.prepare("main", selection(root.path()), 1).unwrap();
+ assert!(state.take("other", &first.confirmation_id, 2).is_err());
+ let second = state.prepare("main", selection(root.path()), 3).unwrap();
+ assert!(state.take("main", &first.confirmation_id, 4).is_err());
+ assert_eq!(
+ state.take("main", &second.confirmation_id, 5).unwrap(),
+ selection(root.path())
+ );
+ assert!(state.take("main", &second.confirmation_id, 6).is_err());
+ let expired = state.prepare("main", selection(root.path()), 10).unwrap();
+ assert!(
+ state
+ .take(
+ "main",
+ &expired.confirmation_id,
+ 10 + WORKER_DEPENDENCY_CONFIRMATION_TTL_MS + 1,
+ )
+ .is_err()
+ );
+}
+
+#[test]
+fn cancellation_is_idempotent_for_the_owning_window() {
+ let root = tempfile::tempdir().unwrap();
+ let state = WorkerDependencyConfirmationState::default();
+ let confirmation = state.prepare("main", selection(root.path()), 1).unwrap();
+ state.cancel("main", &confirmation.confirmation_id).unwrap();
+ state.cancel("main", &confirmation.confirmation_id).unwrap();
+}
diff --git a/apps/desktop/src-tauri/src/bridge/worker_tasks.rs b/apps/desktop/src-tauri/src/bridge/worker_tasks.rs
index 78c6b260..69fb4347 100644
--- a/apps/desktop/src-tauri/src/bridge/worker_tasks.rs
+++ b/apps/desktop/src-tauri/src/bridge/worker_tasks.rs
@@ -156,10 +156,13 @@ fn normalize_worker_dependency_selection(
if !request.valid() {
return Err("REQUEST_INVALID".into());
}
- let adapter = normalize_required_path(
- Path::new(&request.adapter_path),
- request.node_path.is_none(),
- )?;
+ // The shared launch form requires adapters for Codex/Claude and forbids them for
+ // native ACP clients. Only normalize components that the validated shape contains.
+ let adapter = request
+ .adapter_path
+ .as_deref()
+ .map(|path| normalize_required_path(Path::new(path), request.node_path.is_none()))
+ .transpose()?;
let cli = normalize_required_path(Path::new(&request.cli_path), true)?;
let node = request
.node_path
@@ -168,7 +171,7 @@ fn normalize_worker_dependency_selection(
.transpose()?;
let normalized = WorkerDependenciesSelectRequestV1 {
harness: request.harness,
- adapter_path: normalized_path_string(adapter)?,
+ adapter_path: adapter.map(normalized_path_string).transpose()?,
cli_path: normalized_path_string(cli)?,
node_path: node.map(normalized_path_string).transpose()?,
expected_selection_revision: request.expected_selection_revision,
@@ -557,83 +560,5 @@ pub async fn worker_task_continue(
}
#[cfg(test)]
-mod tests {
- use super::*;
- use hiroute_domain::delegation::WorkerHarnessV1;
-
- fn selection(root: &Path) -> WorkerDependenciesSelectRequestV1 {
- WorkerDependenciesSelectRequestV1 {
- harness: WorkerHarnessV1::CodexCli,
- adapter_path: root.join("adapter.js").to_string_lossy().into_owned(),
- cli_path: root.join("codex").to_string_lossy().into_owned(),
- node_path: Some(root.join("node").to_string_lossy().into_owned()),
- expected_selection_revision: 3,
- }
- }
-
- fn make_file(path: &Path, mode: u32) {
- fs::write(path, b"fixture").unwrap();
- #[cfg(unix)]
- {
- use std::os::unix::fs::PermissionsExt;
- fs::set_permissions(path, fs::Permissions::from_mode(mode)).unwrap();
- }
- }
-
- #[test]
- fn preparation_canonicalizes_and_checks_each_selected_component() {
- let root = tempfile::tempdir().unwrap();
- make_file(&root.path().join("adapter.js"), 0o600);
- make_file(&root.path().join("codex"), 0o700);
- make_file(&root.path().join("node"), 0o700);
- let normalized = normalize_worker_dependency_selection(&selection(root.path())).unwrap();
- assert_eq!(
- normalized.adapter_path,
- fs::canonicalize(root.path().join("adapter.js"))
- .unwrap()
- .to_string_lossy()
- );
- let native_adapter = WorkerDependenciesSelectRequestV1 {
- node_path: None,
- ..normalized
- };
- assert!(normalize_worker_dependency_selection(&native_adapter).is_err());
- }
-
- #[test]
- fn confirmation_is_window_bound_single_use_and_expiring() {
- let root = tempfile::tempdir().unwrap();
- make_file(&root.path().join("adapter.js"), 0o600);
- make_file(&root.path().join("codex"), 0o700);
- make_file(&root.path().join("node"), 0o700);
- let state = WorkerDependencyConfirmationState::default();
- let first = state.prepare("main", selection(root.path()), 1).unwrap();
- assert!(state.take("other", &first.confirmation_id, 2).is_err());
- let second = state.prepare("main", selection(root.path()), 3).unwrap();
- assert!(state.take("main", &first.confirmation_id, 4).is_err());
- assert_eq!(
- state.take("main", &second.confirmation_id, 5).unwrap(),
- selection(root.path())
- );
- assert!(state.take("main", &second.confirmation_id, 6).is_err());
- let expired = state.prepare("main", selection(root.path()), 10).unwrap();
- assert!(
- state
- .take(
- "main",
- &expired.confirmation_id,
- 10 + WORKER_DEPENDENCY_CONFIRMATION_TTL_MS + 1,
- )
- .is_err()
- );
- }
-
- #[test]
- fn cancellation_is_idempotent_for_the_owning_window() {
- let root = tempfile::tempdir().unwrap();
- let state = WorkerDependencyConfirmationState::default();
- let confirmation = state.prepare("main", selection(root.path()), 1).unwrap();
- state.cancel("main", &confirmation.confirmation_id).unwrap();
- state.cancel("main", &confirmation.confirmation_id).unwrap();
- }
-}
+#[path = "worker_dependencies_tests.rs"]
+mod tests;
diff --git a/apps/desktop/src-tauri/tests/production_bootstrap.rs b/apps/desktop/src-tauri/tests/production_bootstrap.rs
index 861626af..f71cb489 100644
--- a/apps/desktop/src-tauri/tests/production_bootstrap.rs
+++ b/apps/desktop/src-tauri/tests/production_bootstrap.rs
@@ -227,6 +227,7 @@ async fn real_role_all_child_ack_and_read_only_lookup_use_shared_core() {
agent
.settings
.as_ref()
+ .and_then(|status| status.model())
.is_none_or(|status| !status.model_verified)
}));
drop(session);
diff --git a/apps/desktop/src/agent-editor-state.ts b/apps/desktop/src/agent-editor-state.ts
index d7e5db4b..a104af2c 100644
--- a/apps/desktop/src/agent-editor-state.ts
+++ b/apps/desktop/src/agent-editor-state.ts
@@ -1,101 +1,2 @@
-import type { Agent, AgentFixedModel } from './agents';
-
-export type AgentCollaborationTriggerMode = 'explicit' | 'delegate_by_default';
-export type CodexNativeModelMode = 'hiroute_only' | 'preserve_available';
-export type AgentDefaultChoice =
- | { kind: 'preserve_native' }
- | { kind: 'fixed_model'; client_model_id: string }
- | { kind: 'plan'; plan_id: string };
-export type AgentClaudePresetChoice =
- | { kind: 'preserve_native' }
- | { kind: 'plan'; plan_id: string };
-export type AgentClaudePresetMappings = {
- opus: AgentClaudePresetChoice;
- sonnet: AgentClaudePresetChoice;
- haiku: AgentClaudePresetChoice;
-};
-export type AgentEditorValues = {
- fixedModels: AgentFixedModel[];
- nativeModelMode: CodexNativeModelMode;
- allowedPlanIds: string[];
- defaultChoice: AgentDefaultChoice;
- claudePresets: AgentClaudePresetMappings;
- triggerMode: AgentCollaborationTriggerMode;
-};
-
-const preserve = (): AgentClaudePresetChoice => ({ kind: 'preserve_native' });
-
-export function editorFingerprint(value: AgentEditorValues): string {
- return JSON.stringify({
- ...value,
- allowedPlanIds: [...value.allowedPlanIds].sort(),
- });
-}
-
-export function codexDefaultChoiceValid(
- choice: AgentDefaultChoice,
- mode: CodexNativeModelMode,
- nativeDefault: string | undefined,
- fixedModels: AgentFixedModel[],
- allowedPlanIds: string[],
-): boolean {
- if (choice.kind === 'preserve_native') {
- if (mode === 'hiroute_only') return false;
- // The backend checks whether this name resolves to an authorized fixed model or selected
- // plan alias. The WebView only checks that a current name exists before Preview.
- return Boolean(nativeDefault);
- }
- return choice.kind === 'plan'
- ? allowedPlanIds.includes(choice.plan_id)
- : fixedModels.some(model => model.client_model_id === choice.client_model_id);
-}
-
-export function agentEditorSeed(
- agent: Agent,
- facet: 'model' | 'collaboration',
- availablePlanIds: string[] = [],
-): AgentEditorValues & { known: boolean } {
- const status = facet === 'model' ? agent.settings : agent.settings?.collaboration;
- const selection = status?.current_selection;
- const initial = status?.state === 'not_configured' || status?.state === 'restored';
- const known = !agent.status_error && (initial || (status?.state === 'configured' && !!selection));
- const currentModel = facet === 'model' ? agent.settings?.current_selection : undefined;
- const codex = currentModel?.mode === 'codex_default' ? currentModel : undefined;
- const claude = currentModel?.mode === 'claude_launcher' ? currentModel : undefined;
- const collaboration = facet === 'collaboration'
- && selection
- && 'trigger_mode' in selection
- ? selection
- : undefined;
- const initialPlan = facet === 'model' && initial && known && !currentModel && availablePlanIds.length === 1
- ? availablePlanIds[0] : undefined;
- return {
- known: facet === 'model'
- ? known && (initial || (agent.agent_id === 'agent_codex_default' ? !!codex : !!claude))
- : known,
- fixedModels: currentModel?.fixed_models ?? [],
- nativeModelMode: codex?.native_model_mode ?? 'hiroute_only',
- allowedPlanIds: codex?.allowed_plan_ids ?? (initialPlan && agent.agent_id === 'agent_codex_default' ? [initialPlan] : []),
- defaultChoice: codex?.default_selection ?? (initialPlan && agent.agent_id === 'agent_codex_default'
- ? { kind: 'plan', plan_id: initialPlan } : { kind: 'preserve_native' }),
- claudePresets: claude?.preset_mappings ?? {
- opus: initialPlan && agent.agent_id === 'agent_claude_default' ? { kind: 'plan', plan_id: initialPlan } : preserve(),
- sonnet: initialPlan && agent.agent_id === 'agent_claude_default' ? { kind: 'plan', plan_id: initialPlan } : preserve(),
- haiku: initialPlan && agent.agent_id === 'agent_claude_default' ? { kind: 'plan', plan_id: initialPlan } : preserve(),
- },
- triggerMode: collaboration?.trigger_mode ?? 'explicit',
- };
-}
-
-export function commonClaudePlan(mappings: AgentClaudePresetMappings): string | null {
- const ids = Object.values(mappings).map(choice => choice.kind === 'plan' ? choice.plan_id : '');
- return ids.every(id => id === ids[0]) ? ids[0] : null;
-}
-
-export function sharedClaudePlan(planId: string): AgentClaudePresetMappings {
- return {
- opus: { kind: 'plan', plan_id: planId },
- sonnet: { kind: 'plan', plan_id: planId },
- haiku: { kind: 'plan', plan_id: planId },
- };
-}
+// Compatibility entry for existing consumers. New Agent code lives with the feature.
+export * from './features/agents/editor-state.ts';
diff --git a/apps/desktop/src/agent-mutation-feedback.ts b/apps/desktop/src/agent-mutation-feedback.ts
index 5eb4c8a7..2f65446c 100644
--- a/apps/desktop/src/agent-mutation-feedback.ts
+++ b/apps/desktop/src/agent-mutation-feedback.ts
@@ -1,58 +1,2 @@
-import type { OperationReference } from './features/model-connections/types';
-
-export type AgentMutationOutcome = {
- state: string;
- operation: OperationReference | null;
-};
-
-export type AgentMutationDisposition = 'cancelled' | 'submitted' | 'unverified';
-
-/**
- * A missing Operation is not proof that an apply was a no-op. Once the native
- * host attempted submission, every non-cancelled result without an identity
- * must stay in recovery until the backend can reconcile the idempotency key.
- */
-export function classifyAgentMutation(
- mutation: AgentMutationOutcome,
-): AgentMutationDisposition {
- if (mutation.state === 'cancelled_before_apply') return 'cancelled';
- if (mutation.operation) return 'submitted';
- return 'unverified';
-}
-
-export function agentDisableMessage(state: string, language: 'zh' | 'en'): string {
- const zh = language === 'zh';
- if (state === 'succeeded') return zh
- ? '模型配置已恢复,连接已停用。'
- : 'Model settings restored; the connection is disabled.';
- if (state === 'rolled_back') return zh
- ? '停用未完成,本次变更已回滚,原连接仍有效。请处理冲突或失败原因后重新点击“停用”。'
- : 'Disable did not complete. This change was rolled back; the original connection remains active. Resolve the conflict or failure, then click Disable again.';
- if (state === 'needs_attention') return zh
- ? '停用未完成,回滚尚未确认。请查看操作状态并处理恢复问题。'
- : 'Disable did not complete and rollback is unconfirmed. Check the operation status and resolve the recovery issue.';
- return zh ? '正在恢复模型配置并停用连接…' : 'Restoring model settings and disabling the connection…';
-}
-
-export function agentActionErrorMessage(code: string, language: 'zh' | 'en'): string {
- const zh = language === 'zh';
- if (code === 'AGENT_TOKEN_INVALID') return zh
- ? '令牌须为 16–128 位英文字母、数字或 . _ ~ -。当前令牌未更改。'
- : 'Use 16–128 letters, numbers, or . _ ~ -. The current token was not changed.';
- if (['CHANGE_PREVIEW_STALE', 'REVISION_CONFLICT', 'application.error.change_preview_stale', 'application.error.revision_conflict'].includes(code)) {
- return zh
- ? '配置在保存前发生变化,本次未提交。当前选择已保留,请再次保存以重新读取最新状态。'
- : 'The configuration changed before this save was admitted. Your choices are retained; save again to use the latest state.';
- }
- if (code === 'SERVICE_UNAVAILABLE' || code === 'application.error.gateway_unavailable') {
- return zh
- ? '本机服务暂不可用,或旧接入的登录项清理未完成,本次未提交。请检查 HiRoute 服务;若正在恢复旧接入,也检查其登录项状态。'
- : 'The local service is unavailable, or cleanup of a login item from an older connection is incomplete. Nothing was submitted. Check the HiRoute service, and for an older restore also check its login item.';
- }
- if (code === 'RESOURCE_NOT_FOUND' || code === 'application.error.resource_not_found') {
- return zh
- ? 'Agent 安装或配置已变化。请重新检测该 Agent 后保存;当前选择已保留。'
- : 'The Agent installation or configuration changed. Detect it again, then save; your choices are retained.';
- }
- return zh ? '操作未完成,当前输入已保留。' : 'The operation did not complete; your input is retained.';
-}
+// Compatibility entry for existing consumers.
+export * from './features/agents/mutation-feedback.ts';
diff --git a/apps/desktop/src/agents.tsx b/apps/desktop/src/agents.tsx
index 3e5a4266..95f90163 100644
--- a/apps/desktop/src/agents.tsx
+++ b/apps/desktop/src/agents.tsx
@@ -1,23 +1,20 @@
-import { CodexAccessPanel, CodexAccessSettings, type CodexAccess } from './features/agents/CodexAccessPanel';
+import { CodexAccessPanel } from './features/agents/CodexAccessPanel';
import { confirmedCodexLaunchCommand, type PendingCodexLaunchCopy } from './features/agents/codex-launch';
-import { codexSurfaceFacts } from './features/agents/codex-surfaces';
import { BrandIcon, Dialog, Disclosure, ProductPage, UiIcon, copyText } from './ui';
import { confirmDiscard, useDiscardGuard } from './ui/discard-guard';
import React, { useEffect, useRef, useState } from 'react';
import { invoke } from '@tauri-apps/api/core';
-import {
- agentEditorSeed,
- commonClaudePlan,
- sharedClaudePlan,
- codexDefaultChoiceValid,
- editorFingerprint,
- type AgentClaudePresetMappings,
- type AgentCollaborationTriggerMode,
- type AgentDefaultChoice,
- type AgentEditorValues,
- type CodexNativeModelMode,
-} from './agent-editor-state';
-import type { Plan } from './plan-editor';
+import { agentEditorSeed, agentModelFormInvalid, editorFingerprint, EMPTY_EDITOR_VALUES, type AgentEditorValues } from './features/agents/editor-state';
+import { AgentSettingsFeedback } from './features/agents/AgentSettingsFeedback';
+import { AgentModelEditor, modelSelectionSummary } from './features/agents/AgentModelEditor';
+import { agentBrand, agentDisplayName, agentEcosystem, agentSupportsModelRouting } from './features/agents/ecosystems';
+import { agentHasNoModelConnection, agentModelStatus } from './features/agents/status';
+import { collaborationCheckFailureMessage } from './features/agents/collaboration-check-feedback';
+import { agentSettingsSpec, agentTokenSpec, prerequisiteCheck } from './features/agents/settings-request';
+import type {
+ Agent, AgentSnapshot, AgentFacet as Facet, AgentCheckScope as CheckScope,
+ AgentCollaborationTriggerMode, Preview, Outcome,
+} from './features/agents/types';
import { AgentTasks, type AgentTask, type AgentTaskRead } from './features/AgentTasks';
import type { OperationReference } from './features/model-connections/types';
import { safeDiagnosticCode } from './error-code';
@@ -25,140 +22,19 @@ import {
agentActionErrorMessage,
agentDisableMessage,
classifyAgentMutation,
- type AgentMutationOutcome,
-} from './agent-mutation-feedback';
+} from './features/agents/mutation-feedback';
+
+export type {
+ Agent, AgentSnapshot, AgentFixedModel, AgentModelSurface, AgentReasoningSelection,
+ AgentNativeReasoning, ModelStatus, CollaborationStatus,
+} from './features/agents/types';
-export type CollaborationStatus = {
- state: string;
- restore_point_ref: string | null;
- current_selection?: { trigger_mode: AgentCollaborationTriggerMode } | null;
-};
-export type AgentModelSurface = 'codex_cli' | 'codex_desktop' | 'claude_cli';
-export type AgentReasoningSelection =
- | { kind: 'profile'; profile: string }
- | { kind: 'toggle'; enabled: boolean }
- | { kind: 'budget'; tokens: number };
-export type AgentNativeReasoning =
- | { kind: 'fixed'; profile: string }
- | { kind: 'toggle'; parameter: string }
- | { kind: 'discrete'; parameter: string; profiles: string[] }
- | { kind: 'budget'; parameter: string; minimum_tokens: number; maximum_tokens: number; step_tokens: number };
-export type AgentFixedModel = {
- client_model_id: string;
- candidate: { binding_id: string; reasoning?: AgentReasoningSelection };
-};
-type AgentModelSourceCoverage = {
- binding_id: string;
- source_label: string;
- account_scope_ref: string;
- account_scope_digest: string;
- state: 'ready' | 'credential_required' | 'authorization_required' | 'disabled' | 'model_unconfirmed';
- reasoning: AgentNativeReasoning;
-};
-type AgentNativeModel = {
- client_model_id: string;
- display_name: string;
- source_options?: AgentModelSourceCoverage[];
-};
-type AgentNativeModelCatalog = {
- metadata_source: 'user_configured' | 'target_cache' | 'target_bundled';
- native_default_model: string;
- models: AgentNativeModel[];
-};
-type CodexModelSelection = {
- mode: 'codex_default';
- native_model_mode: CodexNativeModelMode;
- fixed_models: AgentFixedModel[];
- allowed_plan_ids: string[];
- default_selection: AgentDefaultChoice;
-};
-type ClaudeModelSelection = {
- mode: 'claude_launcher';
- surfaces: ['claude_cli'];
- fixed_models: AgentFixedModel[];
- preset_mappings: AgentClaudePresetMappings;
-};
-type AgentModelSelection = CodexModelSelection | ClaudeModelSelection;
-type AgentSurfaceResult = {
- surface: AgentModelSurface;
- applied_revision: number;
- state: 'not_verified' | 'passed' | 'failed';
- reason_code: string | null;
-};
-type AgentLiveCheckTarget = {
- context_id: string;
- surface: AgentModelSurface;
- expected_applied_revision: number;
- client_model_ids: string[];
-};
-export type ModelStatus = {
- state: string;
- model_verified: boolean;
- applied_revision?: number | null;
- surface_results?: AgentSurfaceResult[];
- live_check_targets?: AgentLiveCheckTarget[];
- current_selection?: AgentModelSelection | null;
- protected_native_model_ids?: string[];
- restore_point_ref: string | null;
- collaboration?: CollaborationStatus | null;
-};
-export type Agent = {
- codex_access?: CodexAccess | null;
- agent_id: string;
- version: string;
- context_id: string | null;
- configuration_state: string;
- available_surfaces?: AgentModelSurface[];
- native_model_catalog?: AgentNativeModelCatalog | null;
- settings: ModelStatus | null;
- status_error: string | null;
-};
-export type AgentSnapshot = {
- agents: Agent[];
- plans: { plans: Plan[] };
- trusted_authority: boolean;
-};
-type Preview = {
- applicable: boolean;
- unproven_native_model_ids?: string[];
- blockers: { reason: string; capabilities?: { capability: string; reason: string }[]; model_ids?: string[] }[];
-};
-type Outcome = {
- preview: Preview;
- mutation: AgentMutationOutcome | null;
-};
-type Facet = 'model' | 'collaboration';
-type CheckScope = 'native_authentication' | 'collaboration';
type Editor = { context: string; facet: Facet };
-const EMPTY_EDITOR_VALUES: AgentEditorValues = {
- fixedModels: [],
- nativeModelMode: 'hiroute_only',
- allowedPlanIds: [],
- defaultChoice: { kind: 'preserve_native' },
- claudePresets: {
- opus: { kind: 'preserve_native' },
- sonnet: { kind: 'preserve_native' },
- haiku: { kind: 'preserve_native' },
- },
- triggerMode: 'explicit',
-};
export function desktopErrorCode(error: unknown): string {
return safeDiagnosticCode(error, 'AGENT_UNAVAILABLE');
}
-function prerequisiteCheck(preview: Preview, facet: Facet, agent: Agent): CheckScope | null {
- if (preview.applicable) return null;
- const missing = new Set(preview.blockers.flatMap(block => block.capabilities?.map(item => item.capability) ?? []));
- // Native ingress authentication can gate either facet: collaboration still
- // enters through the selected Agent even though it ultimately dispatches a
- // task. Treat the capability as the authority instead of inferring the check
- // from whichever settings form happened to expose the blocker.
- if (missing.has('ingress_authentication')) return 'native_authentication';
- if (facet === 'collaboration' && (missing.has('skill_loading') || missing.has('trusted_cli_execution'))) return 'collaboration';
- return null;
-}
-
export function Agents({
language,
onMutation,
@@ -208,7 +84,16 @@ export function Agents({
const [busy, setBusy] = useState(false);
const [busyText, setBusyText] = useState('');
const [loadError, setLoadError] = useState('');
- const [actionError, setActionError] = useState('');
+ const [actionError, setActionErrorCode] = useState('');
+ const [actionErrorHint, setActionErrorHint] = useState<string | null>(null);
+ function setActionError(code: string) {
+ setActionErrorCode(code);
+ setActionErrorHint(null);
+ }
+ function setActionFailure(error: unknown) {
+ setActionErrorCode(desktopErrorCode(error));
+ setActionErrorHint(collaborationCheckFailureMessage(error, language));
+ }
const [notice, setNotice] = useState('');
const [tokenEditing, setTokenEditing] = useState(false);
const [tokenDraft, setTokenDraft] = useState('');
@@ -216,13 +101,7 @@ export function Agents({
const [codexMode, setCodexMode] = useState<'profile' | 'root'>('profile');
const [showAgentList, setShowAgentList] = useState(false);
const [tab, setTab] = useState<'configuration' | 'tasks'>(initialTab);
- const agentName = (agent: Agent) => agent.agent_id === 'agent_codex_default'
- ? 'Codex'
- : agent.agent_id === 'agent_claude_default'
- ? 'Claude Code'
- : agent.agent_id.toLowerCase().includes('cursor')
- ? 'Cursor'
- : text('本机 Agent', 'Local Agent');
+ const agentName = (agent: Agent) => agentDisplayName(agent.agent_id, language);
const [editor, setEditor] = useState<Editor | null>(null);
const [editorValues, setEditorValues] = useState<AgentEditorValues>(EMPTY_EDITOR_VALUES);
const [restoreNativeModel, setRestoreNativeModel] = useState('');
@@ -324,7 +203,8 @@ export function Agents({
requestAnimationFrame(() => onCreatePlan?.());
}
async function open(agent: Agent, facet: Facet, source: HTMLElement) {
- if (!mutationAllowed || !snapshot?.trusted_authority || !agent.context_id) return;
+ if (!mutationAllowed || !snapshot?.trusted_authority || !agent.context_id || !agentEcosystem(agent.agent_id)
+ || (facet === 'model' && (!agentSupportsModelRouting(agent.agent_id) || agentHasNoModelConnection(agent)))) return;
if (dirty && !(await confirmDiscard(language))) return;
trigger.current = source;
setActionError('');
@@ -343,57 +223,8 @@ export function Agents({
setPendingLaunchCopy(null);
setBaseline(editorFingerprint(seed));
}
- function spec(agent: Agent, facet: Facet, restore: boolean) {
- if (!agent.context_id) throw new Error('AGENT_INPUT_INVALID');
- const keep = { intent: 'keep' };
- if (facet === 'model') {
- const settings = agent.agent_id === 'agent_codex_default'
- ? {
- mode: 'codex_default',
- native_model_mode: editorValues.nativeModelMode,
- fixed_models: editorValues.fixedModels,
- allowed_plan_ids: editorValues.allowedPlanIds,
- default_selection: editorValues.defaultChoice,
- }
- : {
- mode: 'claude_launcher',
- surfaces: ['claude_cli'],
- fixed_models: editorValues.fixedModels,
- preset_mappings: editorValues.claudePresets,
- };
- return {
- schema_version: { major: 2, minor: 0 },
- context_id: agent.codex_access && !agent.codex_access.slot_occupied
- ? (codexMode === 'root' ? agent.codex_access.root_context_id : agent.codex_access.profile_context_id)
- : agent.context_id,
- restore_native_model: restore && agent.agent_id === 'agent_codex_default' && agent.codex_access?.selected_mode !== 'profile' && restoreNativeModel
- ? restoreNativeModel : undefined,
- model: restore
- ? { intent: 'restore', restore_point_ref: agent.settings?.restore_point_ref }
- : { intent: 'configure', settings },
- collaboration: keep,
- };
- }
-
- return {
- schema_version: { major: 2, minor: 0 },
- context_id: agent.codex_access?.root_context_id ?? agent.context_id,
- model: keep,
- collaboration: restore
- ? {
- intent: 'restore',
- restore_point_ref: agent.settings?.collaboration?.restore_point_ref,
- }
- : {
- intent: 'configure',
- settings: {
- trigger_mode: editorValues.triggerMode,
- },
- },
- };
- }
async function change(agent: Agent, facet: Facet, restore: boolean, source: HTMLElement | null) {
- if (busy || !mutationAllowed || !snapshot?.trusted_authority || !agent.context_id || (!restore && !selectionKnown)) return;
+ if (busy || !mutationAllowed || !snapshot?.trusted_authority || !agent.context_id || !agentEcosystem(agent.agent_id) || (!restore && !selectionKnown)) return;
setBusy(true);
setBusyText(text('正在保存…', 'Saving…'));
setActionError('');
@@ -401,9 +232,9 @@ export function Agents({
setPreview(null);
let blockedByCheck: Preview | null = null;
try {
- const input = { language, spec: spec(agent, facet, restore) };
+ const input = { language, spec: agentSettingsSpec(agent, facet, restore, { values: editorValues, codexMode, restoreNativeModel }) };
let result = await invoke<Outcome>('preview_agent_settings', { input });
- const checkScope = !restore ? prerequisiteCheck(result.preview, facet, agent) : null;
+ const checkScope = !restore ? prerequisiteCheck(result.preview, facet) : null;
if (checkScope) {
blockedByCheck = result.preview;
setBusyText(text('正在检查并保存…', 'Checking and saving…'));
@@ -434,7 +265,7 @@ export function Agents({
setNotice(agentDisableMessage(result.mutation.operation.state, language));
if (!['succeeded', 'rolled_back', 'needs_attention'].includes(result.mutation.operation.state)) setPendingDisable(result.mutation.operation.operation_id);
}
- if (!restore && facet === 'model' && agent.codex_access && activeCodexMode === 'profile' && !agent.settings?.current_selection) {
+ if (!restore && facet === 'model' && agent.codex_access && activeCodexMode === 'profile' && !agentModelStatus(agent)?.current_selection) {
setPendingLaunchCopy({ operationId: result.mutation.operation.operation_id, contextId: input.spec.context_id });
}
onOperation?.(result.mutation.operation, presentation);
@@ -450,7 +281,7 @@ export function Agents({
await refresh();
} catch (caught) {
setPreview(blockedByCheck);
- setActionError(desktopErrorCode(caught));
+ setActionFailure(caught);
onMutation();
await refresh();
} finally {
@@ -460,8 +291,8 @@ export function Agents({
}
}
async function changeToken(agent: Agent, regenerate: boolean, source: HTMLElement | null) {
- const selection = agent.settings?.current_selection;
- if (busy || !mutationAllowed || !snapshot?.trusted_authority || !agent.context_id || !selection || agent.settings?.state !== 'configured') return;
+ const selection = agentModelStatus(agent)?.current_selection;
+ if (busy || !mutationAllowed || !snapshot?.trusted_authority || !agent.context_id || !agentEcosystem(agent.agent_id) || !selection || agentModelStatus(agent)?.state !== 'configured') return;
const custom = regenerate ? undefined : tokenDraft;
if (custom !== undefined && !/^[A-Za-z0-9._~-]{16,128}$/.test(custom)) {
setActionError('AGENT_TOKEN_INVALID');
@@ -474,13 +305,7 @@ export function Agents({
try {
const input = {
language,
- spec: {
- schema_version: { major: 2, minor: 0 },
- context_id: agent.context_id,
- model: { intent: 'configure', settings: selection },
- collaboration: { intent: 'keep' },
- access_token: { intent: regenerate ? 'regenerate' : 'keep' },
- },
+ spec: agentTokenSpec(agent, regenerate),
custom_token: custom,
};
const result = await invoke<Outcome>('preview_agent_settings', { input });
@@ -499,7 +324,7 @@ export function Agents({
}
await refresh();
} catch (caught) {
- setActionError(desktopErrorCode(caught));
+ setActionFailure(caught);
await refresh();
} finally {
setBusy(false);
@@ -521,13 +346,17 @@ export function Agents({
!checked
? text('已取消检查。', 'Check cancelled.')
: scope === 'collaboration'
- ? text('任务委派技能检查通过;未调用上游模型。', 'Task delegation skill check passed; no upstream model was called.')
+ ? agent.agent_id === 'agent_qoder_default'
+ ? agent.settings?.collaboration?.state === 'configured'
+ ? text('用户协作技能验证通过;未执行委派任务。', 'Your installed collaboration skill passed verification; no delegated task was executed.')
+ : text('协作能力检查通过,可以启用任务协作。', 'Collaboration capability check passed. You can enable task collaboration.')
+ : text('任务委派技能检查通过;未调用上游模型。', 'Task delegation skill check passed; no upstream model was called.')
: text('本机认证兼容性检查通过;尚未验证上游模型调用。', 'Local authentication compatibility passed; upstream model access is not verified.'),
);
setPreview(null);
await refresh();
} catch (caught) {
- setActionError(desktopErrorCode(caught));
+ setActionFailure(caught);
} finally {
setBusy(false);
setBusyText('');
@@ -535,127 +364,6 @@ export function Agents({
}
}
- function toggleAllowedPlan(planId: string) {
- setEditorValues(value => {
- const selected = value.allowedPlanIds.includes(planId);
- const allowedPlanIds = selected
- ? value.allowedPlanIds.filter(id => id !== planId)
- : [...value.allowedPlanIds, planId];
- const defaultChoice = selected
- && value.defaultChoice.kind === 'plan'
- && value.defaultChoice.plan_id === planId
- ? value.nativeModelMode === 'preserve_available'
- ? { kind: 'preserve_native' } as const
- : allowedPlanIds.length ? { kind: 'plan', plan_id: allowedPlanIds[0] } as const
- : value.fixedModels.length ? { kind: 'fixed_model', client_model_id: value.fixedModels[0].client_model_id } as const
- : { kind: 'preserve_native' } as const
- : !selected && value.nativeModelMode === 'hiroute_only' && value.defaultChoice.kind === 'preserve_native'
- ? { kind: 'plan', plan_id: planId } as const
- : value.defaultChoice;
- return { ...value, allowedPlanIds, defaultChoice };
- });
- setPreview(null);
- setActionError('');
- setNotice('');
- }
-
- function defaultFixedReasoning(reasoning: AgentNativeReasoning): AgentReasoningSelection | undefined {
- if (reasoning.kind === 'fixed') return undefined;
- if (reasoning.kind === 'toggle') return { kind: 'toggle', enabled: true };
- if (reasoning.kind === 'budget') return { kind: 'budget', tokens: reasoning.maximum_tokens };
- const enabled = reasoning.profiles.filter(profile => !['none', 'off', 'disabled'].includes(profile.toLocaleLowerCase()));
- const profile = enabled.at(-1) ?? reasoning.profiles.at(-1);
- return profile ? { kind: 'profile', profile } : undefined;
- }
-
- function selectFixedSource(model: AgentNativeModel, bindingId: string) {
- setEditorValues(value => {
- const fixedModels = value.fixedModels.filter(item => item.client_model_id !== model.client_model_id);
- const source = model.source_options?.find(option => option.binding_id === bindingId && option.state === 'ready');
- if (source) {
- fixedModels.push({
- client_model_id: model.client_model_id,
- candidate: {
- binding_id: source.binding_id,
- reasoning: defaultFixedReasoning(source.reasoning),
- },
- });
- }
- const defaultChoice = !source
- && value.defaultChoice.kind === 'fixed_model'
- && value.defaultChoice.client_model_id === model.client_model_id
- ? value.nativeModelMode === 'hiroute_only' && value.allowedPlanIds.length
- ? { kind: 'plan', plan_id: value.allowedPlanIds[0] } as const
- : { kind: 'preserve_native' } as const
- : source && value.nativeModelMode === 'hiroute_only' && value.defaultChoice.kind === 'preserve_native'
- ? { kind: 'fixed_model', client_model_id: model.client_model_id } as const
- : value.defaultChoice;
- return { ...value, fixedModels, defaultChoice };
- });
- setPreview(null);
- setActionError('');
- setNotice('');
- }
-
- function setFixedReasoning(clientModelId: string, reasoning: AgentReasoningSelection | undefined) {
- setEditorValues(value => ({
- ...value,
- fixedModels: value.fixedModels.map(model => model.client_model_id === clientModelId
- ? { ...model, candidate: { ...model.candidate, reasoning } }
- : model),
- }));
- setPreview(null);
- setActionError('');
- setNotice('');
- }
-
- function defaultChoiceValue(choice: AgentDefaultChoice): string {
- if (choice.kind === 'preserve_native') return 'native';
- return `${choice.kind === 'plan' ? 'plan' : 'fixed'}:${choice.kind === 'plan' ? choice.plan_id : choice.client_model_id}`;
- }
-
- function selectDefaultChoice(value: string) {
- const defaultChoice: AgentDefaultChoice = value === 'native'
- ? { kind: 'preserve_native' }
- : value.startsWith('plan:')
- ? { kind: 'plan', plan_id: value.slice(5) }
- : { kind: 'fixed_model', client_model_id: value.slice(6) };
- setEditorValues(current => ({ ...current, defaultChoice }));
- setPreview(null);
- setActionError('');
- setNotice('');
- }
-
- function selectNativeModelMode(mode: CodexNativeModelMode) {
- setEditorValues(value => {
- if (mode === value.nativeModelMode) return value;
- const fixedModels = mode === 'hiroute_only'
- ? value.fixedModels.filter(model => !protectedNativeModelIds.has(model.client_model_id))
- : value.fixedModels;
- const defaultChoice = mode === 'hiroute_only' && value.defaultChoice.kind === 'preserve_native'
- ? value.allowedPlanIds.length ? { kind: 'plan', plan_id: value.allowedPlanIds[0] } as const
- : fixedModels.length ? { kind: 'fixed_model', client_model_id: fixedModels[0].client_model_id } as const
- : value.defaultChoice
- : value.defaultChoice;
- return { ...value, nativeModelMode: mode, fixedModels, defaultChoice };
- });
- setPreview(null);
- setActionError('');
- }
-
- function selectClaudePreset(preset: keyof AgentClaudePresetMappings, planId: string) {
- setEditorValues(value => ({
- ...value,
- claudePresets: {
- ...value.claudePresets,
- [preset]: planId ? { kind: 'plan', plan_id: planId } : { kind: 'preserve_native' },
- },
- }));
- setPreview(null);
- setActionError('');
- setNotice('');
- }
-
function setTriggerMode(triggerMode: AgentCollaborationTriggerMode) {
setEditorValues(value => ({ ...value, triggerMode }));
setPreview(null);
@@ -667,13 +375,26 @@ export function Agents({
const enabledPlans = plans.filter(plan => plan.head.status === 'enabled');
const selected = snapshot?.agents.find(agent => agent.agent_id === (selectedAgent ?? snapshot.agents[0]?.agent_id));
const selectedCollaboration = selected?.settings?.collaboration;
- const modelSelection = selected?.settings?.current_selection;
- const protectedNativeModelIds = new Set(selected?.settings?.protected_native_model_ids ?? []);
+ const selectedModel = agentModelStatus(selected);
+ const modelSelection = selectedModel?.current_selection;
const taskSelection = selectedCollaboration?.current_selection;
const needsRecovery = (state?: string | null) => state === 'drift' || state === 'needs_attention';
- const selectedHasDrift = needsRecovery(selected?.settings?.state) || needsRecovery(selectedCollaboration?.state);
- const selectedPending = selected?.settings?.state === 'pending' || selectedCollaboration?.state === 'pending';
+ const selectedHasDrift = needsRecovery(selectedModel?.state) || needsRecovery(selectedCollaboration?.state);
+ const selectedPending = selectedModel?.state === 'pending' || selectedCollaboration?.state === 'pending';
const mutable = mutationAllowed && Boolean(snapshot?.trusted_authority);
+ const qoderRecoveryOperation = selected?.agent_id === 'agent_qoder_default'
+ && !selected.status_error && ['pending', 'needs_attention'].includes(selectedModel?.state ?? '')
+ ? selectedModel?.operation_id : undefined;
+ async function retrySettingsOperation(operationId: string) {
+ if (!selected?.context_id || busy || !snapshot?.trusted_authority) return;
+ setBusy(true); setActionError('');
+ try {
+ await invoke('retry_agent_settings', { input: { schema: 'hiroute.agent-settings-retry/v1', context_id: selected.context_id, operation_id: operationId } });
+ await refresh();
+ } catch (error) { setActionFailure(error); }
+ finally { onMutation(); setBusy(false); }
+ }
+
const executableDiagnostic = (state: string) => {
switch (state) {
case 'not_found_in_scope':
@@ -701,63 +422,15 @@ export function Agents({
const selectedExecutableDiagnostic = selected
? executableDiagnostic(selected.configuration_state)
: null;
- const selectedPlansEnabled = editorValues.allowedPlanIds.every(id => enabledPlans.some(plan => plan.agent_plan_id === id));
- const defaultChoice = editorValues.defaultChoice;
const activeCodexMode = selected?.codex_access?.slot_occupied
? selected.codex_access.selected_mode : codexMode;
- const codexSurfaces = codexSurfaceFacts(activeCodexMode, selected?.available_surfaces ?? []);
- const verificationSurfaces = (selected?.available_surfaces ?? []).filter(surface =>
- selected?.agent_id !== 'agent_codex_default'
- || codexSurfaces.some(fact => fact.surface === surface && fact.applicable));
const catalogModels = (selected?.native_model_catalog?.models ?? [])
.map(model => ({ ...model, source_options: model.source_options ?? [] }));
const nativeRestoreOptions = catalogModels.filter(model =>
!plans.some(plan => plan.model_alias === model.client_model_id));
- const fixedModelRows = editorValues.fixedModels.map(fixed => catalogModels
- .find(model => model.client_model_id === fixed.client_model_id) ?? {
- client_model_id: fixed.client_model_id,
- display_name: fixed.client_model_id,
- source_options: [],
- });
- const selectedFixedSourcesValid = editorValues.fixedModels.every(fixed => {
- if (protectedNativeModelIds.has(fixed.client_model_id)) return true;
- const source = catalogModels
- .find(model => model.client_model_id === fixed.client_model_id)
- ?.source_options.find(option => option.binding_id === fixed.candidate.binding_id);
- if (!source || source.state !== 'ready') return false;
- const selection = fixed.candidate.reasoning;
- if (source.reasoning.kind === 'fixed') return selection === undefined;
- if (source.reasoning.kind === 'toggle') return selection?.kind === 'toggle';
- if (source.reasoning.kind === 'discrete') {
- return selection?.kind === 'profile' && source.reasoning.profiles.includes(selection.profile);
- }
- return selection?.kind === 'budget'
- && selection.tokens >= source.reasoning.minimum_tokens
- && selection.tokens <= source.reasoning.maximum_tokens
- && (selection.tokens - source.reasoning.minimum_tokens) % source.reasoning.step_tokens === 0;
- });
- const nativeDefault = selected?.native_model_catalog?.native_default_model;
- const codexDefaultValid = codexDefaultChoiceValid(
- defaultChoice,
- editorValues.nativeModelMode,
- nativeDefault,
- editorValues.fixedModels,
- editorValues.allowedPlanIds,
- );
- const claudePlanIds = Object.values(editorValues.claudePresets)
- .flatMap(choice => choice.kind === 'plan' ? [choice.plan_id] : []);
- const modelFormInvalid = selected?.agent_id === 'agent_codex_default'
- ? editorValues.allowedPlanIds.length + editorValues.fixedModels.length === 0
- || !selectedFixedSourcesValid
- || !selectedPlansEnabled
- || !codexDefaultValid
- : claudePlanIds.length + editorValues.fixedModels.length === 0
- || claudePlanIds.some(id => !enabledPlans.some(plan => plan.agent_plan_id === id));
+ const modelFormInvalid = agentModelFormInvalid(selected, editorValues, enabledPlans.map(plan => plan.agent_plan_id));
const formInvalid = !selectionKnown || (editor?.facet === 'model' && modelFormInvalid);
- const claudeSharedPlan = commonClaudePlan(editorValues.claudePresets);
const creatingModelConnection = editor?.facet === 'model' && !modelSelection;
- const showCodexDefault = editorValues.nativeModelMode === 'preserve_available'
- || editorValues.fixedModels.length > 0 || editorValues.allowedPlanIds.length > 1;
const submitLabel = creatingModelConnection
? selected?.agent_id === 'agent_codex_default' && activeCodexMode === 'profile'
? text('启用并复制启动命令', 'Enable and copy launch command')
@@ -765,93 +438,11 @@ export function Agents({
: editor?.facet === 'collaboration' && !taskSelection
? text('启用任务路由', 'Enable task routing') : text('保存配置', 'Save settings');
- const brand = (agent: Agent) => agent.agent_id === 'agent_codex_default' ? 'codex' : agent.agent_id === 'agent_claude_default' ? 'claude-code' : 'agent';
- const planName = (id: string) => plans.find(plan => plan.agent_plan_id === id)?.desired.display_name;
- const planEnabled = (id: string) => enabledPlans.some(plan => plan.agent_plan_id === id);
- const surfaceName = (surface: AgentModelSurface) => surface === 'codex_desktop'
- ? 'Codex Desktop'
- : surface === 'codex_cli'
- ? 'Codex CLI'
- : 'Claude Code CLI';
- const sourceStateLabel = (state: AgentModelSourceCoverage['state']) => state === 'ready'
- ? text('来源与账号已覆盖', 'Source and account covered')
- : state === 'credential_required'
- ? text('需要凭据', 'Credential required')
- : state === 'authorization_required'
- ? text('需要账号授权', 'Account authorization required')
- : state === 'disabled'
- ? text('来源已停用', 'Source disabled')
- : text('模型目录匹配未证明', 'Model directory match unproven');
- const fixedReasoningControl = (
- model: AgentNativeModel,
- fixed: AgentFixedModel,
- source: AgentModelSourceCoverage,
- ) => {
- const reasoning = source.reasoning;
- const selection = fixed.candidate.reasoning;
- if (reasoning.kind === 'fixed') {
- return <span className="field-help">{text('原生思考设置:', 'Native reasoning: ')}{reasoning.profile}</span>;
- }
- if (reasoning.kind === 'discrete') {
- return <label className="field"><span className="field-label">{text('思考强度', 'Reasoning effort')}</span><select className="select" value={selection?.kind === 'profile' ? selection.profile : ''} onChange={event => setFixedReasoning(model.client_model_id, { kind: 'profile', profile: event.target.value })}>{reasoning.profiles.map(profile => <option key={profile} value={profile}>{profile}</option>)}</select></label>;
- }
- if (reasoning.kind === 'toggle') {
- return <label className="field"><span className="field-label">{text('思考', 'Reasoning')}</span><select className="select" value={selection?.kind === 'toggle' && selection.enabled ? 'on' : 'off'} onChange={event => setFixedReasoning(model.client_model_id, { kind: 'toggle', enabled: event.target.value === 'on' })}><option value="on">{text('开启', 'On')}</option><option value="off">{text('关闭', 'Off')}</option></select></label>;
- }
- return <label className="field"><span className="field-label">{text('思考预算', 'Reasoning budget')}</span><input className="input" type="number" min={reasoning.minimum_tokens} max={reasoning.maximum_tokens} step={reasoning.step_tokens} value={selection?.kind === 'budget' ? selection.tokens : ''} onChange={event => setFixedReasoning(model.client_model_id, { kind: 'budget', tokens: Number(event.target.value) })} /><span className="field-help">{reasoning.minimum_tokens}–{reasoning.maximum_tokens} tokens</span></label>;
- };
- const savedClaudeSharedPlan = modelSelection?.mode === 'claude_launcher' ? commonClaudePlan(modelSelection.preset_mappings) : null;
- const modelSelectionSummary = modelSelection?.mode === 'codex_default'
- ? modelSelection.default_selection.kind === 'plan'
- ? planName(modelSelection.default_selection.plan_id) ?? text('当前路由不可用', 'Current route unavailable')
- : modelSelection.default_selection.kind === 'fixed_model'
- ? modelSelection.default_selection.client_model_id
- : text('使用 Codex 当前默认模型名称', 'Use the current Codex default model name')
- : modelSelection
- ? savedClaudeSharedPlan
- ? text('三个档位共用:', 'All presets use: ') + (planName(savedClaudeSharedPlan) ?? text('当前路由不可用', 'Current route unavailable'))
- : Object.entries(modelSelection.preset_mappings).map(([preset, choice]) => `${preset[0].toUpperCase() + preset.slice(1)}: ${choice.kind === 'plan' ? planName(choice.plan_id) ?? text('当前路由不可用', 'Current route unavailable') : text('保留原生', 'Native')}`).join(' · ')
- : '';
- const blockedCheckScope = preview && editor && selected
- ? prerequisiteCheck(preview, editor.facet, selected)
- : null;
- const blockedPreview = preview && !preview.applicable ? <div className="callout warn agent-feedback" role="status">
- <UiIcon name="warning" />
- <div>
- <strong>{text('当前无法应用,未修改配置。', 'Cannot apply yet. Configuration was not changed.')}</strong>
- {preview.blockers.map((block, index) => {
- const capabilities = new Set(block.capabilities?.map(capability => capability.capability) ?? []);
- const message = capabilities.has('ingress_authentication')
- ? text('本机认证兼容性尚未确认。', 'Local authentication compatibility is unconfirmed.')
- : block.reason === 'native_model_coverage_unavailable'
- ? `${text('保留原 Codex 模型需要先接入原订阅账号或 API 来源,并证明同账号路由。也可改选“只使用已配置的 HiRoute 模型”。', 'To keep native Codex models, connect the original subscription account or API source and prove same-account routes, or select HiRoute-only.')}${(block.model_ids ?? []).length ? ` ${block.model_ids!.join(', ')}` : ''}`
- : block.reason === 'native_default_invalid'
- ? `${text('原 Codex 默认模型没有同账号可用路由;请接入对应来源,或改选“只使用已配置的 HiRoute 模型”:', 'The native Codex default has no proven same-account route. Connect its source or select HiRoute-only: ')}${(block.model_ids ?? []).join(', ')}`
- : block.reason === 'restore_native_model_invalid'
- ? text('恢复将留下无效的原生默认模型。请在“连接详情与恢复”中明确选择一个原生模型后重试。', 'Restoring would leave an invalid native default. Choose a native model under Connection details and recovery, then retry.')
- : block.reason === 'model_plan_unavailable' && selected?.agent_id === 'agent_codex_default' && defaultChoice.kind === 'preserve_native'
- ? text('当前默认模型名称或所选路由无法用于 Codex Responses。请在“默认选择”中改选已勾选且支持该入口的路由;若要保留原生模型,请先接入对应来源。配置未修改。', 'The current default model name or a selected route cannot be used by Codex Responses. Under Default selection, choose an enabled route that supports this ingress; to preserve a native model, connect its source first. Configuration was not changed.')
- : block.reason === 'model_plan_unavailable' && selected?.agent_id === 'agent_codex_default'
- ? text('所选路由、固定来源或当前默认模型无法用于 Codex Responses。请核对路由是否已启用并支持该入口协议,或改选可用路由;配置未修改。', 'A selected route, fixed source, or current default model cannot be used by Codex Responses. Check that the route is enabled and supports this ingress protocol, or choose an available route. Configuration was not changed.')
- : block.reason === 'codex_context_override'
- ? text('Codex 的显式窗口配置会覆盖计划设置。请移除有效配置中的 model_context_window 和 model_auto_compact_token_limit 后重试;HiRoute 不会删除这些配置。', 'Explicit Codex window settings override the plan. Remove model_context_window and model_auto_compact_token_limit from the effective configuration and retry; HiRoute will not delete these settings.')
- : block.reason === 'claude_plan_capability_unavailable'
- ? text('所选计划无法满足 Claude Code 的工具调用或流式请求能力,请检查全部候选模型。', 'A selected plan cannot meet Claude Code tool or streaming requirements. Check all candidate models.')
- : block.reason === 'claude_context_override'
- ? text('Claude Code 存在窗口覆盖或禁用自动压缩的设置。请移除进程、项目或托管配置中的窗口覆盖,以及禁用压缩的环境变量后重试。', 'Claude Code has window overrides or compaction disabled. Remove process, project, or managed window overrides and compaction-disabling environment variables, then retry.')
- : block.reason === 'claude_context_window_unsupported'
- ? text('所选计划的共同窗口低于 Claude Code 的 100K 最低值。请调整计划窗口或使用 Codex。', 'The shared plan window is below Claude Code’s 100K minimum. Adjust the plan window or use Codex.')
- : block.reason === 'skill_file_conflict'
- ? text('同名任务委派技能内容不同;原文件已保留。请先移走或明确处理该文件后再预览。', 'A task delegation skill with different content already exists. The original was preserved; move or explicitly resolve it before previewing again.')
- : capabilities.has('skill_loading') || capabilities.has('trusted_cli_execution')
- ? text('任务委派技能尚未确认。', 'Task delegation skill capability is unconfirmed.')
- : text('有前置条件尚未满足,请检查当前 Agent 状态。', 'A prerequisite is unmet. Check the current Agent state.');
- return <p key={index}>{message}</p>;
- })}
- {preview.unproven_native_model_ids?.length ? <p>{text('目录中尚未证明可由原账号调用的模型(不会开放给 Codex):', 'Catalog names not proven callable on the original account (not exposed to Codex): ')}{preview.unproven_native_model_ids.join(', ')}</p> : null}
- {blockedCheckScope && selected && <button className="btn" type="button" disabled={busy || !mutable} onClick={event => void check(selected, blockedCheckScope, event.currentTarget)}>{blockedCheckScope === 'native_authentication' ? text('重新检查本机认证', 'Check local authentication again') : text('重新检查任务委派技能', 'Check task delegation skill again')}</button>}
- </div>
- </div> : null;
+ const brand = (agent: Agent) => agentBrand(agent.agent_id);
+ const selectionSummary = modelSelectionSummary(modelSelection, plans, language);
+ const blockedPreview = <AgentSettingsFeedback preview={preview} agent={selected} facet={editor?.facet}
+ defaultChoice={editorValues.defaultChoice} language={language} disabled={busy || !mutable}
+ onCheck={(scope, source) => { if (selected) void check(selected, scope, source); }} />;
const executableStatus = selectedExecutableDiagnostic ? <div className="callout warn agent-feedback" data-agent-executable-state={selected?.configuration_state} role="status">
<UiIcon name="warning" />
<div>
@@ -878,8 +469,8 @@ export function Agents({
<nav className="master-list native-list" aria-label={text('Agent 列表', 'Agent list')}>
{snapshot?.agents.map(agent => {
const active = (selectedAgent ?? snapshot.agents[0]?.agent_id) === agent.agent_id;
- const stateNeedsRecovery = needsRecovery(agent.settings?.state) || needsRecovery(agent.settings?.collaboration?.state);
- const statePending = agent.settings?.state === 'pending' || agent.settings?.collaboration?.state === 'pending';
+ const stateNeedsRecovery = needsRecovery(agentModelStatus(agent)?.state) || needsRecovery(agent.settings?.collaboration?.state);
+ const statePending = agentModelStatus(agent)?.state === 'pending' || agent.settings?.collaboration?.state === 'pending';
const executableState = executableDiagnostic(agent.configuration_state);
const stateLabel = agent.status_error
? text('状态待确认', 'Status unverified')
@@ -889,10 +480,8 @@ export function Agents({
? text('接入需要处理', 'Connection needs attention')
: statePending
? text('正在更新', 'Updating')
- : agent.settings?.current_selection
- ? agent.settings.model_verified
- ? text('路由已验证', 'Routing verified')
- : text('路由已配置 · 调用未验证', 'Routing configured · call unverified')
+ : agentModelStatus(agent)?.current_selection
+ ? text('路由已配置', 'Routing configured')
: agent.settings?.collaboration?.current_selection
? text('任务路由已启用', 'Task routing enabled')
: text('已发现 · 尚未接入', 'Detected · not connected');
@@ -910,42 +499,32 @@ export function Agents({
{!mutable && !selected.codex_access?.pending_operation && <div className="callout warn"><UiIcon name="warning" /><div><strong>{text('Agent 配置可以查看,暂时不能修改', 'Agent settings are viewable but cannot be changed')}</strong><p>{text('本机服务尚未就绪,连接恢复后即可保存配置。', 'The local service is not ready. Reconnect before saving.')}</p></div></div>}
{selected.codex_access && <CodexAccessPanel access={selected.codex_access} language={language} retryDisabled={busy || Boolean(editor) || !snapshot.trusted_authority} onRetry={async () => {
const access = selected.codex_access;
- if (!access?.pending_operation || !selected.context_id || busy) return;
- setBusy(true); setActionError('');
- try {
- await invoke('retry_agent_settings', { input: { schema: 'hiroute.agent-settings-retry/v1', context_id: selected.context_id, operation_id: access.pending_operation } });
- await refresh();
- } catch (error) { setActionError(desktopErrorCode(error)); }
- finally { onMutation(); setBusy(false); }
+ if (access?.pending_operation) await retrySettingsOperation(access.pending_operation);
}} />}
{selected.status_error && <div className="callout warn" data-error-code={selected.status_error}><UiIcon name="warning" /><div><strong>{text('暂时无法核实 Agent 状态', 'Agent status is temporarily unavailable')}</strong><p>{text('当前仍显示已发现的 Agent;重新读取成功前不会把未知状态当作已接入。', 'The detected Agent remains visible. Unknown status is not treated as connected until it can be read again.')}</p><button className="btn" type="button" onClick={() => void refresh()}>{text('重新读取', 'Try again')}</button></div></div>}
{executableStatus}
{selectedHasDrift && <div className="callout warn"><UiIcon name="warning" /><div><strong>{text('接入配置已变化', 'Connection settings changed')}</strong><p>{text('HiRoute 不会覆盖已变化的设置。请在“连接详情与恢复”中恢复需要的路由配置。', 'HiRoute will not overwrite changed settings. Restore the required routing configuration under Connection details and recovery.')}</p></div></div>}
- {selectedPending && !selected.codex_access?.pending_operation && <div className="oc-status-row" role="status"><span className="oc-spinner" /><p>{text('路由配置正在应用,完成后会自动更新。', 'Routing settings are being applied and will update automatically.')}</p></div>}
- <section className="detail-section v3-agent-section">
- <div className="detail-section-head"><h3>{text('模型路由', 'Model routing')}</h3><button className="btn btn-quiet" data-agent-facet="model" disabled={busy || selectedPending || !selected.context_id || !mutable} onClick={event => open(selected, 'model', event.currentTarget)}>{modelSelection ? text('调整', 'Edit') : text('启用', 'Enable')}</button>{selected.settings?.restore_point_ref && <button className="btn btn-quiet" disabled={busy || selectedPending || !mutable} onClick={event => void change(selected, 'model', true, event.currentTarget)}>{text('停用', 'Disable')}</button>}</div>
- <p>{modelSelection ? <>{text('当前选择:', 'Current selection: ')}<strong>{modelSelectionSummary}</strong></> : text('为此 Agent 配置固定模型,或通过智能路由自动选择模型。', 'Configure a fixed model for this Agent, or use smart routing to choose a model automatically.')}</p>
- {modelSelection && verificationSurfaces.length > 0 && <div className="agent-surface-results" aria-label={text('当前客户端验证结果', 'Current client verification results')}>
- {verificationSurfaces.map(surface => {
- const revision = selected.settings?.applied_revision;
- const result = selected.settings?.surface_results?.find(item => item.surface === surface && item.applied_revision === revision);
- const state = selected.settings?.state === 'configured' && !selected.status_error && revision != null
- ? result?.state ?? 'not_verified'
- : 'not_verified';
- return <div className="agent-surface-result" key={surface} data-agent-surface={surface}>
- <span>{surfaceName(surface)} · {revision == null ? text('修订待确认', 'Revision unknown') : `r${revision}`}</span>
- <span className={`badge no-dot ${state === 'passed' ? 'good' : state === 'failed' ? 'bad' : 'warn'}`}>{state === 'passed'
- ? text('已验证', 'Verified')
- : state === 'failed'
- ? text('验证未通过', 'Verification failed')
- : text('尚未验证', 'Not verified')}</span>
- </div>;
- })}
- </div>}
+ {qoderRecoveryOperation && <div className="callout warn" role="alert" data-qoder-model-recovery>
+ <UiIcon name="warning" /><div>
+ <strong>{text('模型路由配置尚未完成', 'Model routing configuration is incomplete')}</strong>
+ <p>{text('请先保存自己的编辑,恢复本次操作开始后发生的配置文件改动,再继续原操作。HiRoute 不会强制覆盖文件;任务协作保持独立。', 'Save your edits and undo configuration changes made since this operation started, then resume it. HiRoute will not force an overwrite; task collaboration remains independent.')}</p>
+ <button className="btn" type="button" disabled={busy || Boolean(editor) || !snapshot.trusted_authority} onClick={() => void retrySettingsOperation(qoderRecoveryOperation)}>{text('重新检查并继续原操作', 'Recheck and resume operation')}</button>
+ </div>
+ </div>}
+ {selectedPending && !qoderRecoveryOperation && !selected.codex_access?.pending_operation && <div className="oc-status-row" role="status"><span className="oc-spinner" /><p>{text('路由配置正在应用,完成后会自动更新。', 'Routing settings are being applied and will update automatically.')}</p></div>}
+ {agentSupportsModelRouting(selected.agent_id) && !agentHasNoModelConnection(selected) && <section className="detail-section v3-agent-section">
+ <div className="detail-section-head"><h3>{text('模型路由', 'Model routing')}</h3><button className="btn btn-quiet" data-agent-facet="model" disabled={busy || selectedPending || !selected.context_id || !agentEcosystem(selected.agent_id) || !mutable} onClick={event => open(selected, 'model', event.currentTarget)}>{modelSelection ? text('调整', 'Edit') : text('启用', 'Enable')}</button>{selectedModel?.restore_point_ref && <button className="btn btn-quiet" disabled={busy || selectedPending || !mutable} onClick={event => void change(selected, 'model', true, event.currentTarget)}>{text('停用', 'Disable')}</button>}</div>
+ <p>{modelSelection ? <>{text('当前选择:', 'Current selection: ')}<strong>{selectionSummary}</strong></> : selected.agent_id === 'agent_qoder_default'
+ ? text('添加可在 Qoder 中明确选择的 HiRoute 路由,保留原有模型和默认值。', 'Add HiRoute routes you can explicitly select in Qoder, while keeping native models and defaults.')
+ : text('为此 Agent 配置固定模型,或通过智能路由自动选择模型。', 'Configure a fixed model for this Agent, or use smart routing to choose a model automatically.')}</p>
{modelSelection?.mode === 'claude_launcher' && <p className="field-help">{text('直接启动 claude,使用 Opus、Sonnet、Haiku 原生预设选择已映射路由;其他计划不会自动出现在模型菜单中。若未显式选择当前模型,Claude Default 取决于账号;预设映射不证明 Default 可用,请通过真实调用验证。', 'Start claude normally and use its native Opus, Sonnet, or Haiku preset for mapped routes. Other plans do not automatically appear in the model picker. Without an explicit model selection, Claude Default depends on the account; preset mappings do not prove it works. Verify with a live call.')}</p>}
- </section>
- <section className="detail-section v3-agent-section">
+ {modelSelection?.mode === 'qoder_additional' && <p className="field-help">{text('重新启动 Qoder 后,在模型选择中选用已添加的 HiRoute 路由。原有模型、登录和默认选择保持不变。', 'Restart Qoder and select an added HiRoute route in its model choices. Existing models, sign-in and defaults stay unchanged.')}</p>}
+ </section>}
+ <section className="detail-section v3-agent-section" data-agent-collaboration>
<div className="detail-section-head"><h3>{text('任务路由', 'Task routing')}</h3><button className="btn btn-quiet" data-agent-facet="collaboration" disabled={busy || !selected.context_id || !mutable} onClick={event => open(selected, 'collaboration', event.currentTarget)}>{taskSelection ? text('调整', 'Edit') : text('启用', 'Enable')}</button></div>
+ {selected.agent_id === 'agent_qoder_default' && <div data-qoder-collaboration>
+ <p>{text('使用 Qoder 原有模型和登录配置,通过任务协作使用 HiRoute 计划。需要登录时,请在终端正常启动 Qoder CLI 并完成登录后重试。', 'Keep your Qoder models and sign-in configuration, and use HiRoute plans through task collaboration. If sign-in is needed, start Qoder CLI normally in a terminal, sign in, and retry.')}</p>
+ </div>}
<p>{taskSelection?.trigger_mode === 'delegate_by_default'
? text('由此 Agent 判断何时将任务交给执行 Agent;你仍可明确要求只回答、不执行。', 'This Agent decides when to delegate work to an execution Agent; you can still explicitly ask it to answer without execution.')
: taskSelection
@@ -953,75 +532,21 @@ export function Agents({
: text('让此 Agent 将任务交给合适的执行 Agent,并获取结果。', 'Let this Agent delegate work to a suitable execution Agent and retrieve the results.')}</p>
<p className="field-help">{text('启用后,可在对话中说:“使用 HiRoute,将当前任务委派给【路由名称】执行。”路由名称见“智能路由”,也可让 Agent 选择合适的路由。', 'After enabling, ask in conversation: “Use HiRoute to delegate this task to [route name].” Find route names under Smart routing, or ask the Agent to choose a suitable route.')}</p>
</section>
- <Disclosure className="native-details" label={text('连接详情与恢复', 'Connection details and recovery')} language={language}><dl>{selected.version && <div><dt>{text('版本', 'Version')}</dt><dd>{selected.version}</dd></div>}{selected.settings?.state === 'configured' && modelSelection && <div><dt>{text('本机接入令牌', 'Local access token')}</dt><dd><input className="input" type="password" value="••••••••••••••••" readOnly aria-label={text('当前令牌已隐藏', 'Current token hidden')} /></dd></div>}</dl>{selected.settings?.restore_point_ref && selected.agent_id === 'agent_codex_default' && selected.codex_access?.selected_mode !== 'profile' && <label className="field-label">{text('恢复时选择原生模型(可选)', 'Native model on restore (optional)')}<input list="codex-native-restore-models" value={restoreNativeModel} onChange={event => { setRestoreNativeModel(event.target.value); setPreview(null); }} placeholder={text('保留原设置', 'Keep original setting')} disabled={busy || !mutable} /><datalist id="codex-native-restore-models">{nativeRestoreOptions.map(model => <option key={model.client_model_id} value={model.client_model_id}>{model.display_name}</option>)}</datalist></label>}{selected.settings?.state === 'configured' && modelSelection && <div className="actions" data-agent-token-controls><button className="btn" disabled={busy || !mutable} onClick={() => { setTokenEditing(true); setTokenDraft(''); setActionError(''); }}>{text('修改令牌', 'Change token')}</button><button className="btn" disabled={busy || !mutable} onClick={event => void changeToken(selected, true, event.currentTarget)}>{text('重新生成', 'Regenerate')}</button></div>}{tokenEditing && selected.settings?.state === 'configured' && modelSelection && <form className="agent-token-form" onSubmit={event => { event.preventDefault(); void changeToken(selected, false, (event.nativeEvent as SubmitEvent).submitter as HTMLElement | null); }}><label className="field"><span className="field-label">{text('新令牌', 'New token')}</span><input className="input" type="password" autoComplete="new-password" value={tokenDraft} onChange={event => setTokenDraft(event.target.value)} minLength={16} maxLength={128} pattern="[A-Za-z0-9._~\\-]{16,128}" required disabled={busy} /><span className="field-help">{text('16–128 位英文字母、数字及 . _ ~ -;保存后原令牌立即失效,无需重新接入。', 'Use 16–128 letters, numbers, or . _ ~ -. The old token stops working after save; reconnecting is unnecessary.')}</span></label><div className="actions"><button className="btn btn-primary" type="submit" disabled={busy || !mutable}>{text('保存令牌', 'Save token')}</button><button className="btn" type="button" disabled={busy} onClick={() => { setTokenEditing(false); setTokenDraft(''); }}>{text('取消', 'Cancel')}</button></div></form>}<div className="actions">{selectedCollaboration?.restore_point_ref && <button className="btn" disabled={busy || !mutable} onClick={event => void change(selected, 'collaboration', true, event.currentTarget)}>{text('停用任务路由', 'Disable task routing')}</button>}</div></Disclosure>
+ <Disclosure className="native-details" label={text('连接详情与恢复', 'Connection details and recovery')} language={language}><dl>{selected.version && <div><dt>{text('版本', 'Version')}</dt><dd>{selected.version}</dd></div>}{selectedModel?.state === 'configured' && modelSelection && <div><dt>{text('本机接入令牌', 'Local access token')}</dt><dd><input className="input" type="password" value="••••••••••••••••" readOnly aria-label={text('当前令牌已隐藏', 'Current token hidden')} /></dd></div>}</dl>{selectedModel?.restore_point_ref && selected.agent_id === 'agent_codex_default' && selected.codex_access?.selected_mode !== 'profile' && <label className="field-label">{text('恢复时选择原生模型(可选)', 'Native model on restore (optional)')}<input list="codex-native-restore-models" value={restoreNativeModel} onChange={event => { setRestoreNativeModel(event.target.value); setPreview(null); }} placeholder={text('保留原设置', 'Keep original setting')} disabled={busy || !mutable} /><datalist id="codex-native-restore-models">{nativeRestoreOptions.map(model => <option key={model.client_model_id} value={model.client_model_id}>{model.display_name}</option>)}</datalist></label>}{selectedModel?.state === 'configured' && modelSelection && <div className="actions" data-agent-token-controls><button className="btn" disabled={busy || !mutable} onClick={() => { setTokenEditing(true); setTokenDraft(''); setActionError(''); }}>{text('修改令牌', 'Change token')}</button><button className="btn" disabled={busy || !mutable} onClick={event => void changeToken(selected, true, event.currentTarget)}>{text('重新生成', 'Regenerate')}</button></div>}{tokenEditing && selectedModel?.state === 'configured' && modelSelection && <form className="agent-token-form" onSubmit={event => { event.preventDefault(); void changeToken(selected, false, (event.nativeEvent as SubmitEvent).submitter as HTMLElement | null); }}><label className="field"><span className="field-label">{text('新令牌', 'New token')}</span><input className="input" type="password" autoComplete="new-password" value={tokenDraft} onChange={event => setTokenDraft(event.target.value)} minLength={16} maxLength={128} pattern="[A-Za-z0-9._~\\-]{16,128}" required disabled={busy} /><span className="field-help">{text('16–128 位英文字母、数字及 . _ ~ -;保存后原令牌立即失效,无需重新接入。', 'Use 16–128 letters, numbers, or . _ ~ -. The old token stops working after save; reconnecting is unnecessary.')}</span></label><div className="actions"><button className="btn btn-primary" type="submit" disabled={busy || !mutable}>{text('保存令牌', 'Save token')}</button><button className="btn" type="button" disabled={busy} onClick={() => { setTokenEditing(false); setTokenDraft(''); }}>{text('取消', 'Cancel')}</button></div></form>}<div className="actions">{selectedCollaboration?.restore_point_ref && <button className="btn" disabled={busy || !mutable} onClick={event => void change(selected, 'collaboration', true, event.currentTarget)}>{text('停用任务路由', 'Disable task routing')}</button>}</div></Disclosure>
{!editor && loadError && <div className="callout warn agent-feedback agent-inline-feedback" role="alert" data-error-code={loadError}><UiIcon name="warning" /><div><strong>{text('状态刷新失败', 'Status refresh failed')}</strong><p>{text('当前仍显示上次读取的结果。', 'The last loaded result is still shown.')}</p><button className="btn" type="button" onClick={() => void refresh()}>{text('重试', 'Retry')}</button></div></div>}
{!editor && blockedPreview}
{!editor && notice && <div className="toast-stack" aria-live="polite"><div className="toast" role="status"><UiIcon name="check" /><span>{notice}</span></div></div>}
- {!editor && actionError && <div className="callout bad agent-feedback agent-inline-feedback" role="alert" data-error-code={actionError}><UiIcon name="warning" /><span>{agentActionErrorMessage(actionError, language)}</span></div>}
+ {!editor && actionError && <div className="callout bad agent-feedback agent-inline-feedback" role="alert" data-error-code={actionError}><UiIcon name="warning" /><span>{actionErrorHint ?? agentActionErrorMessage(actionError, language)}</span></div>}
{!selected.context_id && <div className="callout"><UiIcon name="info" /><span>{text('此 Agent 的设置入口尚不可用。', 'Settings for this Agent are not available yet.')}</span></div>}
{editor?.context === selected.context_id && selected.context_id && <Dialog open title={`${agentName(selected)} · ${editor.facet === 'model' ? text('模型路由', 'Model routing') : text('任务路由', 'Task routing')}`} closeLabel={text('关闭配置', 'Close settings')} closeDisabled={busy} onClose={() => { if (!busy) close(); }} footer={<><button className="btn" type="button" disabled={busy} onClick={close}>{text('取消', 'Cancel')}</button><button className="btn btn-primary" type="submit" form="hr-agent-settings" disabled={busy || !mutable || Boolean(formInvalid)}>{busy ? busyText || text('正在保存…', 'Saving…') : submitLabel}</button></>}>
<form id="hr-agent-settings" className="agent-form" ref={node => { firstField.current = node?.querySelector<HTMLElement>('input:not([disabled]), select:not([disabled]), button:not([disabled])') ?? null; }} onSubmit={event => { event.preventDefault(); void change(selected, editor.facet, false, (event.nativeEvent as SubmitEvent).submitter as HTMLElement | null); }}>
<fieldset disabled={busy || !mutable}>
{editor.facet === 'model' && <p className="field-help" data-agent-service-responsibility>{text('使用路由时请保持 HiRoute 运行。启用不会自动设置开机启动。', 'Keep HiRoute running when using routing. Enabling does not set up automatic startup.')}</p>}
- {editor.facet === 'model' && selected.agent_id === 'agent_codex_default' && <div className="worker-choices">
- <p className="field-help" data-codex-shared-scope>{activeCodexMode === 'profile'
- ? text('按需使用 · 仅 Codex CLI。启用后将启动命令粘贴到终端,开启新会话。普通 Codex 和 Desktop 保持原配置。', 'On demand · Codex CLI only. After enabling, paste the launch command into a terminal to start a new session. Ordinary Codex and Desktop keep their settings.')
- : text('设为默认 · 修改同一配置目录下 Codex CLI 和 Desktop 的模型接入。保存后重新启动对应客户端即可生效。', 'Use by default · changes model access for Codex CLI and Desktop sharing this directory. Restart the client after saving to apply the settings.')}</p>
- <fieldset><legend className="field-label">{text('允许的智能路由', 'Allowed smart routes')}</legend>
- {enabledPlans.length === 1 && creatingModelConnection && <p className="field-help">{text('唯一可用路由已选为默认,可直接启用。', 'The only available route is selected as the default. Enable to continue.')}</p>}
- {enabledPlans.map(plan => <label className="check-row agent-route-choice" data-agent-plan-id={plan.agent_plan_id} key={plan.agent_plan_id}><input type="checkbox" checked={editorValues.allowedPlanIds.includes(plan.agent_plan_id)} onChange={() => toggleAllowedPlan(plan.agent_plan_id)} /><div><strong>{plan.desired.display_name}</strong></div></label>)}
- {!enabledPlans.length && <div className="callout"><UiIcon name="route" /><div><span>{text('先创建并启用一条智能路由。', 'Create and enable a smart route first.')}</span></div>{onCreatePlan && <button className="btn" type="button" onClick={createPlanFromEditor}>{text('创建路由', 'Create route')}</button>}</div>}
- {editorValues.allowedPlanIds.filter(id => !planEnabled(id)).map(id => <label className="check-row agent-route-choice" key={id}><input type="checkbox" checked onChange={() => toggleAllowedPlan(id)} /><span>{planName(id) ?? id} · {text('当前不可用', 'Currently unavailable')}</span></label>)}
- {editorValues.allowedPlanIds.some(id => !planEnabled(id)) && <span className="oc-inline-error">{text('已有路由已停用或不存在,请取消选择后再保存。', 'A previously allowed route is disabled or missing. Remove it before saving.')}</span>}
- </fieldset>
- {showCodexDefault && <>
- <label className="field"><span className="field-label">{text('默认选择', 'Default selection')}</span><select className="select" data-agent-default value={defaultChoiceValue(editorValues.defaultChoice)} onChange={event => selectDefaultChoice(event.target.value)}>{editorValues.nativeModelMode === 'preserve_available' && <option value="native">{text('使用 Codex 当前默认模型名称', 'Use the current Codex default model name')}</option>}{editorValues.fixedModels.map(model => <option key={model.client_model_id} value={`fixed:${model.client_model_id}`}>{model.client_model_id}</option>)}{editorValues.allowedPlanIds.filter(planEnabled).map(id => <option key={id} value={`plan:${id}`}>{planName(id)}</option>)}</select><span className="field-help">{defaultChoice.kind === 'preserve_native'
- ? text('保留当前默认模型名称;请求仍经过 HiRoute。该名称须对应已勾选的路由或已绑定的固定模型。', 'Keep the current default model name; requests still pass through HiRoute. The name must match an enabled route or a bound fixed model.')
- : defaultChoice.kind === 'plan'
- ? editorValues.nativeModelMode === 'preserve_available' ? text('Codex 将默认使用所选智能路由;已证明可用的原生模型名称会继续自动保留。', 'Codex will use the selected smart route by default; proven native model names remain available automatically.') : text('Codex 将默认使用所选智能路由。', 'Codex will use the selected smart route by default.')
- : text('Codex 将默认使用所选固定模型来源。', 'Codex will use the selected fixed model source by default.')}</span>{editorValues.nativeModelMode === 'preserve_available' && defaultChoice.kind === 'preserve_native' && !codexDefaultValid && <span className="oc-inline-error">{text('当前无法读取 Codex 原生默认模型;请修复当前配置后重试。', 'The native Codex default model cannot be read. Repair the current configuration and try again.')}</span>}</label>
- </>}
- {fixedModelRows.length > 0 && <fieldset data-agent-fixed-models><legend className="field-label">{text('已配置的原生模型固定来源', 'Configured native model sources')}</legend>
- {fixedModelRows.map(model => {
- const fixed = editorValues.fixedModels.find(item => item.client_model_id === model.client_model_id);
- const source = fixed ? model.source_options.find(option => option.binding_id === fixed.candidate.binding_id) : undefined;
- return <div className="candidate-row" key={model.client_model_id} data-client-model-id={model.client_model_id}>
- <div><strong>{model.display_name}</strong><small><code>{model.client_model_id}</code></small>{protectedNativeModelIds.has(model.client_model_id) ? <span className="field-help" data-protected-native-model>{text('原生模型绑定由 HiRoute 自动保留;调整路由时无需重新选择。停用模型路由后可重新配置原生来源。', 'HiRoute keeps this native model binding automatically when routes are edited. Disable model routing to change its native source.')}</span> : null}<label className="field"><span className="field-label">{text('固定来源与账号范围', 'Fixed source and account scope')}</span><select className="select" value={fixed?.candidate.binding_id ?? ''} onChange={event => selectFixedSource(model, event.target.value)} disabled={protectedNativeModelIds.has(model.client_model_id)}>{!protectedNativeModelIds.has(model.client_model_id) && <option value="">{text('不通过 HiRoute 固定此名称', 'Do not fix this name through HiRoute')}</option>}{fixed && !source && <option value={fixed.candidate.binding_id} disabled>{protectedNativeModelIds.has(model.client_model_id) ? text('原有绑定已保留,当前列表未显示来源', 'Binding retained; source is not in the current list') : text('原有来源当前不可用', 'Previous source unavailable')}</option>}{model.source_options.map(option => <option key={option.binding_id} value={option.binding_id} disabled={option.state !== 'ready'}>{option.source_label} · {option.account_scope_ref} · {sourceStateLabel(option.state)}</option>)}</select></label>{source && <span className="field-help">{sourceStateLabel(source.state)} · {text('账号范围摘要 ', 'Account scope digest ')}<code>{source.account_scope_digest.slice(0, 18)}…</code></span>}{fixed && source?.state === 'ready' && !protectedNativeModelIds.has(model.client_model_id) && fixedReasoningControl(model, fixed, source)}{!model.source_options.length && !protectedNativeModelIds.has(model.client_model_id) && <span className="field-help">{text('此原生名称尚无独立来源/账号绑定;元数据不会被当作可调用证明。', 'This native name has no independent source/account binding; metadata is not treated as callable proof.')}</span>}</div>
- </div>;
- })}
- </fieldset>}
- <Disclosure label={text('高级设置', 'Advanced settings')} language={language}>
- {selected.codex_access && <CodexAccessSettings access={selected.codex_access} mode={activeCodexMode} language={language} disabled={busy || !mutable} onMode={mode => { setCodexMode(mode); setPreview(null); setActionError(''); }} />}
- <fieldset data-agent-native-mode><legend className="field-label">{text('Codex 可用模型', 'Models available in Codex')}</legend>
- <label className="check-row"><input type="radio" name="codex-native-mode" value="hiroute_only" checked={editorValues.nativeModelMode === 'hiroute_only'} onChange={() => selectNativeModelMode('hiroute_only')} /><div><strong>{text('只使用已配置的 HiRoute 模型', 'Use configured HiRoute models only')}</strong><small>{text('无需接入原 Codex 账号;关闭时恢复原配置。', 'No original Codex account connection required; disabling restores the original configuration.')}</small></div></label>
- <label className="check-row"><input type="radio" name="codex-native-mode" value="preserve_available" checked={editorValues.nativeModelMode === 'preserve_available'} onChange={() => selectNativeModelMode('preserve_available')} /><div><strong>{text('同时保留 Codex 原有模型', 'Also keep native Codex models')}</strong><small>{text('先在“模型”接入原订阅账号或 API 来源;只保留能证明同账号可调用的模型。缓存目录不是账号权限。', 'Connect the original subscription account or API source under Models first. Only proven same-account models are kept; the cache is not entitlement.')}</small></div></label>
- </fieldset>
- <div className="callout" data-codex-shared-scope><UiIcon name="info" /><div><strong>{activeCodexMode === 'profile' ? text('独立 CLI 配置', 'Separate CLI configuration') : text('一套共享配置', 'One shared configuration')}</strong><p>{activeCodexMode === 'profile'
- ? text('本次保存只作用于指定 profile 的 Codex CLI。Desktop 继续使用原来的默认配置。', 'This save applies only to Codex CLI using the selected profile. Desktop keeps its original default configuration.')
- : text('保存一次即作用于共享此配置作用域与 CODEX_HOME 的 Codex CLI 和 Desktop。', 'One save applies to Codex CLI and Desktop when they share this configuration scope and CODEX_HOME.')}</p>{codexSurfaces.map(({surface, detected, applicable}) => {
- return <span className="field-help" key={surface} data-agent-surface-fact={surface} data-agent-surface-detected={detected ? 'true' : 'false'} data-agent-surface-applicable={applicable ? 'true' : 'false'}>{surfaceName(surface)} · {detected ? text('当前已发现可执行入口', 'currently detected as runnable') : text('当前未发现可执行入口', 'not currently detected as runnable')} · {applicable ? text('适用当前模式', 'applies to this mode') : text('不适用当前模式', 'does not apply to this mode')}</span>;
- })}</div></div>
- <p className="field-help" data-agent-plan-compatibility>{text('保存时会核对路由的 Codex Responses 能力。不同入口的会话历史可能不同。', 'Saving checks the routes’ Codex Responses capabilities. History may differ between entry points.')}</p>
- </Disclosure>
- {modelFormInvalid && <span className="oc-inline-error">{text('请选择可用路由或固定模型,并修正不可用项。', 'Choose an available route or fixed model and resolve unavailable selections.')}</span>}
- </div>}
- {editor.facet === 'model' && selected.agent_id === 'agent_claude_default' && <div className="worker-choices">
- <label className="field"><span className="field-label">{claudeSharedPlan === null ? text('模型档位路由', 'Preset routes') : text('共用一条路由', 'Use one route for all presets')}</span><select className="select" aria-label={text('Claude Code 路由', 'Claude Code route')} value={claudeSharedPlan ?? ''} onChange={event => { setEditorValues(value => ({ ...value, claudePresets: sharedClaudePlan(event.target.value) })); setPreview(null); setActionError(''); }}><option value="" disabled>{claudeSharedPlan === null ? text('已分别配置模型档位', 'Presets configured separately') : text('选择路由', 'Choose a route')}</option>{claudeSharedPlan && !planEnabled(claudeSharedPlan) && <option value={claudeSharedPlan} disabled>{text('原有路由当前不可用', 'Previous route unavailable')}</option>}{enabledPlans.map(plan => <option key={plan.agent_plan_id} value={plan.agent_plan_id}>{plan.desired.display_name}</option>)}</select><span className="field-help">{claudeSharedPlan === null
- ? text('当前按档位分别配置。选择同一条路由可统一 Opus、Sonnet、Haiku;不会修改 Claude 当前默认模型。', 'Presets are configured separately. Choose one route to unify Opus, Sonnet and Haiku; the current Claude default model is unchanged.')
- : text('应用于 Opus、Sonnet、Haiku;高级设置可分别配置。不会修改 Claude 当前默认模型。', 'Applies to Opus, Sonnet and Haiku; configure them separately under Advanced settings. The current Claude default model is unchanged.')}</span></label>
- {editorValues.fixedModels.length > 0 && <p className="field-help">{text('保留已有固定模型:', 'Existing fixed models retained: ')}{editorValues.fixedModels.map(model => model.client_model_id).join(' · ')}</p>}
- <p className="field-help" data-agent-activation>{text('保存后,重新启动 Claude Code 即可加载配置。', 'Restart Claude Code after saving to load the settings.')}</p>
- <Disclosure label={text('高级设置', 'Advanced settings')} language={language} defaultOpen={claudeSharedPlan === null || claudePlanIds.some(id => !planEnabled(id))}>
- <p className="field-help">{text('普通 claude 入口使用这些映射。账号 Default 仍需真实调用验证,可显式选择已映射的模型档位。', 'The ordinary claude entry uses these mappings. Account Default needs a live call to verify; explicitly choose a mapped preset.')}</p>
- {(['opus', 'sonnet', 'haiku'] as const).map(preset => {
- const choice = editorValues.claudePresets[preset];
- const selectedPlan = choice.kind === 'plan' ? choice.plan_id : '';
- return <label className="field" key={preset}><span className="field-label">{preset[0].toUpperCase() + preset.slice(1)}</span><select className="select" value={selectedPlan} onChange={event => selectClaudePreset(preset, event.target.value)}><option value="">{text('保留原生值或缺省关系', 'Preserve native value or default relationship')}</option>{selectedPlan && !planEnabled(selectedPlan) && <option value={selectedPlan} disabled>{text('原有路由当前不可用', 'Previous route unavailable')}</option>}{enabledPlans.map(plan => <option key={plan.agent_plan_id} value={plan.agent_plan_id}>{plan.desired.display_name}</option>)}</select></label>;
- })}
- </Disclosure>
- {modelFormInvalid && <span className="oc-inline-error">{text('至少将一个预设映射到可用智能路由,或保留已有固定模型。', 'Map at least one preset to an enabled smart route, or retain an existing fixed model.')}</span>}
- {!enabledPlans.length && <div className="callout"><UiIcon name="route" /><div><span>{text('先创建并启用一条智能路由。', 'Create and enable a smart route first.')}</span></div>{onCreatePlan && <button className="btn" type="button" onClick={createPlanFromEditor}>{text('创建路由', 'Create route')}</button>}</div>}
- </div>}
+ {editor.facet === 'model' && <AgentModelEditor agent={selected} values={editorValues} plans={plans} language={language} disabled={busy || !mutable} invalid={modelFormInvalid} codexMode={activeCodexMode}
+ onCodexMode={mode => { setCodexMode(mode); setPreview(null); setActionError(''); }}
+ onChange={setEditorValues}
+ onEdited={(clearNotice = true) => { setPreview(null); setActionError(''); if (clearNotice) setNotice(''); }}
+ onCreatePlan={onCreatePlan ? createPlanFromEditor : undefined} />}
{editor.facet === 'collaboration' && <fieldset className="worker-choices"><legend className="field-label">{text('委派时机', 'When to delegate')}</legend><label className="check-row"><input type="radio" name="agent-collaboration-trigger" value="explicit" checked={editorValues.triggerMode === 'explicit'} onChange={() => setTriggerMode('explicit')} /><div><strong>{text('仅在明确要求时', 'Only when explicitly requested')}</strong><span>{text('只有当你要求执行、委派或交给 Worker 时,Agent 才会启动任务。', 'The Agent starts a task only when you ask it to execute, delegate, or hand work to a Worker.')}</span></div></label><label className="check-row"><input type="radio" name="agent-collaboration-trigger" value="delegate_by_default" checked={editorValues.triggerMode === 'delegate_by_default'} onChange={() => setTriggerMode('delegate_by_default')} /><div><strong>{text('默认由 Agent 判断', 'Let the Agent decide by default')}</strong><span>{text('Agent 可以主动委派适合执行的任务;明确要求只回答时不会启动任务。', 'The Agent may proactively delegate suitable work, but will not start a task when you explicitly ask for an answer only.')}</span></div></label><p className="field-help">{text('可委派的任务路由在“智能路由”中管理。', 'Manage routes available for task delegation under Smart routing.')}</p></fieldset>}
{!selectionKnown && <div className="callout warn" role="alert"><UiIcon name="warning" /><span>{text('当前配置状态无法核实,不能覆盖保存。请刷新或处理配置变化。', 'The current setting cannot be verified. Refresh or resolve configuration changes before saving.')}</span></div>}
</fieldset>
@@ -1029,7 +554,7 @@ export function Agents({
{blockedPreview}
{executableStatus}
{notice && <div className="callout agent-feedback" role="status"><UiIcon name="info" /><span>{notice}</span></div>}
- {actionError && <div className="callout bad agent-feedback" role="alert" data-error-code={actionError}><UiIcon name="warning" /><span>{agentActionErrorMessage(actionError, language)}</span></div>}
+ {actionError && <div className="callout bad agent-feedback" role="alert" data-error-code={actionError}><UiIcon name="warning" /><span>{actionErrorHint ?? agentActionErrorMessage(actionError, language)}</span></div>}
</Dialog>}
</div>}
</section>
diff --git a/apps/desktop/src/features/WorkerDependencies.tsx b/apps/desktop/src/features/WorkerDependencies.tsx
index 2f324950..72265111 100644
--- a/apps/desktop/src/features/WorkerDependencies.tsx
+++ b/apps/desktop/src/features/WorkerDependencies.tsx
@@ -7,6 +7,8 @@ import {
selectedWorkerDependencies,
workerDependencyRevision,
workerDependencySelectionMatches,
+ workerDependencyComponents,
+ workerDependencySelectionComplete,
workerDependencySelectionState,
workerEnvelopeData,
type WorkerDependenciesView,
@@ -51,7 +53,8 @@ export function WorkerDependencies({
}) {
const zh = language === 'zh';
const text = (cn: string, en: string) => zh ? cn : en;
- const name = harness === 'codex_cli' ? 'Codex CLI' : 'Claude Code';
+ const name = { codex_cli: 'Codex CLI', claude_code: 'Claude Code', qoder_cli: 'Qoder CLI' }[harness];
+ const components = workerDependencyComponents(harness);
const [view, setView] = useState<WorkerDependenciesView | null>(null);
const [selection, setSelection] = useState<WorkerDependencySelectionRequest | null>(null);
const [refreshing, setRefreshing] = useState(false);
@@ -84,7 +87,9 @@ export function WorkerDependencies({
function errorMessage(cause: unknown) {
const code = failureCode(cause);
if (code.includes('MISSING')) return text('所选安装缺少文件,请重新检测或修正路径。', 'The selected installation is missing files. Detect again or correct the paths.');
- if (code.includes('INVALID')) return text('所选路径不是可用的程序或连接组件。', 'A selected path is not a usable executable or adapter.');
+ if (code.includes('INVALID')) return harness === 'qoder_cli'
+ ? text('所选路径不是可用的 Qoder CLI,请重新检测或修正路径。', 'The selected path is not a usable Qoder CLI. Detect again or correct the path.')
+ : text('所选路径不是可用的程序或连接组件。', 'A selected path is not a usable executable or adapter.');
if (code.includes('EXPIRED')) return text('本次保存已过期,请重新尝试。', 'This save expired. Try again.');
if (code.includes('STALE') || code.includes('CONFLICT')) return text('安装选择已经变化,请重新检测后确认。', 'The installation selection changed. Detect and confirm again.');
if (code.includes('AUTHORITY') || code.includes('DENIED')) return text('当前连接只能查看,不能修改本机安装选择。', 'The current connection can view but cannot change the local installation selection.');
@@ -119,9 +124,8 @@ export function WorkerDependencies({
function edit(patch: Partial<WorkerDependencySelectionRequest>) {
setSelection(current => ({
harness,
- adapter_path: '',
cli_path: '',
- node_path: null,
+ ...(harness === 'qoder_cli' ? {} : { adapter_path: '', node_path: null }),
expected_selection_revision: view ? workerDependencyRevision(view, harness) : 0,
...current,
...patch,
@@ -132,12 +136,15 @@ export function WorkerDependencies({
}
async function saveSelection() {
- if (!selection || !selection.cli_path || !selection.adapter_path || submitting) return;
+ if (!selection || !workerDependencySelectionComplete(selection) || submitting) return;
setSubmitting(true);
setError('');
setNotice('');
try {
- const prepared = await invoke<Confirmation>('worker_dependencies_select_prepare', { input: selection });
+ const input = harness === 'qoder_cli'
+ ? { harness, cli_path: selection.cli_path, expected_selection_revision: selection.expected_selection_revision }
+ : selection;
+ const prepared = await invoke<Confirmation>('worker_dependencies_select_prepare', { input });
if (!mounted.current) {
await invoke('worker_dependencies_select_cancel', {
input: { confirmation_id: prepared.confirmation_id },
@@ -174,6 +181,16 @@ export function WorkerDependencies({
}
}
+ async function openInstallationGuide(event: React.MouseEvent<HTMLAnchorElement>) {
+ if (!("__TAURI_INTERNALS__" in window)) return;
+ event.preventDefault();
+ try {
+ await invoke('open_external_url', { url: event.currentTarget.href });
+ } catch {
+ setError(text('无法打开官方安装说明,请手动打开链接;已填写的路径会保留。', 'Could not open the official installation guide. Open the link manually; your paths are retained.'));
+ }
+ }
+
const state = view ? workerDependencySelectionState(view, harness) : null;
const savedSelection = view ? selectedWorkerDependencies(view, harness) : null;
const replacingSelection = Boolean(view && selection && savedSelection
@@ -201,7 +218,13 @@ export function WorkerDependencies({
{state === 'configured' && <span className="badge good no-dot">{text('已配置', 'Configured')}</span>}
</div>
- {!view && <div className="option-panel"><div className="option-row"><div><strong>{text('检测本机安装', 'Detect local installation')}</strong><span>{text(`查找 ${name}、连接组件和必要的 Node.js。`, `Find ${name}, its adapter, and Node.js when required.`)}</span></div><button className="btn btn-primary" type="button" disabled={refreshing} onClick={() => void discover()}>{refreshing ? text('正在检测…', 'Detecting…') : text('一键检测', 'Detect')}</button></div></div>}
+ {harness === 'qoder_cli' && <p className="field-help" data-qoder-installation-guide>
+ {text('选择已安装的 Qoder CLI(qoder 或 qodercli)。需要登录时,请在终端正常启动该 CLI 并完成登录,再返回使用。', 'Select your installed Qoder CLI (qoder or qodercli). When sign-in is needed, start that CLI normally in a terminal and sign in, then return here.')} {' '}
+ <a href="https://docs.qoder.com/cli/installation" target="_blank" rel="noreferrer" onClick={event => void openInstallationGuide(event)}>{text('官方安装与升级说明', 'Official installation and upgrade guide')}</a>
+ </p>}
+ {!view && <div className="option-panel"><div className="option-row"><div><strong>{text('检测本机安装', 'Detect local installation')}</strong><span>{harness === 'qoder_cli'
+ ? text('查找当前环境中的 Qoder CLI。', 'Find Qoder CLI in the current environment.')
+ : text(`查找 ${name}、连接组件和必要的 Node.js。`, `Find ${name}, its adapter, and Node.js when required.`)}</span></div><button className="btn btn-primary" type="button" disabled={refreshing} onClick={() => void discover()}>{refreshing ? text('正在检测…', 'Detecting…') : text('一键检测', 'Detect')}</button></div></div>}
{view && <div className={`callout ${state === 'configured' ? 'good' : state === 'found' ? '' : 'warn'}`}>
<UiIcon name={state === 'incomplete' ? 'warning' : 'check'} />
@@ -217,15 +240,15 @@ export function WorkerDependencies({
</div>
</div>}
- {view && state === 'incomplete' && view.install_hints.filter(hint => hint.harness === harness).map((hint, index) => <div className="option-row" key={`${hint.component}:${hint.reason_code}:${index}`}><div><strong>{text(`需要 ${componentName(hint.component)}`, `${componentName(hint.component)} required`)}</strong><span>{hint.reason_code === 'worker.dependencies.scan_incomplete' ? text('本次检测未能完整扫描,请重新检测。', 'The scan was incomplete. Detect again.') : text('当前没有找到可用路径。', 'No usable path was found.')}</span></div>{hint.command && <button className="btn" type="button" onClick={() => void copyCommand(hint.command!)}>{text('复制安装命令', 'Copy install command')}</button>}</div>)}
+ {view && state === 'incomplete' && view.install_hints.filter(hint => hint.harness === harness && components.includes(hint.component)).map((hint, index) => <div className="option-row" key={`${hint.component}:${hint.reason_code}:${index}`}><div><strong>{text(`需要 ${componentName(hint.component)}`, `${componentName(hint.component)} required`)}</strong><span>{hint.reason_code === 'worker.dependencies.scan_incomplete' ? text('本次检测未能完整扫描,请重新检测。', 'The scan was incomplete. Detect again.') : text('当前没有找到可用路径。', 'No usable path was found.')}</span></div>{hint.command && <button className="btn" type="button" onClick={() => void copyCommand(hint.command!)}>{text('复制安装命令', 'Copy install command')}</button>}</div>)}
{view && <div className="editor-actions worker-dependency-actions">
<button className="btn" type="button" disabled={refreshing || submitting} onClick={() => void discover()}>{refreshing ? text('正在检测…', 'Detecting…') : text('重新检测', 'Detect again')}</button>
- {(!savedSelection || replacingSelection) && <button className="btn btn-primary" type="button" disabled={!selection?.cli_path || !selection.adapter_path || refreshing || submitting} onClick={() => void saveSelection()}>{submitting ? text('正在保存…', 'Saving…') : savedSelection ? text('更换安装', 'Replace installation') : text('使用此安装', 'Use this installation')}</button>}
+ {(!savedSelection || replacingSelection) && <button className="btn btn-primary" type="button" disabled={!workerDependencySelectionComplete(selection) || refreshing || submitting} onClick={() => void saveSelection()}>{submitting ? text('正在保存…', 'Saving…') : savedSelection ? text('更换安装', 'Replace installation') : text('使用此安装', 'Use this installation')}</button>}
<button className="btn btn-quiet" type="button" onClick={() => setAdvanced(value => !value)}>{advanced ? text('收起高级设置', 'Hide Advanced') : savedSelection ? text('更换或高级设置', 'Replace or Advanced') : text('高级设置', 'Advanced')}</button>
</div>}
- {advanced && view && <Disclosure className="native-details" defaultOpen label={text('安装路径与候选', 'Installation paths and candidates')} language={language}>{(['cli', 'adapter', 'node'] as WorkerDependencyComponent[]).map(component => <div className="field" key={component}>
+ {advanced && view && <Disclosure className="native-details" defaultOpen label={text('安装路径与候选', 'Installation paths and candidates')} language={language}>{components.map(component => <div className="field" key={component}>
<label className="field-label" htmlFor={`worker-${harness}-${component}`}>{componentName(component)} {component === 'node' && <span className="muted">{text('按连接组件需要选填', 'Optional when the adapter does not require it')}</span>}</label>
<input id={`worker-${harness}-${component}`} className="input" value={inputValue(component)} placeholder={text('输入绝对路径', 'Enter an absolute path')} onChange={event => selectCandidate(component, event.target.value)} />
{!!candidates(component).length && <div className="native-list">{candidates(component).map(candidate => <button className={`list-row${inputValue(component) === candidate.path ? ' active' : ''}`} type="button" key={`${component}:${candidate.path}`} onClick={() => selectCandidate(component, candidate.path)}><span className="row-main"><span className="row-title">{candidate.path}</span><span className="row-meta">{candidate.source} · {candidate.state}</span></span>{inputValue(component) === candidate.path && <UiIcon name="check" />}</button>)}</div>}
diff --git a/apps/desktop/src/features/agents/AgentModelEditor.tsx b/apps/desktop/src/features/agents/AgentModelEditor.tsx
new file mode 100644
index 00000000..9ac7d362
--- /dev/null
+++ b/apps/desktop/src/features/agents/AgentModelEditor.tsx
@@ -0,0 +1,55 @@
+import React from 'react';
+import type { Dispatch, SetStateAction } from 'react';
+import type { Plan } from '../../plan-editor';
+import type { Agent, AgentModelSelection } from './types';
+import type { AgentEditorValues } from './editor-state';
+import { commonClaudePlan } from './editor-state';
+import { agentEcosystem } from './ecosystems';
+import { CodexModelEditor } from './CodexModelEditor';
+import { ClaudeModelEditor } from './ClaudeModelEditor';
+import { QoderModelEditor } from './QoderModelEditor';
+
+export type AgentModelEditorProps = {
+ agent: Agent;
+ values: AgentEditorValues;
+ plans: Plan[];
+ language: 'zh' | 'en';
+ disabled: boolean;
+ invalid: boolean;
+ codexMode: 'profile' | 'root';
+ onCodexMode: (mode: 'profile' | 'root') => void;
+ onChange: Dispatch<SetStateAction<AgentEditorValues>>;
+ onEdited: (clearNotice?: boolean) => void;
+ onCreatePlan?: () => void;
+};
+
+export function AgentModelEditor(props: AgentModelEditorProps) {
+ switch (agentEcosystem(props.agent.agent_id)) {
+ case 'codex': return <CodexModelEditor {...props} />;
+ case 'claude': return <ClaudeModelEditor {...props} />;
+ case 'qoder': return <QoderModelEditor {...props} />;
+ default: return null;
+ }
+}
+
+export function modelSelectionSummary(selection: AgentModelSelection | null | undefined, plans: Plan[], language: 'zh' | 'en'): string {
+ const text = (zh: string, en: string) => language === 'zh' ? zh : en;
+ const planName = (id: string) => plans.find(plan => plan.agent_plan_id === id)?.desired.display_name;
+ switch (selection?.mode) {
+ case 'codex_default':
+ return selection.default_selection.kind === 'plan'
+ ? planName(selection.default_selection.plan_id) ?? text('当前路由不可用', 'Current route unavailable')
+ : selection.default_selection.kind === 'fixed_model'
+ ? selection.default_selection.client_model_id
+ : text('使用 Codex 当前默认模型名称', 'Use the current Codex default model name');
+ case 'claude_launcher': {
+ const sharedPlan = commonClaudePlan(selection.preset_mappings);
+ return sharedPlan
+ ? text('三个档位共用:', 'All presets use: ') + (planName(sharedPlan) ?? text('当前路由不可用', 'Current route unavailable'))
+ : Object.entries(selection.preset_mappings).map(([preset, choice]) => `${preset[0].toUpperCase() + preset.slice(1)}: ${choice.kind === 'plan' ? planName(choice.plan_id) ?? text('当前路由不可用', 'Current route unavailable') : text('保留原生', 'Native')}`).join(' · ');
+ }
+ case 'qoder_additional':
+ return selection.allowed_plan_ids.map(id => planName(id) ?? text('当前路由不可用', 'Current route unavailable')).join(' · ');
+ default: return '';
+ }
+}
diff --git a/apps/desktop/src/features/agents/AgentSettingsFeedback.tsx b/apps/desktop/src/features/agents/AgentSettingsFeedback.tsx
new file mode 100644
index 00000000..4807ae92
--- /dev/null
+++ b/apps/desktop/src/features/agents/AgentSettingsFeedback.tsx
@@ -0,0 +1,60 @@
+import React from 'react';
+import { UiIcon } from '../../ui';
+import { prerequisiteCheck } from './settings-request';
+import type { Agent, AgentCheckScope, AgentDefaultChoice, AgentFacet, Preview } from './types';
+
+/** Translate authoritative Preview blockers without making capability or recovery decisions. */
+export function AgentSettingsFeedback({ preview, agent: selected, facet, defaultChoice, language, disabled, onCheck }: {
+ preview: Preview | null;
+ agent?: Agent;
+ facet?: AgentFacet;
+ defaultChoice: AgentDefaultChoice;
+ language: 'zh' | 'en';
+ disabled: boolean;
+ onCheck: (scope: AgentCheckScope, source: HTMLElement) => void;
+}) {
+ if (!preview || preview.applicable) return null;
+ const text = (zh: string, en: string) => language === 'zh' ? zh : en;
+ const blockedCheckScope = facet ? prerequisiteCheck(preview, facet) : null;
+ return <div className="callout warn agent-feedback" role="status">
+ <UiIcon name="warning" />
+ <div>
+ <strong>{text('当前无法应用,未修改配置。', 'Cannot apply yet. Configuration was not changed.')}</strong>
+ {preview.blockers.map((block, index) => {
+ const capabilities = new Set(block.capabilities?.map(capability => capability.capability) ?? []);
+ const message = capabilities.has('ingress_authentication')
+ ? text('本机认证兼容性尚未确认。', 'Local authentication compatibility is unconfirmed.')
+ : block.reason === 'native_model_coverage_unavailable'
+ ? `${text('保留原 Codex 模型需要先接入原订阅账号或 API 来源,并证明同账号路由。也可改选“只使用已配置的 HiRoute 模型”。', 'To keep native Codex models, connect the original subscription account or API source and prove same-account routes, or select HiRoute-only.')}${(block.model_ids ?? []).length ? ` ${block.model_ids!.join(', ')}` : ''}`
+ : block.reason === 'native_default_invalid'
+ ? `${text('原 Codex 默认模型没有同账号可用路由;请接入对应来源,或改选“只使用已配置的 HiRoute 模型”:', 'The native Codex default has no proven same-account route. Connect its source or select HiRoute-only: ')}${(block.model_ids ?? []).join(', ')}`
+ : block.reason === 'restore_native_model_invalid'
+ ? text('恢复将留下无效的原生默认模型。请在“连接详情与恢复”中明确选择一个原生模型后重试。', 'Restoring would leave an invalid native default. Choose a native model under Connection details and recovery, then retry.')
+ : block.reason === 'qoder_default_in_use'
+ ? text('Qoder 当前默认模型仍引用将被移除的 HiRoute 路由。请先在 Qoder 中通过 /model 切换到其他模型,再重试;HiRoute 不会替你更改默认模型。', 'Qoder’s current default still uses a HiRoute route being removed. Switch to another model with /model in Qoder, then retry; HiRoute will not change the default for you.')
+ : block.reason === 'qoder_model_file_conflict'
+ ? text('Qoder 中的受管路由配置已变化。请核对用户修改后重新预览;HiRoute 不会覆盖冲突字段或无关配置,任务协作无需停用。', 'Managed Qoder route settings have changed. Review your edits, then preview again; HiRoute will not overwrite conflicting fields or unrelated settings. Task collaboration can stay enabled.')
+ : block.reason === 'model_plan_unavailable' && selected?.agent_id === 'agent_codex_default' && defaultChoice.kind === 'preserve_native'
+ ? text('当前默认模型名称或所选路由无法用于 Codex Responses。请在“默认选择”中改选已勾选且支持该入口的路由;若要保留原生模型,请先接入对应来源。配置未修改。', 'The current default model name or a selected route cannot be used by Codex Responses. Under Default selection, choose an enabled route that supports this ingress; to preserve a native model, connect its source first. Configuration was not changed.')
+ : block.reason === 'model_plan_unavailable' && selected?.agent_id === 'agent_codex_default'
+ ? text('所选路由、固定来源或当前默认模型无法用于 Codex Responses。请核对路由是否已启用并支持该入口协议,或改选可用路由;配置未修改。', 'A selected route, fixed source, or current default model cannot be used by Codex Responses. Check that the route is enabled and supports this ingress protocol, or choose an available route. Configuration was not changed.')
+ : block.reason === 'codex_context_override'
+ ? text('Codex 的显式窗口配置会覆盖计划设置。请移除有效配置中的 model_context_window 和 model_auto_compact_token_limit 后重试;HiRoute 不会删除这些配置。', 'Explicit Codex window settings override the plan. Remove model_context_window and model_auto_compact_token_limit from the effective configuration and retry; HiRoute will not delete these settings.')
+ : block.reason === 'claude_plan_capability_unavailable'
+ ? text('所选计划无法满足 Claude Code 的工具调用或流式请求能力,请检查全部候选模型。', 'A selected plan cannot meet Claude Code tool or streaming requirements. Check all candidate models.')
+ : block.reason === 'claude_context_override'
+ ? text('Claude Code 存在窗口覆盖或禁用自动压缩的设置。请移除进程、项目或托管配置中的窗口覆盖,以及禁用压缩的环境变量后重试。', 'Claude Code has window overrides or compaction disabled. Remove process, project, or managed window overrides and compaction-disabling environment variables, then retry.')
+ : block.reason === 'claude_context_window_unsupported'
+ ? text('所选计划的共同窗口低于 Claude Code 的 100K 最低值。请调整计划窗口或使用 Codex。', 'The shared plan window is below Claude Code’s 100K minimum. Adjust the plan window or use Codex.')
+ : block.reason === 'skill_file_conflict'
+ ? text('同名任务委派技能内容不同;原文件已保留。请先移走或明确处理该文件后再预览。', 'A task delegation skill with different content already exists. The original was preserved; move or explicitly resolve it before previewing again.')
+ : capabilities.has('skill_loading') || capabilities.has('trusted_cli_execution')
+ ? text('任务委派技能尚未确认。', 'Task delegation skill capability is unconfirmed.')
+ : text('有前置条件尚未满足,请检查当前 Agent 状态。', 'A prerequisite is unmet. Check the current Agent state.');
+ return <p key={index}>{message}</p>;
+ })}
+ {preview.unproven_native_model_ids?.length ? <p>{text('目录中尚未证明可由原账号调用的模型(不会开放给 Codex):', 'Catalog names not proven callable on the original account (not exposed to Codex): ')}{preview.unproven_native_model_ids.join(', ')}</p> : null}
+ {blockedCheckScope && selected && <button className="btn" type="button" disabled={disabled} onClick={event => onCheck(blockedCheckScope, event.currentTarget)}>{blockedCheckScope === 'native_authentication' ? text('重新检查本机认证', 'Check local authentication again') : text('重新检查任务委派技能', 'Check task delegation skill again')}</button>}
+ </div>
+ </div>;
+}
diff --git a/apps/desktop/src/features/agents/ClaudeModelEditor.tsx b/apps/desktop/src/features/agents/ClaudeModelEditor.tsx
new file mode 100644
index 00000000..5d2fab03
--- /dev/null
+++ b/apps/desktop/src/features/agents/ClaudeModelEditor.tsx
@@ -0,0 +1,45 @@
+import React from 'react';
+import { Disclosure, UiIcon } from '../../ui';
+import type { AgentModelEditorProps } from './AgentModelEditor';
+import { commonClaudePlan, sharedClaudePlan } from './editor-state';
+import type { AgentClaudePresetMappings } from './types';
+
+export function ClaudeModelEditor({
+ values: editorValues, plans, language, onChange: setEditorValues,
+ onEdited, onCreatePlan, invalid: modelFormInvalid,
+}: AgentModelEditorProps) {
+ const text = (zh: string, en: string) => language === 'zh' ? zh : en;
+ const enabledPlans = plans.filter(plan => plan.head.status === 'enabled');
+ const planEnabled = (id: string) => enabledPlans.some(plan => plan.agent_plan_id === id);
+ const claudePlanIds = Object.values(editorValues.claudePresets)
+ .flatMap(choice => choice.kind === 'plan' ? [choice.plan_id] : []);
+ const claudeSharedPlan = commonClaudePlan(editorValues.claudePresets);
+ function selectClaudePreset(preset: keyof AgentClaudePresetMappings, planId: string) {
+ setEditorValues(value => ({
+ ...value,
+ claudePresets: {
+ ...value.claudePresets,
+ [preset]: planId ? { kind: 'plan', plan_id: planId } : { kind: 'preserve_native' },
+ },
+ }));
+ onEdited();
+ }
+
+ return <div className="worker-choices">
+ <label className="field"><span className="field-label">{claudeSharedPlan === null ? text('模型档位路由', 'Preset routes') : text('共用一条路由', 'Use one route for all presets')}</span><select className="select" aria-label={text('Claude Code 路由', 'Claude Code route')} value={claudeSharedPlan ?? ''} onChange={event => { setEditorValues(value => ({ ...value, claudePresets: sharedClaudePlan(event.target.value) })); onEdited(false); }}><option value="" disabled>{claudeSharedPlan === null ? text('已分别配置模型档位', 'Presets configured separately') : text('选择路由', 'Choose a route')}</option>{claudeSharedPlan && !planEnabled(claudeSharedPlan) && <option value={claudeSharedPlan} disabled>{text('原有路由当前不可用', 'Previous route unavailable')}</option>}{enabledPlans.map(plan => <option key={plan.agent_plan_id} value={plan.agent_plan_id}>{plan.desired.display_name}</option>)}</select><span className="field-help">{claudeSharedPlan === null
+ ? text('当前按档位分别配置。选择同一条路由可统一 Opus、Sonnet、Haiku;不会修改 Claude 当前默认模型。', 'Presets are configured separately. Choose one route to unify Opus, Sonnet and Haiku; the current Claude default model is unchanged.')
+ : text('应用于 Opus、Sonnet、Haiku;高级设置可分别配置。不会修改 Claude 当前默认模型。', 'Applies to Opus, Sonnet and Haiku; configure them separately under Advanced settings. The current Claude default model is unchanged.')}</span></label>
+ {editorValues.fixedModels.length > 0 && <p className="field-help">{text('保留已有固定模型:', 'Existing fixed models retained: ')}{editorValues.fixedModels.map(model => model.client_model_id).join(' · ')}</p>}
+ <p className="field-help" data-agent-activation>{text('保存后,重新启动 Claude Code 即可加载配置。', 'Restart Claude Code after saving to load the settings.')}</p>
+ <Disclosure label={text('高级设置', 'Advanced settings')} language={language} defaultOpen={claudeSharedPlan === null || claudePlanIds.some(id => !planEnabled(id))}>
+ <p className="field-help">{text('普通 claude 入口使用这些映射。账号 Default 仍需真实调用验证,可显式选择已映射的模型档位。', 'The ordinary claude entry uses these mappings. Account Default needs a live call to verify; explicitly choose a mapped preset.')}</p>
+ {(['opus', 'sonnet', 'haiku'] as const).map(preset => {
+ const choice = editorValues.claudePresets[preset];
+ const selectedPlan = choice.kind === 'plan' ? choice.plan_id : '';
+ return <label className="field" key={preset}><span className="field-label">{preset[0].toUpperCase() + preset.slice(1)}</span><select className="select" value={selectedPlan} onChange={event => selectClaudePreset(preset, event.target.value)}><option value="">{text('保留原生值或缺省关系', 'Preserve native value or default relationship')}</option>{selectedPlan && !planEnabled(selectedPlan) && <option value={selectedPlan} disabled>{text('原有路由当前不可用', 'Previous route unavailable')}</option>}{enabledPlans.map(plan => <option key={plan.agent_plan_id} value={plan.agent_plan_id}>{plan.desired.display_name}</option>)}</select></label>;
+ })}
+ </Disclosure>
+ {modelFormInvalid && <span className="oc-inline-error">{text('至少将一个预设映射到可用智能路由,或保留已有固定模型。', 'Map at least one preset to an enabled smart route, or retain an existing fixed model.')}</span>}
+ {!enabledPlans.length && <div className="callout"><UiIcon name="route" /><div><span>{text('先创建并启用一条智能路由。', 'Create and enable a smart route first.')}</span></div>{onCreatePlan && <button className="btn" type="button" onClick={onCreatePlan}>{text('创建路由', 'Create route')}</button>}</div>}
+ </div>;
+}
diff --git a/apps/desktop/src/features/agents/CodexAccessPanel.tsx b/apps/desktop/src/features/agents/CodexAccessPanel.tsx
index c2931c2c..686021c9 100644
--- a/apps/desktop/src/features/agents/CodexAccessPanel.tsx
+++ b/apps/desktop/src/features/agents/CodexAccessPanel.tsx
@@ -2,20 +2,8 @@ import React, { useState } from 'react';
import { Disclosure, UiIcon, copyText } from '../../ui';
import { preferredCodexShell } from './codex-launch';
-export type CodexAccess = {
- codex_home: string;
- slot_id: string;
- profile_context_id: string;
- root_context_id: string;
- selected_mode: 'profile' | 'root';
- slot_occupied: boolean;
- target_file: string;
- profile_name: string;
- commands: Record<string, string>;
- pending_operation: string | null;
- access_revoked: boolean;
- conflict_fields: string[];
-};
+export type { CodexAccess } from './types';
+import type { CodexAccess } from './types';
export function CodexAccessSettings({ access, mode, language, disabled, onMode }: {
access: CodexAccess; mode: 'profile' | 'root'; language: 'zh' | 'en'; disabled: boolean;
@@ -31,8 +19,8 @@ export function CodexAccessSettings({ access, mode, language, disabled, onMode }
</label>
{access.slot_occupied && <p className="field-help">{text('切换接入方式前,请先停用并完成配置恢复。', 'Disable and finish restoring the configuration before switching modes.')}</p>}
<Disclosure label={text('配置位置与会话历史', 'Configuration location and history')} language={language}>
- <dl><div><dt>CODEX_HOME</dt><dd><code>{access.codex_home}</code></dd></div>
- {access.slot_occupied && <div><dt>{text('目标文件', 'Target file')}</dt><dd><code>{access.target_file}</code></dd></div>}
+ <dl><div><dt>CODEX_HOME</dt><dd><code className="configuration-path">{access.codex_home}</code></dd></div>
+ {access.slot_occupied && <div><dt>{text('目标文件', 'Target file')}</dt><dd><code className="configuration-path">{access.target_file}</code></dd></div>}
</dl>
<p className="field-help">{text('不同入口的会话历史可能不同;不提供跨 provider 历史恢复。独立 profile 不支持启动 Desktop。', 'History may differ between entry points; cross-provider recovery is not provided. The separate profile cannot launch Desktop.')}</p>
</Disclosure>
@@ -64,7 +52,7 @@ export function CodexAccessPanel({ access, language, retryDisabled, onRetry }: {
<UiIcon name="warning" /><div>
<strong>{text('配置文件存在冲突', 'Configuration file conflict')}</strong>
<p>{text('文件冲突解决前无法完成停用,原连接仍有效。HiRoute 会保留你的修改;请处理以下字段后重新点击“停用”。其他配置仍可修改。', 'Disable cannot complete until the conflict is resolved; the original connection remains active. HiRoute preserves your edits. Resolve these fields, then click Disable again. Other settings remain editable.')}</p>
- <p><code>{access.target_file}</code></p>
+ <p><code className="configuration-path">{access.target_file}</code></p>
<ul>{access.conflict_fields.map(field => <li key={field}><code>{field}</code></li>)}</ul>
</div>
</div>}
@@ -73,7 +61,7 @@ export function CodexAccessPanel({ access, language, retryDisabled, onRetry }: {
<p>{access.access_revoked
? text('已停用,配置文件待清理。旧令牌已失效。', 'Disabled; configuration cleanup is pending. The old token is invalid.')
: text('当前操作尚未完成,不能切换接入模式。', 'The current operation is incomplete; mode switching is blocked.')}</p>
- <p><code>{access.target_file}</code></p>
+ <p><code className="configuration-path">{access.target_file}</code></p>
{access.conflict_fields.length > 0 && <ul>{access.conflict_fields.map(field => <li key={field}><code>{field}</code></li>)}</ul>}
<p>{access.access_revoked
? text('请修复所列冲突,或自行清理 HiRoute 受管字段后重新检查。无关设置和注释可以保留。清理完成前,新的配置保存会暂停。', 'Resolve the listed conflicts, or remove the HiRoute-managed fields and recheck. Unrelated settings and comments can remain. New configuration saves wait until cleanup finishes.')
diff --git a/apps/desktop/src/features/agents/CodexModelEditor.tsx b/apps/desktop/src/features/agents/CodexModelEditor.tsx
new file mode 100644
index 00000000..a38928b3
--- /dev/null
+++ b/apps/desktop/src/features/agents/CodexModelEditor.tsx
@@ -0,0 +1,206 @@
+import { agentModelStatus } from './status';
+import React from 'react';
+import { Disclosure, UiIcon } from '../../ui';
+import type { AgentModelEditorProps } from './AgentModelEditor';
+import { CodexAccessSettings } from './CodexAccessPanel';
+import { codexSurfaceFacts } from './codex-surfaces';
+import { surfaceName } from './ecosystems';
+import { codexDefaultChoiceValid } from './editor-state';
+import type {
+ AgentDefaultChoice, AgentFixedModel, AgentNativeModel, AgentNativeReasoning,
+ AgentModelSourceCoverage, AgentReasoningSelection, CodexNativeModelMode,
+} from './types';
+
+export function CodexModelEditor({
+ agent: selected, values: editorValues, plans, language, disabled, codexMode: activeCodexMode,
+ onCodexMode, onChange: setEditorValues, onEdited, onCreatePlan, invalid: modelFormInvalid,
+}: AgentModelEditorProps) {
+ const text = (zh: string, en: string) => language === 'zh' ? zh : en;
+ const enabledPlans = plans.filter(plan => plan.head.status === 'enabled');
+ const planName = (id: string) => plans.find(plan => plan.agent_plan_id === id)?.desired.display_name;
+ const planEnabled = (id: string) => enabledPlans.some(plan => plan.agent_plan_id === id);
+ const protectedNativeModelIds = new Set(agentModelStatus(selected)?.protected_native_model_ids ?? []);
+ const codexSurfaces = codexSurfaceFacts(activeCodexMode, selected.available_surfaces ?? []);
+ const catalogModels = (selected.native_model_catalog?.models ?? [])
+ .map(model => ({ ...model, source_options: model.source_options ?? [] }));
+ const fixedModelRows = editorValues.fixedModels.map(fixed => catalogModels
+ .find(model => model.client_model_id === fixed.client_model_id) ?? {
+ client_model_id: fixed.client_model_id,
+ display_name: fixed.client_model_id,
+ source_options: [],
+ });
+ const creatingModelConnection = !agentModelStatus(selected)?.current_selection;
+ const defaultChoice = editorValues.defaultChoice;
+ const codexDefaultValid = codexDefaultChoiceValid(defaultChoice, editorValues.nativeModelMode,
+ selected.native_model_catalog?.native_default_model, editorValues.fixedModels, editorValues.allowedPlanIds);
+ const showCodexDefault = editorValues.nativeModelMode === 'preserve_available'
+ || editorValues.fixedModels.length > 0 || editorValues.allowedPlanIds.length > 1;
+ function toggleAllowedPlan(planId: string) {
+ setEditorValues(value => {
+ const selected = value.allowedPlanIds.includes(planId);
+ const allowedPlanIds = selected
+ ? value.allowedPlanIds.filter(id => id !== planId)
+ : [...value.allowedPlanIds, planId];
+ const defaultChoice = selected
+ && value.defaultChoice.kind === 'plan'
+ && value.defaultChoice.plan_id === planId
+ ? value.nativeModelMode === 'preserve_available'
+ ? { kind: 'preserve_native' } as const
+ : allowedPlanIds.length ? { kind: 'plan', plan_id: allowedPlanIds[0] } as const
+ : value.fixedModels.length ? { kind: 'fixed_model', client_model_id: value.fixedModels[0].client_model_id } as const
+ : { kind: 'preserve_native' } as const
+ : !selected && value.nativeModelMode === 'hiroute_only' && value.defaultChoice.kind === 'preserve_native'
+ ? { kind: 'plan', plan_id: planId } as const
+ : value.defaultChoice;
+ return { ...value, allowedPlanIds, defaultChoice };
+ });
+ onEdited();
+ }
+
+ function defaultFixedReasoning(reasoning: AgentNativeReasoning): AgentReasoningSelection | undefined {
+ if (reasoning.kind === 'fixed') return undefined;
+ if (reasoning.kind === 'toggle') return { kind: 'toggle', enabled: true };
+ if (reasoning.kind === 'budget') return { kind: 'budget', tokens: reasoning.maximum_tokens };
+ const enabled = reasoning.profiles.filter(profile => !['none', 'off', 'disabled'].includes(profile.toLocaleLowerCase()));
+ const profile = enabled.at(-1) ?? reasoning.profiles.at(-1);
+ return profile ? { kind: 'profile', profile } : undefined;
+ }
+
+ function selectFixedSource(model: AgentNativeModel, bindingId: string) {
+ setEditorValues(value => {
+ const fixedModels = value.fixedModels.filter(item => item.client_model_id !== model.client_model_id);
+ const source = model.source_options?.find(option => option.binding_id === bindingId && option.state === 'ready');
+ if (source) {
+ fixedModels.push({
+ client_model_id: model.client_model_id,
+ candidate: {
+ binding_id: source.binding_id,
+ reasoning: defaultFixedReasoning(source.reasoning),
+ },
+ });
+ }
+ const defaultChoice = !source
+ && value.defaultChoice.kind === 'fixed_model'
+ && value.defaultChoice.client_model_id === model.client_model_id
+ ? value.nativeModelMode === 'hiroute_only' && value.allowedPlanIds.length
+ ? { kind: 'plan', plan_id: value.allowedPlanIds[0] } as const
+ : { kind: 'preserve_native' } as const
+ : source && value.nativeModelMode === 'hiroute_only' && value.defaultChoice.kind === 'preserve_native'
+ ? { kind: 'fixed_model', client_model_id: model.client_model_id } as const
+ : value.defaultChoice;
+ return { ...value, fixedModels, defaultChoice };
+ });
+ onEdited();
+ }
+
+ function setFixedReasoning(clientModelId: string, reasoning: AgentReasoningSelection | undefined) {
+ setEditorValues(value => ({
+ ...value,
+ fixedModels: value.fixedModels.map(model => model.client_model_id === clientModelId
+ ? { ...model, candidate: { ...model.candidate, reasoning } }
+ : model),
+ }));
+ onEdited();
+ }
+
+ function defaultChoiceValue(choice: AgentDefaultChoice): string {
+ if (choice.kind === 'preserve_native') return 'native';
+ return `${choice.kind === 'plan' ? 'plan' : 'fixed'}:${choice.kind === 'plan' ? choice.plan_id : choice.client_model_id}`;
+ }
+
+ function selectDefaultChoice(value: string) {
+ const defaultChoice: AgentDefaultChoice = value === 'native'
+ ? { kind: 'preserve_native' }
+ : value.startsWith('plan:')
+ ? { kind: 'plan', plan_id: value.slice(5) }
+ : { kind: 'fixed_model', client_model_id: value.slice(6) };
+ setEditorValues(current => ({ ...current, defaultChoice }));
+ onEdited();
+ }
+
+ function selectNativeModelMode(mode: CodexNativeModelMode) {
+ setEditorValues(value => {
+ if (mode === value.nativeModelMode) return value;
+ const fixedModels = mode === 'hiroute_only'
+ ? value.fixedModels.filter(model => !protectedNativeModelIds.has(model.client_model_id))
+ : value.fixedModels;
+ const defaultChoice = mode === 'hiroute_only' && value.defaultChoice.kind === 'preserve_native'
+ ? value.allowedPlanIds.length ? { kind: 'plan', plan_id: value.allowedPlanIds[0] } as const
+ : fixedModels.length ? { kind: 'fixed_model', client_model_id: fixedModels[0].client_model_id } as const
+ : value.defaultChoice
+ : value.defaultChoice;
+ return { ...value, nativeModelMode: mode, fixedModels, defaultChoice };
+ });
+ onEdited(false);
+ }
+
+ const sourceStateLabel = (state: AgentModelSourceCoverage['state']) => state === 'ready'
+ ? text('来源与账号已覆盖', 'Source and account covered')
+ : state === 'credential_required'
+ ? text('需要凭据', 'Credential required')
+ : state === 'authorization_required'
+ ? text('需要账号授权', 'Account authorization required')
+ : state === 'disabled'
+ ? text('来源已停用', 'Source disabled')
+ : text('模型目录匹配未证明', 'Model directory match unproven');
+ const fixedReasoningControl = (
+ model: AgentNativeModel,
+ fixed: AgentFixedModel,
+ source: AgentModelSourceCoverage,
+ ) => {
+ const reasoning = source.reasoning;
+ const selection = fixed.candidate.reasoning;
+ if (reasoning.kind === 'fixed') {
+ return <span className="field-help">{text('原生思考设置:', 'Native reasoning: ')}{reasoning.profile}</span>;
+ }
+ if (reasoning.kind === 'discrete') {
+ return <label className="field"><span className="field-label">{text('思考强度', 'Reasoning effort')}</span><select className="select" value={selection?.kind === 'profile' ? selection.profile : ''} onChange={event => setFixedReasoning(model.client_model_id, { kind: 'profile', profile: event.target.value })}>{reasoning.profiles.map(profile => <option key={profile} value={profile}>{profile}</option>)}</select></label>;
+ }
+ if (reasoning.kind === 'toggle') {
+ return <label className="field"><span className="field-label">{text('思考', 'Reasoning')}</span><select className="select" value={selection?.kind === 'toggle' && selection.enabled ? 'on' : 'off'} onChange={event => setFixedReasoning(model.client_model_id, { kind: 'toggle', enabled: event.target.value === 'on' })}><option value="on">{text('开启', 'On')}</option><option value="off">{text('关闭', 'Off')}</option></select></label>;
+ }
+ return <label className="field"><span className="field-label">{text('思考预算', 'Reasoning budget')}</span><input className="input" type="number" min={reasoning.minimum_tokens} max={reasoning.maximum_tokens} step={reasoning.step_tokens} value={selection?.kind === 'budget' ? selection.tokens : ''} onChange={event => setFixedReasoning(model.client_model_id, { kind: 'budget', tokens: Number(event.target.value) })} /><span className="field-help">{reasoning.minimum_tokens}–{reasoning.maximum_tokens} tokens</span></label>;
+ };
+ return <div className="worker-choices">
+ <p className="field-help" data-codex-shared-scope>{activeCodexMode === 'profile'
+ ? text('按需使用 · 仅 Codex CLI。启用后将启动命令粘贴到终端,开启新会话。普通 Codex 和 Desktop 保持原配置。', 'On demand · Codex CLI only. After enabling, paste the launch command into a terminal to start a new session. Ordinary Codex and Desktop keep their settings.')
+ : text('设为默认 · 修改同一配置目录下 Codex CLI 和 Desktop 的模型接入。保存后重新启动对应客户端即可生效。', 'Use by default · changes model access for Codex CLI and Desktop sharing this directory. Restart the client after saving to apply the settings.')}</p>
+ <fieldset><legend className="field-label">{text('允许的智能路由', 'Allowed smart routes')}</legend>
+ {enabledPlans.length === 1 && creatingModelConnection && <p className="field-help">{text('唯一可用路由已选为默认,可直接启用。', 'The only available route is selected as the default. Enable to continue.')}</p>}
+ {enabledPlans.map(plan => <label className="check-row agent-route-choice" data-agent-plan-id={plan.agent_plan_id} key={plan.agent_plan_id}><input type="checkbox" checked={editorValues.allowedPlanIds.includes(plan.agent_plan_id)} onChange={() => toggleAllowedPlan(plan.agent_plan_id)} /><div><strong>{plan.desired.display_name}</strong></div></label>)}
+ {!enabledPlans.length && <div className="callout"><UiIcon name="route" /><div><span>{text('先创建并启用一条智能路由。', 'Create and enable a smart route first.')}</span></div>{onCreatePlan && <button className="btn" type="button" onClick={onCreatePlan}>{text('创建路由', 'Create route')}</button>}</div>}
+ {editorValues.allowedPlanIds.filter(id => !planEnabled(id)).map(id => <label className="check-row agent-route-choice" key={id}><input type="checkbox" checked onChange={() => toggleAllowedPlan(id)} /><span>{planName(id) ?? id} · {text('当前不可用', 'Currently unavailable')}</span></label>)}
+ {editorValues.allowedPlanIds.some(id => !planEnabled(id)) && <span className="oc-inline-error">{text('已有路由已停用或不存在,请取消选择后再保存。', 'A previously allowed route is disabled or missing. Remove it before saving.')}</span>}
+ </fieldset>
+ {showCodexDefault && <>
+ <label className="field"><span className="field-label">{text('默认选择', 'Default selection')}</span><select className="select" data-agent-default value={defaultChoiceValue(editorValues.defaultChoice)} onChange={event => selectDefaultChoice(event.target.value)}>{editorValues.nativeModelMode === 'preserve_available' && <option value="native">{text('使用 Codex 当前默认模型名称', 'Use the current Codex default model name')}</option>}{editorValues.fixedModels.map(model => <option key={model.client_model_id} value={`fixed:${model.client_model_id}`}>{model.client_model_id}</option>)}{editorValues.allowedPlanIds.filter(planEnabled).map(id => <option key={id} value={`plan:${id}`}>{planName(id)}</option>)}</select><span className="field-help">{defaultChoice.kind === 'preserve_native'
+ ? text('保留当前默认模型名称;请求仍经过 HiRoute。该名称须对应已勾选的路由或已绑定的固定模型。', 'Keep the current default model name; requests still pass through HiRoute. The name must match an enabled route or a bound fixed model.')
+ : defaultChoice.kind === 'plan'
+ ? editorValues.nativeModelMode === 'preserve_available' ? text('Codex 将默认使用所选智能路由;已证明可用的原生模型名称会继续自动保留。', 'Codex will use the selected smart route by default; proven native model names remain available automatically.') : text('Codex 将默认使用所选智能路由。', 'Codex will use the selected smart route by default.')
+ : text('Codex 将默认使用所选固定模型来源。', 'Codex will use the selected fixed model source by default.')}</span>{editorValues.nativeModelMode === 'preserve_available' && defaultChoice.kind === 'preserve_native' && !codexDefaultValid && <span className="oc-inline-error">{text('当前无法读取 Codex 原生默认模型;请修复当前配置后重试。', 'The native Codex default model cannot be read. Repair the current configuration and try again.')}</span>}</label>
+ </>}
+ {fixedModelRows.length > 0 && <fieldset data-agent-fixed-models><legend className="field-label">{text('已配置的原生模型固定来源', 'Configured native model sources')}</legend>
+ {fixedModelRows.map(model => {
+ const fixed = editorValues.fixedModels.find(item => item.client_model_id === model.client_model_id);
+ const source = fixed ? model.source_options.find(option => option.binding_id === fixed.candidate.binding_id) : undefined;
+ return <div className="candidate-row" key={model.client_model_id} data-client-model-id={model.client_model_id}>
+ <div><strong>{model.display_name}</strong><small><code>{model.client_model_id}</code></small>{protectedNativeModelIds.has(model.client_model_id) ? <span className="field-help" data-protected-native-model>{text('原生模型绑定由 HiRoute 自动保留;调整路由时无需重新选择。停用模型路由后可重新配置原生来源。', 'HiRoute keeps this native model binding automatically when routes are edited. Disable model routing to change its native source.')}</span> : null}<label className="field"><span className="field-label">{text('固定来源与账号范围', 'Fixed source and account scope')}</span><select className="select" value={fixed?.candidate.binding_id ?? ''} onChange={event => selectFixedSource(model, event.target.value)} disabled={protectedNativeModelIds.has(model.client_model_id)}>{!protectedNativeModelIds.has(model.client_model_id) && <option value="">{text('不通过 HiRoute 固定此名称', 'Do not fix this name through HiRoute')}</option>}{fixed && !source && <option value={fixed.candidate.binding_id} disabled>{protectedNativeModelIds.has(model.client_model_id) ? text('原有绑定已保留,当前列表未显示来源', 'Binding retained; source is not in the current list') : text('原有来源当前不可用', 'Previous source unavailable')}</option>}{model.source_options.map(option => <option key={option.binding_id} value={option.binding_id} disabled={option.state !== 'ready'}>{option.source_label} · {option.account_scope_ref} · {sourceStateLabel(option.state)}</option>)}</select></label>{source && <span className="field-help">{sourceStateLabel(source.state)} · {text('账号范围摘要 ', 'Account scope digest ')}<code>{source.account_scope_digest.slice(0, 18)}…</code></span>}{fixed && source?.state === 'ready' && !protectedNativeModelIds.has(model.client_model_id) && fixedReasoningControl(model, fixed, source)}{!model.source_options.length && !protectedNativeModelIds.has(model.client_model_id) && <span className="field-help">{text('此原生名称尚无独立来源/账号绑定;元数据不会被当作可调用证明。', 'This native name has no independent source/account binding; metadata is not treated as callable proof.')}</span>}</div>
+ </div>;
+ })}
+ </fieldset>}
+ <Disclosure label={text('高级设置', 'Advanced settings')} language={language}>
+ {selected.codex_access && <CodexAccessSettings access={selected.codex_access} mode={activeCodexMode} language={language} disabled={disabled} onMode={onCodexMode} />}
+ <fieldset data-agent-native-mode><legend className="field-label">{text('Codex 可用模型', 'Models available in Codex')}</legend>
+ <label className="check-row"><input type="radio" name="codex-native-mode" value="hiroute_only" checked={editorValues.nativeModelMode === 'hiroute_only'} onChange={() => selectNativeModelMode('hiroute_only')} /><div><strong>{text('只使用已配置的 HiRoute 模型', 'Use configured HiRoute models only')}</strong><small>{text('无需接入原 Codex 账号;关闭时恢复原配置。', 'No original Codex account connection required; disabling restores the original configuration.')}</small></div></label>
+ <label className="check-row"><input type="radio" name="codex-native-mode" value="preserve_available" checked={editorValues.nativeModelMode === 'preserve_available'} onChange={() => selectNativeModelMode('preserve_available')} /><div><strong>{text('同时保留 Codex 原有模型', 'Also keep native Codex models')}</strong><small>{text('先在“模型”接入原订阅账号或 API 来源;只保留能证明同账号可调用的模型。缓存目录不是账号权限。', 'Connect the original subscription account or API source under Models first. Only proven same-account models are kept; the cache is not entitlement.')}</small></div></label>
+ </fieldset>
+ <div className="callout" data-codex-shared-scope><UiIcon name="info" /><div><strong>{activeCodexMode === 'profile' ? text('独立 CLI 配置', 'Separate CLI configuration') : text('一套共享配置', 'One shared configuration')}</strong><p>{activeCodexMode === 'profile'
+ ? text('本次保存只作用于指定 profile 的 Codex CLI。Desktop 继续使用原来的默认配置。', 'This save applies only to Codex CLI using the selected profile. Desktop keeps its original default configuration.')
+ : text('保存一次即作用于共享此配置作用域与 CODEX_HOME 的 Codex CLI 和 Desktop。', 'One save applies to Codex CLI and Desktop when they share this configuration scope and CODEX_HOME.')}</p>{codexSurfaces.map(({surface, detected, applicable}) => {
+ return <span className="field-help" key={surface} data-agent-surface-fact={surface} data-agent-surface-detected={detected ? 'true' : 'false'} data-agent-surface-applicable={applicable ? 'true' : 'false'}>{surfaceName(surface)} · {detected ? text('当前已发现可执行入口', 'currently detected as runnable') : text('当前未发现可执行入口', 'not currently detected as runnable')} · {applicable ? text('适用当前模式', 'applies to this mode') : text('不适用当前模式', 'does not apply to this mode')}</span>;
+ })}</div></div>
+ <p className="field-help" data-agent-plan-compatibility>{text('保存时会核对路由的 Codex Responses 能力。不同入口的会话历史可能不同。', 'Saving checks the routes’ Codex Responses capabilities. History may differ between entry points.')}</p>
+ </Disclosure>
+ {modelFormInvalid && <span className="oc-inline-error">{text('请选择可用路由或固定模型,并修正不可用项。', 'Choose an available route or fixed model and resolve unavailable selections.')}</span>}
+ </div>;
+}
diff --git a/apps/desktop/src/features/agents/QoderModelEditor.tsx b/apps/desktop/src/features/agents/QoderModelEditor.tsx
new file mode 100644
index 00000000..7eacaeb1
--- /dev/null
+++ b/apps/desktop/src/features/agents/QoderModelEditor.tsx
@@ -0,0 +1,33 @@
+import React from 'react';
+import { UiIcon } from '../../ui';
+import type { AgentModelEditorProps } from './AgentModelEditor';
+
+/** Qoder adds explicit routes without importing or replacing native models. */
+export function QoderModelEditor({ values, plans, language, disabled, invalid, onChange, onEdited, onCreatePlan }: AgentModelEditorProps) {
+ const text = (zh: string, en: string) => language === 'zh' ? zh : en;
+ const enabledPlans = plans.filter(plan => plan.head.status === 'enabled');
+ const unavailable = values.allowedPlanIds.filter(id => !enabledPlans.some(plan => plan.agent_plan_id === id));
+ function toggle(planId: string) {
+ onChange(current => ({ ...current, allowedPlanIds: current.allowedPlanIds.includes(planId)
+ ? current.allowedPlanIds.filter(id => id !== planId) : [...current.allowedPlanIds, planId] }));
+ onEdited();
+ }
+ return <div className="worker-choices" data-qoder-additional-routes>
+ <p>{text('将所选智能路由添加到 Qoder 的模型选择中。原有模型、提供方、登录和当前默认模型保持不变。', 'Add selected smart routes to Qoder’s model choices. Existing models, providers, sign-in and the current default model stay unchanged.')}</p>
+ <fieldset disabled={disabled} className="worker-choices">
+ <legend className="field-label">{text('添加智能路由', 'Add smart routes')}</legend>
+ {enabledPlans.map(plan => <label className="check-row" key={plan.agent_plan_id} data-agent-plan-id={plan.agent_plan_id}>
+ <input type="checkbox" checked={values.allowedPlanIds.includes(plan.agent_plan_id)} onChange={() => toggle(plan.agent_plan_id)} />
+ <span>{plan.desired.display_name}</span>
+ </label>)}
+ {unavailable.map(id => <label className="check-row" key={id} data-agent-plan-id={id}>
+ <input type="checkbox" checked onChange={() => toggle(id)} />
+ <span>{plans.find(plan => plan.agent_plan_id === id)?.desired.display_name ?? id} · {text('当前不可用,可取消选择', 'Currently unavailable; deselect to remove')}</span>
+ </label>)}
+ </fieldset>
+ <p className="field-help" data-agent-activation>{text('保存后重新启动 Qoder,通过 /model 明确选用已添加的 HiRoute 路由。未选择时继续使用原来的模型。', 'Restart Qoder after saving, then explicitly select an added HiRoute route with /model. Otherwise it keeps using your previous model.')}</p>
+ <p className="field-help">{text('在 HiRoute 中调整或移除这些路由。如果已将某条路由设为 Qoder 默认模型,移除前请先在 Qoder 中切换到其他模型。', 'Adjust or remove these routes in HiRoute. If one is now your Qoder default, switch to another model in Qoder before removing it.')}</p>
+ {invalid && <span className="oc-inline-error">{text('至少选择一条已启用路由,并取消不可用的选择。', 'Select at least one enabled route and remove unavailable selections.')}</span>}
+ {!enabledPlans.length && <div className="callout"><UiIcon name="route" /><div>{text('先创建并启用一条智能路由。任务协作仍可独立启用。', 'Create and enable a smart route first. Task collaboration can still be enabled independently.')}</div>{onCreatePlan && <button className="btn" type="button" onClick={onCreatePlan}>{text('创建路由', 'Create route')}</button>}</div>}
+ </div>;
+}
diff --git a/apps/desktop/src/features/agents/README.md b/apps/desktop/src/features/agents/README.md
new file mode 100644
index 00000000..19476c7f
--- /dev/null
+++ b/apps/desktop/src/features/agents/README.md
@@ -0,0 +1,129 @@
+# Agent settings feature
+
+This feature presents Codex, Claude Code and Qoder model routing and task collaboration. It translates an
+editable draft into the existing Agent settings intent; it does not discover installations,
+read credentials, authorize a route, or implement file recovery. The [code map](../../../../../docs/code-map/README.md) connects these boundaries
+to their production owners and executable contracts.
+
+## Responsibilities and state
+
+| Entry | Responsibility |
+| --- | --- |
+| [types.ts](types.ts) | WebView projections and current serialized model choices. These describe the existing native/API contract, not a second capability authority. |
+| [status.ts](status.ts) | Reads the shared model/collaboration-only status union. A missing model capability is distinct from an unconfigured model or an unreadable status. |
+| [ecosystems.ts](ecosystems.ts) | Explicit current Agent identity, display name, brand and surface labels. Unknown discovered identities have no settings editor. |
+| [editor-state.ts](editor-state.ts) | Draft initialization, dirty comparison and local form completeness. Only a trusted first connection can preselect a sole enabled route. Existing mappings, including unavailable choices, are retained. |
+| [settings-request.ts](settings-request.ts) | Ecosystem-specific intent construction, independent model/collaboration restore intents, token changes that retain the saved selection, and capability-based prerequisite check selection. |
+| [AgentModelEditor.tsx](AgentModelEditor.tsx) | Explicit composition of [Codex](CodexModelEditor.tsx), [Claude](ClaudeModelEditor.tsx) and [Qoder](QoderModelEditor.tsx) forms and their saved-selection summary. Codex allowlist/default/native retention, Claude preset mappings and Qoder additional routes remain different concepts. |
+| [AgentSettingsFeedback.tsx](AgentSettingsFeedback.tsx) | Presentation of authoritative Preview blockers. |
+| [collaboration-check-feedback.ts](collaboration-check-feedback.ts) | Versioned collaboration-check failures become safe login, Skill recovery and retry guidance; native output is never display text. |
+| [CodexAccessPanel.tsx](CodexAccessPanel.tsx) | Profile/root facts, mode controls, launch commands, ordinary file-conflict diagnosis and an existing pending Operation's recovery entry. |
+| [codex-launch.ts](codex-launch.ts), [codex-surfaces.ts](codex-surfaces.ts) | Confirmed command-copy eligibility and the distinction between detected executables and mode applicability. |
+| [mutation-feedback.ts](mutation-feedback.ts) | Submitted, pre-apply cancelled and uncertain outcomes; truthful disable/recovery messages. |
+| [Agents page](../../agents.tsx) | Snapshot refresh, selected Agent/tab, in-memory draft and mode, discard guard, native calls, Operation handoff, confirmation-dependent copy effect and task-history composition. |
+
+Qoder adds only explicitly selected Plan IDs through `qoder_additional`. It does not
+edit the native default or show native catalogs, fixed-source choices or import controls.
+Its model configuration uses the existing Preview, protected token and independent
+restore flow. A model restore keeps the collaboration Skill; a collaboration restore
+keeps the model routes. Token updates retain the saved ecosystem-specific selection.
+
+Task collaboration remains independently usable without any model connection or
+published Plan: its form submits `model: keep`. Both model-capable status and actual
+collaboration-only status retain this path. Capability and installed-Skill checks
+provide scoped prerequisite or diagnostic facts; neither proves a delegated task
+completed or a model route worked. They do not create another settings workflow.
+Context IDs bind requests and are not user-facing configuration scopes. Show only
+readable locations already supplied by the native projection (currently the Codex
+configuration directory and file); do not infer a path from an opaque context ID.
+The Plan editor owns its single-CLI installation selection through
+[WorkerDependencies](../WorkerDependencies.tsx); `qoder` and `qodercli` paths are presented
+as returned by discovery, without adapter or Node placeholders.
+
+The page owns interaction state so changing forms does not create another submission or
+Operation store. The native session owns confirmation, protected token registration and
+submission identity; the daemon owns persistent Operations, authorization, journals and
+recovery. The top-level `agents.tsx` type exports and `agent-editor-state.ts` /
+`agent-mutation-feedback.ts` exports remain compatibility entry points for existing callers.
+New Agent feature code imports its local owners directly.
+
+## Current call paths
+
+1. The page invokes `agent_snapshot`. The native
+ [bridge](../../../src-tauri/src/bridge.rs) and
+ [Agent session](../../../src-tauri/src/agent_session.rs) use Client Core to read
+ `ScanAgents`, `GetAgentConnectionStatus` and the plan catalog. A per-Agent status error
+ stays unknown; discovering an executable does not prove model access.
+2. Enable/Edit creates a draft. `agentSettingsSpec` builds the current settings intent;
+ `preview_agent_settings` reaches native Preview, confirmation and protected Apply.
+ If authoritative blockers require a local check, the page invokes
+ `check_agent_authentication` and re-previews. The form's completeness check cannot
+ authorize a route or prove a live model call.
+3. A returned Operation goes to the shell's existing Operation observer. Missing identity
+ after a possible submission remains uncertain. First Codex profile enable copies a
+ command only after the **same** Operation succeeds and a fresh snapshot confirms the
+ target. Clipboard failure preserves the completed connection and manual-copy entry;
+ it never replays Apply.
+4. Ordinary Disable submits a new restore intent through Preview. The backend restores
+ files conditionally before withdrawing access. A normal file conflict preserves the
+ original connection and permits a fresh Preview/Operation after repair. The separate
+ `retry_agent_settings` entry is for an existing pending Operation, including historical
+ sealed revoke tails; it is not the ordinary conflict retry path.
+
+The native [check session](../../../src-tauri/src/agent_check_session.rs) separately
+owns exact ecosystem/surface checks, paid-call consent and response validation for
+real-call diagnostics. These backend checks and their acceptance evidence are not
+additional enable/save steps or model-verification badges on the settings page.
+
+## Keep the product capabilities separate
+
+| User capability | Owner and evidence boundary |
+| --- | --- |
+| Scan installations / read connection state | Native Agent snapshot and backend integrations; this feature renders the projection. |
+| Import an Agent's existing model source into HiRoute | [Model management](../../product/ModelManagementPage.tsx), [device scan](../device-scan/DeviceScanList.tsx) and the protected candidate flow. Import does not configure that Agent to use HiRoute. |
+| Connect an Agent to HiRoute routing | These forms and settings intents, followed by native/backend Preview and Apply. |
+| Safely restore managed configuration | Application transaction and integration/storage effects. The UI presents progress and recovery actions; it cannot infer safety from file appearance. |
+| Copy a command / start an Agent | Copy is a host clipboard effect. It does not launch a process, enable service startup or prove a model call. Existing Codex profile/root applicability stays explicit. |
+| Enable delegation / execute a Worker task | Collaboration configures the caller's task-routing skill. [Task history](../AgentTasks.tsx) and Worker contracts separately own execution, cancellation and results. Model routing support does not imply Worker harness support. |
+
+## Product contract tests
+
+| User journey or invariant | Representative evidence |
+| --- | --- |
+| Shared configuration actions and state across Codex, Claude Code and Qoder, without an automatic live model call | `agent.configuration.shared-interactions` in the [Agent browser scenarios](../../../tests/v3/browser/agent-trust-scenarios.mjs) |
+| First enable, exact existing selections, unknown state and discard protection | [agent-editor-state.test.mjs](../../../tests/agent-editor-state.test.mjs) |
+| Correct ecosystem intent, independent restores, saved-selection token rotation and unsupported identity rejection | [agent-settings-request.test.mjs](../../../tests/agent-settings-request.test.mjs) |
+| Collaboration without a model or published Plan, prerequisite failure/retry and restore; independent single-CLI selection | `qoder.collaboration.enable-without-model`, `qoder.collaboration.retry-and-restore`, `qoder.installation.single-cli` in the browser scenarios; [status projection](../../../tests/agent-status.test.mjs) |
+| Additional routes, cancelled drafts, unavailable saved routes, token rotation and independent restores | `qoder.routing.additional-plans`, `qoder.routing.adjust-and-restore`; the native [settings session](../../../src-tauri/src/agent_session.rs) and [check session](../../../src-tauri/src/agent_check_session.rs) retain protected-boundary tests. Browser IPC does not prove native settings preservation or real provider calls. |
+| Submission uncertainty and restore-first feedback | [agent-mutation-feedback.test.mjs](../../../tests/agent-mutation-feedback.test.mjs) |
+| Same successful Operation and fresh target before copying; discovery versus applicability | [codex-launch.test.mjs](../../../tests/codex-launch.test.mjs), [codex-surfaces.test.mjs](../../../tests/codex-surfaces.test.mjs) |
+| Reachable forms, cancellation, mappings and native clipboard IPC selection | [Agent browser scenarios](../../../tests/v3/browser/agent-trust-scenarios.mjs), [clipboard.test.mjs](../../../tests/clipboard.test.mjs) |
+| File conflict keeps the grant, service-failure compensation and delete races | [backend profile tests](../../../../../crates/daemon/src/control/runtime/settings_profile_tests.rs) |
+| Historical sealed-tail restart and same-Operation recovery | [legacy recovery tests](../../../../../crates/daemon/src/control/runtime/settings_profile_legacy_tests.rs) |
+
+Pure Node tests prove draft/intent contracts. Browser scenarios exercise components with
+mock IPC; backend fixtures prove their specific transaction invariants. None alone proves
+real Tauri, installed-Agent or account behavior. Select checks using the repository's
+[test planner](../../../../../scripts/test-plan.py), retaining that distinction.
+
+## Adding an actual ecosystem
+
+Start with the existing enable, adjust, disable and failure-recovery interaction.
+The scenarios above document those product rules. During review,
+compare the new ecosystem with Codex and Claude Code: an extra check action, status
+badge or confirmation needs a product requirement, not just a callable native API.
+Necessary checks use the authoritative Preview/prerequisite path above; normal
+configuration does not automatically call a paid model.
+
+First establish its real scan/read/import/connect/restore/launch/delegation capabilities
+and the native/backend contract. Add an explicit identity in `ecosystems.ts`, its DTO and
+draft/intent cases, and any required blocker presentation. Add a dedicated form through
+`AgentModelEditor` only when model management is supported; collaboration-only status
+must not acquire an empty model form. Unknown identities must not borrow Claude settings or an existing launch
+command. Keep the common page's submission/Operation flow unless the new behavior needs
+an independently designed contract.
+
+Use a user journey to decide what can be shared after the first real integration. This
+feature has no universal plugin protocol or dynamic form schema, and does not claim support
+for additional ecosystems. New native commands, Worker harnesses, configuration formats or
+recovery semantics require their own contract work rather than a new UI label.
diff --git a/apps/desktop/src/features/agents/codex-launch.ts b/apps/desktop/src/features/agents/codex-launch.ts
index df324949..3a4e342e 100644
--- a/apps/desktop/src/features/agents/codex-launch.ts
+++ b/apps/desktop/src/features/agents/codex-launch.ts
@@ -1,4 +1,5 @@
-import type { Agent } from '../../agents';
+import { agentModelStatus } from './status.ts';
+import type { Agent } from './types';
import type { OperationReference } from '../model-connections/types';
export type PendingCodexLaunchCopy = { operationId: string; contextId: string };
@@ -17,7 +18,7 @@ export function confirmedCodexLaunchCommand(
): string | null {
const access = agent?.codex_access;
if (operation?.operation_id !== target.operationId || operation.state !== 'succeeded'
- || agent?.status_error || agent?.settings?.state !== 'configured'
+ || agent?.status_error || agentModelStatus(agent)?.state !== 'configured'
|| !access?.slot_occupied || access.selected_mode !== 'profile'
|| access.profile_context_id !== target.contextId || access.pending_operation || access.access_revoked) return null;
return access.commands[preferredCodexShell(platform, access.commands)] || null;
diff --git a/apps/desktop/src/features/agents/collaboration-check-feedback.ts b/apps/desktop/src/features/agents/collaboration-check-feedback.ts
new file mode 100644
index 00000000..4dba986b
--- /dev/null
+++ b/apps/desktop/src/features/agents/collaboration-check-feedback.ts
@@ -0,0 +1,55 @@
+const FAILURE_SCHEMA = 'hiroute.agent-collaboration-check-failure/v1';
+
+const messages = {
+ login_required: {
+ zh: '当前客户端需要登录。请正常打开已选客户端完成登录,然后重试协作检查。',
+ en: 'The selected client needs sign-in. Open it normally, sign in, then retry the collaboration check.',
+ },
+ installed_skill_missing: {
+ zh: '未找到已安装的协作 Skill。请检查协作目标,再选择安全恢复或重新启用协作,然后重试检查。现有内容不会自动覆盖。',
+ en: 'The installed collaboration Skill was not found. Review the collaboration target, then safely restore or re-enable collaboration and retry the check. Existing content will not be overwritten automatically.',
+ },
+ installed_skill_changed: {
+ zh: '已安装的协作 Skill 内容发生变化。请检查协作目标,再选择安全恢复或重新启用协作,然后重试检查。现有内容不会自动覆盖。',
+ en: 'The installed collaboration Skill has changed. Review the collaboration target, then safely restore or re-enable collaboration and retry the check. Existing content will not be overwritten automatically.',
+ },
+ installed_skill_invalid: {
+ zh: '已安装的协作 Skill 无法用于本次检查。请检查协作目标,再选择安全恢复或重新启用协作,然后重试检查。现有内容不会自动覆盖。',
+ en: 'The installed collaboration Skill cannot be used for this check. Review the collaboration target, then safely restore or re-enable collaboration and retry the check. Existing content will not be overwritten automatically.',
+ },
+ native_context_unavailable: {
+ zh: '所选客户端上下文暂不可用。请重新选择可用的客户端上下文,然后重试协作检查。',
+ en: 'The selected client context is unavailable. Select an available client context again, then retry the collaboration check.',
+ },
+ native_context_changed: {
+ zh: '所选客户端上下文已经变化。请重新选择并确认客户端上下文,然后重试协作检查。',
+ en: 'The selected client context has changed. Select and confirm the client context again, then retry the collaboration check.',
+ },
+ dependency_unavailable: {
+ zh: '协作检查所需的客户端或命令行入口不可用。请重新检测并选择可用的安装,然后重试检查。',
+ en: 'A client or command-line entry required for the collaboration check is unavailable. Detect and select an available installation again, then retry the check.',
+ },
+ check_timed_out: {
+ zh: '协作检查超时,尚未确认协作可用。请确认所选客户端可正常使用,然后重试检查。',
+ en: 'The collaboration check timed out; collaboration has not been verified. Confirm the selected client is available, then retry the check.',
+ },
+ verification_failed: {
+ zh: '协作验证未通过。请检查所选客户端和协作 Skill 的状态,然后重试检查。',
+ en: 'Collaboration verification failed. Check the selected client and collaboration Skill, then retry the check.',
+ },
+};
+
+function record(value: unknown): value is Record<string, unknown> {
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
+}
+
+/** Project only the versioned backend reason; native error details are not display text. */
+export function collaborationCheckFailureMessage(error: unknown, language: 'zh' | 'en'): string | null {
+ if (!record(error) || error.source !== 'backend' || !record(error.envelope)) return null;
+ const { envelope } = error;
+ if (!record(envelope.error) || envelope.error.details_schema !== FAILURE_SCHEMA
+ || !record(envelope.data) || envelope.data.schema !== FAILURE_SCHEMA) return null;
+ const { reason } = envelope.data;
+ if (typeof reason !== 'string' || !Object.hasOwn(messages, reason)) return null;
+ return messages[reason as keyof typeof messages][language];
+}
diff --git a/apps/desktop/src/features/agents/ecosystems.ts b/apps/desktop/src/features/agents/ecosystems.ts
new file mode 100644
index 00000000..f92b78ea
--- /dev/null
+++ b/apps/desktop/src/features/agents/ecosystems.ts
@@ -0,0 +1,56 @@
+import type { AgentModelSelection, AgentModelSurface } from './types';
+
+export type AgentEcosystem = 'codex' | 'claude' | 'qoder';
+
+/** Only these current integrations have settings editors; discovery is independent. */
+export function agentEcosystem(agentId: string): AgentEcosystem | null {
+ switch (agentId) {
+ case 'agent_codex_default': return 'codex';
+ case 'agent_claude_default': return 'claude';
+ case 'agent_qoder_default': return 'qoder';
+ default: return null;
+ }
+}
+
+export function agentSupportsModelRouting(agentId: string): boolean {
+ const ecosystem = agentEcosystem(agentId);
+ return ecosystem === 'codex' || ecosystem === 'claude' || ecosystem === 'qoder';
+}
+
+/** A saved selection must belong to the actual integration, including token-only edits. */
+export function agentModelSelectionMatches(agentId: string, selection: AgentModelSelection): boolean {
+ switch (agentEcosystem(agentId)) {
+ case 'codex': return selection.mode === 'codex_default';
+ case 'claude': return selection.mode === 'claude_launcher';
+ case 'qoder': return selection.mode === 'qoder_additional';
+ default: return false;
+ }
+}
+
+export function agentDisplayName(agentId: string, language: 'zh' | 'en'): string {
+ switch (agentEcosystem(agentId)) {
+ case 'codex': return 'Codex';
+ case 'claude': return 'Claude Code';
+ case 'qoder': return 'Qoder';
+ default: return agentId.toLowerCase().includes('cursor') ? 'Cursor' : language === 'zh' ? '本机 Agent' : 'Local Agent';
+ }
+}
+
+export function agentBrand(agentId: string): 'codex' | 'claude-code' | 'qoder' | 'agent' {
+ switch (agentEcosystem(agentId)) {
+ case 'codex': return 'codex';
+ case 'claude': return 'claude-code';
+ case 'qoder': return 'qoder';
+ default: return 'agent';
+ }
+}
+
+export function surfaceName(surface: AgentModelSurface): string {
+ switch (surface) {
+ case 'codex_desktop': return 'Codex Desktop';
+ case 'codex_cli': return 'Codex CLI';
+ case 'claude_cli': return 'Claude Code CLI';
+ case 'qoder_cli': return 'Qoder CLI';
+ default: return surface;
+ }
+}
diff --git a/apps/desktop/src/features/agents/editor-state.ts b/apps/desktop/src/features/agents/editor-state.ts
new file mode 100644
index 00000000..b72ec63b
--- /dev/null
+++ b/apps/desktop/src/features/agents/editor-state.ts
@@ -0,0 +1,162 @@
+import type {
+ Agent, AgentFixedModel, AgentDefaultChoice, AgentClaudePresetChoice,
+ AgentClaudePresetMappings, AgentCollaborationTriggerMode, CodexNativeModelMode,
+} from './types';
+import { agentEcosystem, agentModelSelectionMatches, agentSupportsModelRouting } from './ecosystems.ts';
+import { agentModelStatus } from './status.ts';
+export type {
+ AgentDefaultChoice, AgentClaudePresetChoice, AgentClaudePresetMappings,
+ AgentCollaborationTriggerMode, CodexNativeModelMode,
+} from './types';
+
+export type AgentEditorValues = {
+ fixedModels: AgentFixedModel[];
+ nativeModelMode: CodexNativeModelMode;
+ allowedPlanIds: string[];
+ defaultChoice: AgentDefaultChoice;
+ claudePresets: AgentClaudePresetMappings;
+ triggerMode: AgentCollaborationTriggerMode;
+};
+
+export const EMPTY_EDITOR_VALUES: AgentEditorValues = {
+ fixedModels: [],
+ nativeModelMode: 'hiroute_only',
+ allowedPlanIds: [],
+ defaultChoice: { kind: 'preserve_native' },
+ claudePresets: {
+ opus: { kind: 'preserve_native' },
+ sonnet: { kind: 'preserve_native' },
+ haiku: { kind: 'preserve_native' },
+ },
+ triggerMode: 'explicit',
+};
+const preserve = (): AgentClaudePresetChoice => ({ kind: 'preserve_native' });
+
+export function editorFingerprint(value: AgentEditorValues): string {
+ return JSON.stringify({
+ ...value,
+ allowedPlanIds: [...value.allowedPlanIds].sort(),
+ });
+}
+
+export function codexDefaultChoiceValid(
+ choice: AgentDefaultChoice,
+ mode: CodexNativeModelMode,
+ nativeDefault: string | undefined,
+ fixedModels: AgentFixedModel[],
+ allowedPlanIds: string[],
+): boolean {
+ if (choice.kind === 'preserve_native') {
+ if (mode === 'hiroute_only') return false;
+ // The backend checks whether this name resolves to an authorized fixed model or selected
+ // plan alias. The WebView only checks that a current name exists before Preview.
+ return Boolean(nativeDefault);
+ }
+ return choice.kind === 'plan'
+ ? allowedPlanIds.includes(choice.plan_id)
+ : fixedModels.some(model => model.client_model_id === choice.client_model_id);
+}
+
+export function agentEditorSeed(
+ agent: Agent,
+ facet: 'model' | 'collaboration',
+ availablePlanIds: string[] = [],
+): AgentEditorValues & { known: boolean } {
+ const ecosystem = agentEcosystem(agent.agent_id);
+ const status = facet === 'model' ? agentModelStatus(agent) : agent.settings?.collaboration;
+ const selection = status?.current_selection;
+ const initial = status?.state === 'not_configured' || status?.state === 'restored';
+ const known = ecosystem !== null && !agent.status_error && (initial || (status?.state === 'configured' && !!selection));
+ const currentModel = facet === 'model' ? agentModelStatus(agent)?.current_selection : undefined;
+ const codex = currentModel?.mode === 'codex_default' ? currentModel : undefined;
+ const claude = currentModel?.mode === 'claude_launcher' ? currentModel : undefined;
+ const qoder = currentModel?.mode === 'qoder_additional' ? currentModel : undefined;
+ const collaboration = facet === 'collaboration'
+ && selection
+ && 'trigger_mode' in selection
+ ? selection
+ : undefined;
+ const initialPlan = facet === 'model' && initial && known && !currentModel && availablePlanIds.length === 1
+ ? availablePlanIds[0] : undefined;
+ return {
+ known: facet === 'model'
+ ? known && agentSupportsModelRouting(agent.agent_id) && (initial || Boolean(currentModel && agentModelSelectionMatches(agent.agent_id, currentModel)))
+ : known,
+ fixedModels: currentModel && 'fixed_models' in currentModel ? currentModel.fixed_models : [],
+ nativeModelMode: codex?.native_model_mode ?? 'hiroute_only',
+ allowedPlanIds: codex?.allowed_plan_ids ?? qoder?.allowed_plan_ids
+ ?? (initialPlan && (ecosystem === 'codex' || ecosystem === 'qoder') ? [initialPlan] : []),
+ defaultChoice: codex?.default_selection ?? (initialPlan && ecosystem === 'codex'
+ ? { kind: 'plan', plan_id: initialPlan } : { kind: 'preserve_native' }),
+ claudePresets: claude?.preset_mappings ?? {
+ opus: initialPlan && ecosystem === 'claude' ? { kind: 'plan', plan_id: initialPlan } : preserve(),
+ sonnet: initialPlan && ecosystem === 'claude' ? { kind: 'plan', plan_id: initialPlan } : preserve(),
+ haiku: initialPlan && ecosystem === 'claude' ? { kind: 'plan', plan_id: initialPlan } : preserve(),
+ },
+ triggerMode: collaboration?.trigger_mode ?? 'explicit',
+ };
+}
+
+export function commonClaudePlan(mappings: AgentClaudePresetMappings): string | null {
+ const ids = Object.values(mappings).map(choice => choice.kind === 'plan' ? choice.plan_id : '');
+ return ids.every(id => id === ids[0]) ? ids[0] : null;
+}
+
+export function sharedClaudePlan(planId: string): AgentClaudePresetMappings {
+ return {
+ opus: { kind: 'plan', plan_id: planId },
+ sonnet: { kind: 'plan', plan_id: planId },
+ haiku: { kind: 'plan', plan_id: planId },
+ };
+}
+
+/** Local form completeness only; Preview remains the authority for capabilities and grants. */
+export function agentModelFormInvalid(agent: Agent | undefined, editorValues: AgentEditorValues, enabledPlanIds: string[]): boolean {
+ if (!agent || agentEcosystem(agent.agent_id) === null) return true;
+ if (agentEcosystem(agent.agent_id) === 'qoder') {
+ return editorValues.allowedPlanIds.length === 0
+ || editorValues.allowedPlanIds.some(id => !enabledPlanIds.includes(id));
+ }
+ const protectedNativeModelIds = new Set(agentModelStatus(agent)?.protected_native_model_ids ?? []);
+ const catalogModels = (agent.native_model_catalog?.models ?? [])
+ .map(model => ({ ...model, source_options: model.source_options ?? [] }));
+ const selectedPlansEnabled = editorValues.allowedPlanIds.every(id => enabledPlanIds.includes(id));
+ const defaultChoice = editorValues.defaultChoice;
+ const selectedFixedSourcesValid = editorValues.fixedModels.every(fixed => {
+ if (protectedNativeModelIds.has(fixed.client_model_id)) return true;
+ const source = catalogModels
+ .find(model => model.client_model_id === fixed.client_model_id)
+ ?.source_options.find(option => option.binding_id === fixed.candidate.binding_id);
+ if (!source || source.state !== 'ready') return false;
+ const selection = fixed.candidate.reasoning;
+ if (source.reasoning.kind === 'fixed') return selection === undefined;
+ if (source.reasoning.kind === 'toggle') return selection?.kind === 'toggle';
+ if (source.reasoning.kind === 'discrete') {
+ return selection?.kind === 'profile' && source.reasoning.profiles.includes(selection.profile);
+ }
+ return selection?.kind === 'budget'
+ && selection.tokens >= source.reasoning.minimum_tokens
+ && selection.tokens <= source.reasoning.maximum_tokens
+ && (selection.tokens - source.reasoning.minimum_tokens) % source.reasoning.step_tokens === 0;
+ });
+ const nativeDefault = agent.native_model_catalog?.native_default_model;
+ const codexDefaultValid = codexDefaultChoiceValid(
+ defaultChoice,
+ editorValues.nativeModelMode,
+ nativeDefault,
+ editorValues.fixedModels,
+ editorValues.allowedPlanIds,
+ );
+ const claudePlanIds = Object.values(editorValues.claudePresets)
+ .flatMap(choice => choice.kind === 'plan' ? [choice.plan_id] : []);
+ switch (agentEcosystem(agent.agent_id)) {
+ case 'codex':
+ return editorValues.allowedPlanIds.length + editorValues.fixedModels.length === 0
+ || !selectedFixedSourcesValid || !selectedPlansEnabled || !codexDefaultValid;
+ case 'claude':
+ return claudePlanIds.length + editorValues.fixedModels.length === 0
+ || claudePlanIds.some(id => !enabledPlanIds.includes(id));
+ default:
+ return true;
+ }
+}
diff --git a/apps/desktop/src/features/agents/mutation-feedback.ts b/apps/desktop/src/features/agents/mutation-feedback.ts
new file mode 100644
index 00000000..1a8e94c0
--- /dev/null
+++ b/apps/desktop/src/features/agents/mutation-feedback.ts
@@ -0,0 +1,54 @@
+import type { AgentMutationOutcome } from './types';
+export type { AgentMutationOutcome } from './types';
+
+export type AgentMutationDisposition = 'cancelled' | 'submitted' | 'unverified';
+
+/**
+ * A missing Operation is not proof that an apply was a no-op. Once the native
+ * host attempted submission, every non-cancelled result without an identity
+ * must stay in recovery until the backend can reconcile the idempotency key.
+ */
+export function classifyAgentMutation(
+ mutation: AgentMutationOutcome,
+): AgentMutationDisposition {
+ if (mutation.state === 'cancelled_before_apply') return 'cancelled';
+ if (mutation.operation) return 'submitted';
+ return 'unverified';
+}
+
+export function agentDisableMessage(state: string, language: 'zh' | 'en'): string {
+ const zh = language === 'zh';
+ if (state === 'succeeded') return zh
+ ? '模型配置已恢复,连接已停用。'
+ : 'Model settings restored; the connection is disabled.';
+ if (state === 'rolled_back') return zh
+ ? '停用未完成,本次变更已回滚,原连接仍有效。请处理冲突或失败原因后重新点击“停用”。'
+ : 'Disable did not complete. This change was rolled back; the original connection remains active. Resolve the conflict or failure, then click Disable again.';
+ if (state === 'needs_attention') return zh
+ ? '停用未完成,回滚尚未确认。请查看操作状态并处理恢复问题。'
+ : 'Disable did not complete and rollback is unconfirmed. Check the operation status and resolve the recovery issue.';
+ return zh ? '正在恢复模型配置并停用连接…' : 'Restoring model settings and disabling the connection…';
+}
+
+export function agentActionErrorMessage(code: string, language: 'zh' | 'en'): string {
+ const zh = language === 'zh';
+ if (code === 'AGENT_TOKEN_INVALID') return zh
+ ? '令牌须为 16–128 位英文字母、数字或 . _ ~ -。当前令牌未更改。'
+ : 'Use 16–128 letters, numbers, or . _ ~ -. The current token was not changed.';
+ if (['CHANGE_PREVIEW_STALE', 'REVISION_CONFLICT', 'application.error.change_preview_stale', 'application.error.revision_conflict'].includes(code)) {
+ return zh
+ ? '配置在保存前发生变化,本次未提交。当前选择已保留,请再次保存以重新读取最新状态。'
+ : 'The configuration changed before this save was admitted. Your choices are retained; save again to use the latest state.';
+ }
+ if (code === 'SERVICE_UNAVAILABLE' || code === 'application.error.gateway_unavailable') {
+ return zh
+ ? '本机服务暂不可用,或旧接入的登录项清理未完成,本次未提交。请检查 HiRoute 服务;若正在恢复旧接入,也检查其登录项状态。'
+ : 'The local service is unavailable, or cleanup of a login item from an older connection is incomplete. Nothing was submitted. Check the HiRoute service, and for an older restore also check its login item.';
+ }
+ if (code === 'RESOURCE_NOT_FOUND' || code === 'application.error.resource_not_found') {
+ return zh
+ ? 'Agent 安装或配置已变化。请重新检测该 Agent 后保存;当前选择已保留。'
+ : 'The Agent installation or configuration changed. Detect it again, then save; your choices are retained.';
+ }
+ return zh ? '操作未完成,当前输入已保留。' : 'The operation did not complete; your input is retained.';
+}
diff --git a/apps/desktop/src/features/agents/settings-request.ts b/apps/desktop/src/features/agents/settings-request.ts
new file mode 100644
index 00000000..bad6df7f
--- /dev/null
+++ b/apps/desktop/src/features/agents/settings-request.ts
@@ -0,0 +1,95 @@
+import type { Agent, AgentCheckScope, AgentFacet, AgentModelSelection, Preview } from './types';
+import type { AgentEditorValues } from './editor-state';
+import { agentEcosystem, agentModelSelectionMatches, agentSupportsModelRouting } from './ecosystems.ts';
+import { agentHasNoModelConnection, agentModelStatus } from './status.ts';
+
+type SettingsDraft = {
+ values: AgentEditorValues;
+ codexMode: 'profile' | 'root';
+ restoreNativeModel: string;
+};
+
+/** Build only the public intent. Native Preview/confirmation owns authorization and Apply. */
+export function agentSettingsSpec(agent: Agent, facet: AgentFacet, restore: boolean, draft: SettingsDraft) {
+ const ecosystem = agentEcosystem(agent.agent_id);
+ if (!agent.context_id || !ecosystem) throw new Error('AGENT_INPUT_INVALID');
+ const { values, codexMode, restoreNativeModel } = draft;
+ const keep = { intent: 'keep' as const };
+ if (facet === 'model') {
+ if (!agentSupportsModelRouting(agent.agent_id) || agentHasNoModelConnection(agent)) throw new Error('AGENT_INPUT_INVALID');
+ const current = agentModelStatus(agent)?.current_selection;
+ if (current && !agentModelSelectionMatches(agent.agent_id, current)) throw new Error('AGENT_INPUT_INVALID');
+ let settings: AgentModelSelection;
+ switch (ecosystem) {
+ case 'codex':
+ settings = {
+ mode: 'codex_default',
+ native_model_mode: values.nativeModelMode,
+ fixed_models: values.fixedModels,
+ allowed_plan_ids: values.allowedPlanIds,
+ default_selection: values.defaultChoice,
+ };
+ break;
+ case 'claude':
+ settings = {
+ mode: 'claude_launcher',
+ surfaces: ['claude_cli'],
+ fixed_models: values.fixedModels,
+ preset_mappings: values.claudePresets,
+ };
+ break;
+ case 'qoder':
+ settings = { mode: 'qoder_additional', allowed_plan_ids: values.allowedPlanIds };
+ break;
+ default: throw new Error('AGENT_INPUT_INVALID');
+ }
+ return {
+ schema_version: { major: 2, minor: 0 },
+ context_id: agent.codex_access && !agent.codex_access.slot_occupied
+ ? (codexMode === 'root' ? agent.codex_access.root_context_id : agent.codex_access.profile_context_id)
+ : agent.context_id,
+ restore_native_model: restore && ecosystem === 'codex' && agent.codex_access?.selected_mode !== 'profile' && restoreNativeModel
+ ? restoreNativeModel : undefined,
+ model: restore
+ ? { intent: 'restore', restore_point_ref: agentModelStatus(agent)?.restore_point_ref }
+ : { intent: 'configure', settings },
+ collaboration: keep,
+ };
+ }
+ return {
+ schema_version: { major: 2, minor: 0 },
+ context_id: agent.codex_access?.root_context_id ?? agent.context_id,
+ model: keep,
+ collaboration: restore
+ ? { intent: 'restore', restore_point_ref: agent.settings?.collaboration?.restore_point_ref }
+ : { intent: 'configure', settings: { trigger_mode: values.triggerMode } },
+ };
+}
+
+/** Token changes retain the current model selection and never resubmit an editor draft. */
+export function agentTokenSpec(agent: Agent, regenerate: boolean) {
+ const selection = agentModelStatus(agent)?.current_selection;
+ if (!agent.context_id || !agentSupportsModelRouting(agent.agent_id) || !selection
+ || !agentModelSelectionMatches(agent.agent_id, selection)) {
+ throw new Error('AGENT_INPUT_INVALID');
+ }
+ return {
+ schema_version: { major: 2, minor: 0 },
+ context_id: agent.context_id,
+ model: { intent: 'configure', settings: selection },
+ collaboration: { intent: 'keep' },
+ access_token: { intent: regenerate ? 'regenerate' : 'keep' },
+ };
+}
+
+export function prerequisiteCheck(preview: Preview, facet: AgentFacet): AgentCheckScope | null {
+ if (preview.applicable) return null;
+ const missing = new Set(preview.blockers.flatMap(block => block.capabilities?.map(item => item.capability) ?? []));
+ // Native ingress authentication can gate either facet: collaboration still
+ // enters through the selected Agent even though it ultimately dispatches a
+ // task. Treat the capability as the authority instead of inferring the check
+ // from whichever settings form happened to expose the blocker.
+ if (missing.has('ingress_authentication')) return 'native_authentication';
+ if (facet === 'collaboration' && (missing.has('skill_loading') || missing.has('trusted_cli_execution'))) return 'collaboration';
+ return null;
+}
diff --git a/apps/desktop/src/features/agents/status.ts b/apps/desktop/src/features/agents/status.ts
new file mode 100644
index 00000000..46dfca4b
--- /dev/null
+++ b/apps/desktop/src/features/agents/status.ts
@@ -0,0 +1,13 @@
+import type { Agent, ModelStatus } from './types';
+
+/** Collaboration-only status has no model facet; absence is not an unconfigured model. */
+export function agentModelStatus(agent: Agent | null | undefined): ModelStatus | null {
+ const settings = agent?.settings;
+ return settings && 'state' in settings ? settings : null;
+}
+
+export function agentHasNoModelConnection(agent: Agent | null | undefined): boolean {
+ const settings = agent?.settings;
+ return Boolean(settings && 'schema' in settings
+ && settings.schema === 'hiroute.agent-collaboration-only-settings-status/v2');
+}
diff --git a/apps/desktop/src/features/agents/types.ts b/apps/desktop/src/features/agents/types.ts
new file mode 100644
index 00000000..85e80312
--- /dev/null
+++ b/apps/desktop/src/features/agents/types.ts
@@ -0,0 +1,159 @@
+import type { Plan } from '../../plan-editor';
+import type { OperationReference } from '../model-connections/types';
+
+export type AgentCollaborationTriggerMode = 'explicit' | 'delegate_by_default';
+export type CodexNativeModelMode = 'hiroute_only' | 'preserve_available';
+export type AgentDefaultChoice =
+ | { kind: 'preserve_native' }
+ | { kind: 'fixed_model'; client_model_id: string }
+ | { kind: 'plan'; plan_id: string };
+export type AgentClaudePresetChoice =
+ | { kind: 'preserve_native' }
+ | { kind: 'plan'; plan_id: string };
+export type AgentClaudePresetMappings = {
+ opus: AgentClaudePresetChoice;
+ sonnet: AgentClaudePresetChoice;
+ haiku: AgentClaudePresetChoice;
+};
+
+export type CodexAccess = {
+ codex_home: string;
+ slot_id: string;
+ profile_context_id: string;
+ root_context_id: string;
+ selected_mode: 'profile' | 'root';
+ slot_occupied: boolean;
+ target_file: string;
+ profile_name: string;
+ commands: Record<string, string>;
+ pending_operation: string | null;
+ access_revoked: boolean;
+ conflict_fields: string[];
+};
+
+export type CollaborationStatus = {
+ state: string;
+ restore_point_ref: string | null;
+ current_selection?: { trigger_mode: AgentCollaborationTriggerMode } | null;
+};
+export type AgentModelSurface = 'codex_cli' | 'codex_desktop' | 'claude_cli' | 'qoder_cli';
+export type AgentReasoningSelection =
+ | { kind: 'profile'; profile: string }
+ | { kind: 'toggle'; enabled: boolean }
+ | { kind: 'budget'; tokens: number };
+export type AgentNativeReasoning =
+ | { kind: 'fixed'; profile: string }
+ | { kind: 'toggle'; parameter: string }
+ | { kind: 'discrete'; parameter: string; profiles: string[] }
+ | { kind: 'budget'; parameter: string; minimum_tokens: number; maximum_tokens: number; step_tokens: number };
+export type AgentFixedModel = {
+ client_model_id: string;
+ candidate: { binding_id: string; reasoning?: AgentReasoningSelection };
+};
+export type AgentModelSourceCoverage = {
+ binding_id: string;
+ source_label: string;
+ account_scope_ref: string;
+ account_scope_digest: string;
+ state: 'ready' | 'credential_required' | 'authorization_required' | 'disabled' | 'model_unconfirmed';
+ reasoning: AgentNativeReasoning;
+};
+export type AgentNativeModel = {
+ client_model_id: string;
+ display_name: string;
+ source_options?: AgentModelSourceCoverage[];
+};
+export type AgentNativeModelCatalog = {
+ metadata_source: 'user_configured' | 'target_cache' | 'target_bundled';
+ native_default_model: string;
+ models: AgentNativeModel[];
+};
+export type CodexModelSelection = {
+ mode: 'codex_default';
+ native_model_mode: CodexNativeModelMode;
+ fixed_models: AgentFixedModel[];
+ allowed_plan_ids: string[];
+ default_selection: AgentDefaultChoice;
+};
+export type ClaudeModelSelection = {
+ mode: 'claude_launcher';
+ surfaces: ['claude_cli'];
+ fixed_models: AgentFixedModel[];
+ preset_mappings: AgentClaudePresetMappings;
+};
+export type QoderModelSelection = {
+ mode: 'qoder_additional';
+ allowed_plan_ids: string[];
+};
+export type AgentModelSelection = CodexModelSelection | ClaudeModelSelection | QoderModelSelection;
+export type AgentSurfaceResult = {
+ surface: AgentModelSurface;
+ applied_revision: number;
+ state: 'not_verified' | 'passed' | 'failed';
+ reason_code: string | null;
+};
+export type AgentLiveCheckTarget = {
+ context_id: string;
+ surface: AgentModelSurface;
+ expected_applied_revision: number;
+ client_model_ids: string[];
+};
+export type AgentLiveCheckCompletion = {
+ accepted: boolean;
+ scope: string;
+ model_call: boolean;
+ state?: string;
+ call_count: number;
+ requested_call_count: number;
+};
+export type ModelStatus = {
+ state: string;
+ operation_id?: string | null;
+ operation_state?: string | null;
+ model_verified: boolean;
+ applied_revision?: number | null;
+ surface_results?: AgentSurfaceResult[];
+ live_check_targets?: AgentLiveCheckTarget[];
+ current_selection?: AgentModelSelection | null;
+ protected_native_model_ids?: string[];
+ restore_point_ref: string | null;
+ collaboration?: CollaborationStatus | null;
+};
+export type CollaborationOnlyStatus = {
+ schema: 'hiroute.agent-collaboration-only-settings-status/v2';
+ context_id: string;
+ collaboration: CollaborationStatus;
+};
+export type AgentSettingsStatus = ModelStatus | CollaborationOnlyStatus;
+export type Agent = {
+ codex_access?: CodexAccess | null;
+ agent_id: string;
+ version: string;
+ context_id: string | null;
+ configuration_state: string;
+ available_surfaces?: AgentModelSurface[];
+ native_model_catalog?: AgentNativeModelCatalog | null;
+ settings: AgentSettingsStatus | null;
+ status_error: string | null;
+};
+export type AgentSnapshot = {
+ agents: Agent[];
+ plans: { plans: Plan[] };
+ trusted_authority: boolean;
+};
+export type Preview = {
+ applicable: boolean;
+ unproven_native_model_ids?: string[];
+ blockers: { reason: string; capabilities?: { capability: string; reason: string }[]; model_ids?: string[] }[];
+};
+export type AgentMutationOutcome = {
+ state: string;
+ operation: OperationReference | null;
+};
+
+export type Outcome = {
+ preview: Preview;
+ mutation: AgentMutationOutcome | null;
+};
+export type AgentFacet = 'model' | 'collaboration';
+export type AgentCheckScope = 'native_authentication' | 'collaboration';
diff --git a/apps/desktop/src/features/device-scan/DeviceScanList.tsx b/apps/desktop/src/features/device-scan/DeviceScanList.tsx
index f5ece81e..43f15465 100644
--- a/apps/desktop/src/features/device-scan/DeviceScanList.tsx
+++ b/apps/desktop/src/features/device-scan/DeviceScanList.tsx
@@ -22,6 +22,7 @@ export type ComputeScanResult = { items: ComputeScanItem[] };
function agentName(agentId: string, language: 'zh' | 'en') {
if (agentId.includes('claude')) return 'Claude Code';
if (agentId.includes('codex')) return 'Codex';
+ if (agentId.includes('qoder')) return 'Qoder';
return language === 'zh' ? '本机 Agent' : 'Local agent';
}
diff --git a/apps/desktop/src/features/home/copy.ts b/apps/desktop/src/features/home/copy.ts
index 57f6a81c..745e4ce8 100644
--- a/apps/desktop/src/features/home/copy.ts
+++ b/apps/desktop/src/features/home/copy.ts
@@ -135,6 +135,7 @@ export function facetLabel(state: HomeFacetState, language: Language): string {
pending: ['正在处理', 'Pending'],
degraded: ['受到影响', 'Degraded'],
unavailable: ['不可用', 'Unavailable'],
+ unsupported: ['不支持', 'Not supported'],
unknown: ['待核实', 'Unverified'],
};
return labels[state][language === 'zh' ? 0 : 1];
diff --git a/apps/desktop/src/features/home/state.ts b/apps/desktop/src/features/home/state.ts
index 4ec6c9ce..43c5c5b9 100644
--- a/apps/desktop/src/features/home/state.ts
+++ b/apps/desktop/src/features/home/state.ts
@@ -63,7 +63,7 @@ export function visibleData<T>(read: HomeRead<T>): T | undefined {
}
function configuredFacet(state: HomeFacetState): boolean {
- return state !== 'unconfigured' && state !== 'unknown';
+ return state !== 'unconfigured' && state !== 'unknown' && state !== 'unsupported';
}
function hasAnyConfiguration(compute?: HomeCompute, plans?: HomePlans, agents?: HomeAgents): boolean {
diff --git a/apps/desktop/src/features/home/types.ts b/apps/desktop/src/features/home/types.ts
index 631a5b55..155dcc12 100644
--- a/apps/desktop/src/features/home/types.ts
+++ b/apps/desktop/src/features/home/types.ts
@@ -90,7 +90,7 @@ export type HomePlans = {
drafts: HomeDraft[];
};
-export type HomeFacetState = 'unconfigured' | 'configured' | 'verified' | 'pending' | 'degraded' | 'unavailable' | 'unknown';
+export type HomeFacetState = 'unconfigured' | 'configured' | 'verified' | 'pending' | 'degraded' | 'unavailable' | 'unsupported' | 'unknown';
export type HomeAgent = {
agentId: string;
diff --git a/apps/desktop/src/features/worker-dependencies-state.ts b/apps/desktop/src/features/worker-dependencies-state.ts
index 5d3ecb93..b7d11213 100644
--- a/apps/desktop/src/features/worker-dependencies-state.ts
+++ b/apps/desktop/src/features/worker-dependencies-state.ts
@@ -1,4 +1,4 @@
-export type WorkerHarness = 'codex_cli' | 'claude_code';
+export type WorkerHarness = 'codex_cli' | 'claude_code' | 'qoder_cli';
export type WorkerDependencyComponent = 'cli' | 'adapter' | 'node';
export type WorkerDependencyCandidateState = 'found' | 'missing' | 'invalid' | 'unavailable';
@@ -13,7 +13,7 @@ export type WorkerDependencyCandidate = {
export type WorkerDependencySelection = {
harness: WorkerHarness;
- adapter_path: string;
+ adapter_path?: string | null;
cli_path: string;
node_path?: string | null;
};
@@ -36,6 +36,17 @@ export type WorkerDependencySelectionRequest = WorkerDependencySelection & {
expected_selection_revision: number;
};
+export function workerDependencyComponents(harness: WorkerHarness): WorkerDependencyComponent[] {
+ return harness === 'qoder_cli' ? ['cli'] : ['cli', 'adapter', 'node'];
+}
+
+export function workerDependencySelectionComplete(selection: WorkerDependencySelection | null): boolean {
+ if (!selection?.cli_path) return false;
+ return selection.harness === 'qoder_cli'
+ ? selection.adapter_path == null && selection.node_path == null
+ : Boolean(selection.adapter_path);
+}
+
export type WorkerMachineEnvelope<T> = {
status: 'succeeded' | 'accepted' | 'usage_error' | 'conflict' | 'denied' | 'not_found' | 'unavailable' | 'action_required' | 'needs_attention' | 'internal_error';
data?: T | null;
@@ -72,7 +83,7 @@ export function workerDependencySelectionMatches(
const selected = selectedWorkerDependencies(view, request.harness);
return Boolean(selected
&& selected.cli_path === request.cli_path
- && selected.adapter_path === request.adapter_path
+ && (selected.adapter_path ?? null) === (request.adapter_path ?? null)
&& (selected.node_path ?? null) === (request.node_path ?? null));
}
@@ -84,7 +95,7 @@ export function recommendedWorkerDependencies(
if (selected) {
return {
...selected,
- node_path: selected.node_path ?? null,
+ ...(harness === 'qoder_cli' ? {} : { node_path: selected.node_path ?? null }),
expected_selection_revision: workerDependencyRevision(view, harness),
};
}
@@ -93,8 +104,10 @@ export function recommendedWorkerDependencies(
return {
harness,
cli_path: found('cli')?.path ?? '',
- adapter_path: found('adapter')?.path ?? '',
- node_path: found('node')?.path ?? null,
+ ...(harness === 'qoder_cli' ? {} : {
+ adapter_path: found('adapter')?.path ?? '',
+ node_path: found('node')?.path ?? null,
+ }),
expected_selection_revision: workerDependencyRevision(view, harness),
};
}
@@ -110,12 +123,13 @@ export function workerDependencySelectionState(
&& candidate.component === component
&& candidate.path === path)?.state
: undefined;
- const nodeRequired = Boolean(request.node_path)
+ const nodeRequired = harness !== 'qoder_cli' && (Boolean(request.node_path)
|| (!selected && view.install_hints.some(hint => hint.harness === harness
&& hint.component === 'node'
- && hint.reason_code === 'worker.dependencies.install_required'));
- const complete = fact('cli', request.cli_path) === 'found'
- && fact('adapter', request.adapter_path) === 'found'
+ && hint.reason_code === 'worker.dependencies.install_required')));
+ const complete = workerDependencySelectionComplete(request)
+ && fact('cli', request.cli_path) === 'found'
+ && (harness === 'qoder_cli' || fact('adapter', request.adapter_path) === 'found')
&& (!nodeRequired || fact('node', request.node_path) === 'found');
if (selected && complete) return 'configured';
if (complete) return 'found';
diff --git a/apps/desktop/src/occami/styles.css b/apps/desktop/src/occami/styles.css
index a52ebafd..0c28c34a 100644
--- a/apps/desktop/src/occami/styles.css
+++ b/apps/desktop/src/occami/styles.css
@@ -54,12 +54,11 @@
.agent-form .worker-choices fieldset {display:grid;gap:10px;}
.agent-form .agent-route-choice {padding:12px 14px;border:1px solid var(--border);border-radius:10px;background:var(--bg-soft);}
.agent-form .agent-route-choice:has(input:checked) {border-color:var(--accent);background:var(--accent-soft);}
+.configuration-path {white-space:pre-wrap;overflow-wrap:anywhere;}
.agent-launch-command {white-space:pre-wrap;overflow-wrap:anywhere;padding:14px;border:1px solid var(--border);border-radius:10px;background:var(--bg-soft);font-size:calc(12px * var(--hr-text-scale));}
.agent-launch-shell {display:flex;align-items:center;gap:8px;}
.agent-launch-shell .select {width:auto;max-width:160px;}
.agent-form .worker-choices>.field-label {margin-bottom:10px;color:var(--text);font-size:calc(14px * var(--hr-text-scale));font-weight:620;}
-.agent-surface-results {display:grid;gap:8px;margin-top:12px;}
-.agent-surface-result {display:flex;align-items:center;justify-content:space-between;gap:12px;color:var(--text-muted);font-size:calc(12px * var(--hr-text-scale));}
.native-details .actions {display:flex;flex-wrap:wrap;gap:8px;padding:4px 0 16px;}
.task-workspace .master-toolbar {grid-template-columns:minmax(0,1fr) auto;align-items:center;}
.task-workspace .master-list {padding-bottom:12px;}
diff --git a/apps/desktop/src/plan-editor-errors.ts b/apps/desktop/src/plan-editor-errors.ts
index c0585696..37bd8ee4 100644
--- a/apps/desktop/src/plan-editor-errors.ts
+++ b/apps/desktop/src/plan-editor-errors.ts
@@ -11,6 +11,7 @@ export function planErrorMessage(error: unknown, language: 'zh' | 'en'): string
EDITOR_INVALID: ['请检查名称、使用场景及模型设置,当前输入已保留。', 'Check the name, purpose and model settings. Your input is retained.'],
INVALID_ARGUMENTS: ['部分路由设置未通过校验,请检查输入后重试。', 'Some routing settings failed validation. Check your input and retry.'],
CONFLICT: ['配置已在其他地方变化,请重新读取后再提交。当前输入已保留。', 'The configuration changed elsewhere. Reload before submitting. Your input is retained.'],
+ QODER_MODEL_BUDGET_CONFLICT: ['新预算低于 Qoder 当前已接入模型声明的容量。请先在 Agent 页面停用 Qoder 的模型路由,再发布此计划并重新配置模型路由;任务协作无需停用。当前输入已保留。', 'The new budget is below the capacity declared by the current Qoder model connection. Disable Qoder model routing on the Agent page, publish this plan, then configure model routing again. Task collaboration can stay enabled. Your input is retained.'],
PLAN_HEAD_STALE: ['当前路由已在其他地方发布新版本。你的输入已保留,请读取当前生效配置后重新编辑。', 'A newer route version was published elsewhere. Your input is retained; reload the active route before editing again.'],
DRAFT_REVISION_STALE: ['该草稿已在其他地方更新或移除。你的输入已保留,请读取最新草稿和生效配置后重试。', 'This draft was updated or removed elsewhere. Your input is retained; reload the latest draft and active route before retrying.'],
DAEMON_UNAVAILABLE: ['暂时无法连接本机服务,当前输入已保留。请稍后重试。', 'Cannot connect to the local service. Your input is retained. Try again.'],
diff --git a/apps/desktop/src/plan-editor.tsx b/apps/desktop/src/plan-editor.tsx
index 0138068c..5e36ed42 100644
--- a/apps/desktop/src/plan-editor.tsx
+++ b/apps/desktop/src/plan-editor.tsx
@@ -16,7 +16,7 @@ import React, { forwardRef, useEffect, useImperativeHandle, useRef, useState } f
import { invoke } from '@tauri-apps/api/core';
export type Selection = { binding_id: string; reasoning?: { kind: 'profile'; profile: string } | { kind: 'toggle'; enabled: boolean } | { kind: 'budget'; tokens: number } };
type Mode = 'fixed_model' | 'smart_saving' | 'free_first';
-type Work = { harness: 'codex_cli' | 'claude_code'; protocol: 'responses' | 'messages' };
+type Work = { harness: 'codex_cli' | 'claude_code' | 'qoder_cli'; protocol: 'responses' | 'messages' };
type ClassifierAuthHeader = { name: string; value_secret_ref: string };
type SmartClassifier = { kind: 'local_rules' } | {
kind: 'rest';
@@ -109,7 +109,7 @@ function activePlanQualityModels(plan: Plan, candidates: Candidate[]): PlanQuali
}
return models;
}
-export const PlanEditor = forwardRef<PlanEditorHandle, { plan?: Plan; draft?: Draft; creating?: boolean; initialBindingId?: string; editingMemory?: PlanEditorMemory; language: 'zh' | 'en'; active?: boolean; usedBy?: { id: string; name: string; brand: 'codex' | 'claude-code' | 'agent'; isDefault: boolean }[]; onOpenAgent?: (agentId: string) => void; onOpenSession?: (sessionId: string, requestId: string) => void; onDone: () => Promise<void>; onClose: () => void; onDirty?: (dirty: boolean) => void; onEdit?: () => void; onBusyChange?: (busy: boolean) => void; onOperation?: (operation: PlanOperation | null) => void; onPersisted?: (editor: PersistedEditor<Plan, Draft> | null, action: 'save_draft' | 'publish', identity: PersistenceIdentity, operation: PlanOperation | null) => void }>(function PlanEditor({ plan, draft, creating = false, initialBindingId, editingMemory, language, active = true, usedBy = [], onOpenAgent, onOpenSession, onDone, onClose, onDirty, onEdit, onBusyChange, onOperation, onPersisted }, ref) {
+export const PlanEditor = forwardRef<PlanEditorHandle, { plan?: Plan; draft?: Draft; creating?: boolean; initialBindingId?: string; editingMemory?: PlanEditorMemory; language: 'zh' | 'en'; active?: boolean; usedBy?: { id: string; name: string; brand: 'codex' | 'claude-code' | 'qoder' | 'agent'; isDefault: boolean }[]; onOpenAgent?: (agentId: string) => void; onOpenSession?: (sessionId: string, requestId: string) => void; onDone: () => Promise<void>; onClose: () => void; onDirty?: (dirty: boolean) => void; onEdit?: () => void; onBusyChange?: (busy: boolean) => void; onOperation?: (operation: PlanOperation | null) => void; onPersisted?: (editor: PersistedEditor<Plan, Draft> | null, action: 'save_draft' | 'publish', identity: PersistenceIdentity, operation: PlanOperation | null) => void }>(function PlanEditor({ plan, draft, creating = false, initialBindingId, editingMemory, language, active = true, usedBy = [], onOpenAgent, onOpenSession, onDone, onClose, onDirty, onEdit, onBusyChange, onOperation, onPersisted }, ref) {
const en = language === 'en', text = (zh: string, eng: string) => en ? eng : zh;
const [editor, setEditor] = useState<Editor>(() => structuredClone(draft?.editor ?? (plan ? reopen(plan) : emptyEditor())));
const [draftId] = useState(() => draft?.draft_id ?? 'draft/' + crypto.randomUUID());
@@ -482,13 +482,14 @@ export const PlanEditor = forwardRef<PlanEditorHandle, { plan?: Plan; draft?: Dr
{editor.delegation_enabled && <div className="field"><label className="field-label">{text('执行任务的 Agent', 'Task execution agent')}</label><p className="field-help">{text('每份计划选择一个执行 Agent,不做自动回退。', 'Choose one execution agent per plan; there is no automatic fallback.')}</p><div className="v3-executors">{([
['codex_cli', 'Codex CLI', text('使用 Codex CLI 执行委派任务', 'Use Codex CLI for delegated tasks')],
['claude_code', 'Claude Code', text('使用 Claude Code 执行委派任务', 'Use Claude Code for delegated tasks')],
- ] as const).map(([value, title, description]) => <button className={`v3-executor${editor.work?.harness === value ? ' selected' : ''}`} type="button" key={value} aria-pressed={editor.work?.harness === value} onClick={() => update({ work: { harness: value, protocol: value === 'claude_code' ? 'messages' : 'responses' } })}><BrandIcon kind={value === 'codex_cli' ? 'codex' : 'claude-code'} label={`${title} logo`} /><div><strong>{title}</strong><span>{description}</span></div>{editor.work?.harness === value && <UiIcon name="check" />}</button>)}</div>{validationIssue?.group === 'executor' && <p className="oc-inline-error route-lane-error">{validationIssue.message}</p>}
+ ['qoder_cli', 'Qoder CLI', text('使用 Qoder CLI 执行委派任务', 'Use Qoder CLI for delegated tasks')],
+ ] as const).map(([value, title, description]) => <button className={`v3-executor${editor.work?.harness === value ? ' selected' : ''}`} type="button" key={value} aria-pressed={editor.work?.harness === value} onClick={() => update({ work: { harness: value, protocol: value === 'claude_code' ? 'messages' : 'responses' } })}><BrandIcon kind={value === 'codex_cli' ? 'codex' : value === 'claude_code' ? 'claude-code' : 'qoder'} label={`${title} logo`} /><div><strong>{title}</strong><span>{description}</span></div>{editor.work?.harness === value && <UiIcon name="check" />}</button>)}</div>{validationIssue?.group === 'executor' && <p className="oc-inline-error route-lane-error">{validationIssue.message}</p>}
{editor.work && <WorkerDependencies key={editor.work.harness} harness={editor.work.harness} language={language} active={active && moreSettingsOpen} onOperation={onOperation} />}
</div>}</section>
</Disclosure>
</section>
- {plan && <section className="editor-section"><div className="editor-section-heading"><div><h3>{text('在哪里使用', 'Where it is used')}</h3><p>{text('在 Agent 页面修改默认模型路由。', 'Change the default model route from the Agent page.')}</p></div></div>{usedBy.length ? <div className="agent-card-list">{usedBy.map(agent => <button className="agent-card" type="button" key={agent.id} onClick={() => onOpenAgent?.(agent.id)} disabled={!onOpenAgent}><BrandIcon kind={agent.brand} label={`${agent.name} logo`} /><div className="agent-main"><strong>{agent.name}</strong><span>{agent.isDefault ? text('主 Agent 默认使用', 'Default for main agent') : text('用于模型路由', 'Used for model routing')}</span></div><UiIcon name="chevronRight" /></button>)}</div> : <span className="muted plan-unused">{text('尚未被任何 Agent 用作模型路由', 'Not used by any agent for model routing yet')}</span>}</section>}
+ {plan && <section className="editor-section"><div className="editor-section-heading"><div><h3>{text('在哪里使用', 'Where it is used')}</h3><p>{text('在 Agent 页面调整模型路由。', 'Adjust model routing from the Agent page.')}</p></div></div>{usedBy.length ? <div className="agent-card-list">{usedBy.map(agent => <button className="agent-card" type="button" key={agent.id} onClick={() => onOpenAgent?.(agent.id)} disabled={!onOpenAgent}><BrandIcon kind={agent.brand} label={`${agent.name} logo`} /><div className="agent-main"><strong>{agent.name}</strong><span>{agent.isDefault ? text('主 Agent 默认使用', 'Default for main agent') : text('用于模型路由', 'Used for model routing')}</span></div><UiIcon name="chevronRight" /></button>)}</div> : <span className="muted plan-unused">{text('尚未被任何 Agent 用作模型路由', 'Not used by any agent for model routing yet')}</span>}</section>}
{plan && <section className="editor-section"><div className="editor-section-heading"><div><h3>{text('运行表现', 'Runtime performance')}</h3><p>{text('默认比较当前生效版本所选模型在时间范围内的阶段胜任度;未评分与部分证据会明确标出。', 'Compare stage competence over time for models selected by the active revision. Unrated and partial evidence remain explicit.')}</p></div></div><PlanQuality planId={plan.agent_plan_id} planRevision={plan.agent_plan_revision} currentModels={activePlanQualityModels(plan, options?.candidates ?? [])} language={language} onOpenEvidence={onOpenSession} /></section>}
diff --git a/apps/desktop/src/product/DesktopApp.tsx b/apps/desktop/src/product/DesktopApp.tsx
index 66864718..ab2188d3 100644
--- a/apps/desktop/src/product/DesktopApp.tsx
+++ b/apps/desktop/src/product/DesktopApp.tsx
@@ -35,6 +35,7 @@ import { RoutingPage, type RoutingEditorIntent } from './RoutingPage';
import { SettingsPage } from './SettingsPage';
import { useDesktopHome } from './use-desktop-home';
import { safeDiagnosticCode } from '../error-code';
+import { planErrorMessage } from '../plan-editor-errors';
import {
acceptObservedOperation,
currentPendingHint,
@@ -77,6 +78,7 @@ function failureCode(error: unknown): string {
}
function failureHelp(code: string, language: 'zh' | 'en'): string {
+ if (code === 'QODER_MODEL_BUDGET_CONFLICT') return planErrorMessage(code, language);
const messages: Record<string, [string, string]> = {
CONFIRMATION_EXPIRED: ['确认已过期,请重新预览。输入已保留。', 'Confirmation expired. Preview again; your input is retained.'],
CONFIRMATION_STALE: ['确认已失效,请重新预览。', 'This confirmation is no longer valid. Preview again.'],
diff --git a/apps/desktop/src/product/RoutingPage.tsx b/apps/desktop/src/product/RoutingPage.tsx
index 59db685d..15bdb08f 100644
--- a/apps/desktop/src/product/RoutingPage.tsx
+++ b/apps/desktop/src/product/RoutingPage.tsx
@@ -6,6 +6,8 @@ import { requestEditorReplacement } from '../ui/discard-guard';
import { ProductPage, UiIcon } from '../ui';
import type { DesktopOperation, DesktopSnapshot } from './home-projections';
import type { AgentSnapshot } from '../agents';
+import { agentModelStatus } from '../features/agents/status';
+import { agentBrand, agentDisplayName } from '../features/agents/ecosystems';
import { routingEditorEntries } from '../routing-editor-entries';
export type RoutingEditorIntent = { key: string; plan?: Plan; draft?: Draft; staleDraft?: boolean; initialBindingId?: string; editingMemory?: PlanEditorMemory };
@@ -111,19 +113,17 @@ export function RoutingPage({ language, active = true, snapshot, agentSnapshot,
setEditor({ key: crypto.randomUUID(), editingMemory: {} });
setShowList(false);
}
- const agentName = (agentId: string) => agentId === 'agent_codex_default' ? 'Codex' : agentId === 'agent_claude_default' ? 'Claude Code' : text('本机 Agent', 'Local Agent');
- const agentBrand = (agentId: string) => agentId.toLowerCase().includes('codex') ? 'codex' as const : agentId.toLowerCase().includes('claude') ? 'claude-code' as const : 'agent' as const;
const usedBy = editor?.plan ? (agentSnapshot?.agents ?? []).flatMap(agent => {
- const model = agent.settings?.current_selection;
+ const model = agentModelStatus(agent)?.current_selection;
const isDefault = model?.mode === 'codex_default'
&& model.default_selection.kind === 'plan'
&& model.default_selection.plan_id === editor.plan!.agent_plan_id;
- const isAllowed = model?.mode === 'codex_default'
+ const isAllowed = model?.mode === 'codex_default' || model?.mode === 'qoder_additional'
? model.allowed_plan_ids.includes(editor.plan!.agent_plan_id)
: model?.mode === 'claude_launcher'
? Object.values(model.preset_mappings).some(selection => selection.kind === 'plan' && selection.plan_id === editor.plan!.agent_plan_id)
: false;
- return isDefault || isAllowed ? [{ id: agent.agent_id, name: agentName(agent.agent_id), brand: agentBrand(agent.agent_id), isDefault }] : [];
+ return isDefault || isAllowed ? [{ id: agent.agent_id, name: agentDisplayName(agent.agent_id, language), brand: agentBrand(agent.agent_id), isDefault }] : [];
}) : [];
const pageLocked = busy || localBusy || editorBusy || !mutable;
const pageActions = creating ? <>
diff --git a/apps/desktop/src/product/home-projections.ts b/apps/desktop/src/product/home-projections.ts
index 7017016d..80a30ae8 100644
--- a/apps/desktop/src/product/home-projections.ts
+++ b/apps/desktop/src/product/home-projections.ts
@@ -1,4 +1,5 @@
import type { Agent, AgentSnapshot } from '../agents';
+import { agentHasNoModelConnection, agentModelStatus } from '../features/agents/status.ts';
import type {
HomeActivity,
HomeAgents,
@@ -169,8 +170,7 @@ export function projectHomeCompute(snapshot: ManagementSnapshot): HomeCompute {
};
}
-function facet(state: string | undefined, verified = false): HomeFacetState {
- if (verified) return 'verified';
+function facet(state: string | undefined): HomeFacetState {
if (!state || state === 'not_configured' || state === 'restored') return 'unconfigured';
if (state === 'configured') return 'configured';
if (state === 'pending') return 'pending';
@@ -180,21 +180,21 @@ function facet(state: string | undefined, verified = false): HomeFacetState {
}
function projectAgent(agent: Agent): HomeAgents['agents'][number] {
+ const model = agentModelStatus(agent);
const normalized = agent.agent_id.toLowerCase();
const brand = normalized.includes('codex')
? 'codex'
- : normalized.includes('claude') ? 'claude-code' : 'agent';
+ : normalized.includes('claude') ? 'claude-code' : normalized.includes('qoder') ? 'qoder' : 'agent';
return {
agentId: agent.agent_id,
contextId: agent.context_id ?? undefined,
displayName: agent.agent_id === 'agent_codex_default'
? 'Codex'
- : agent.agent_id === 'agent_claude_default' ? 'Claude Code' : agent.agent_id,
+ : agent.agent_id === 'agent_claude_default' ? 'Claude Code'
+ : agent.agent_id === 'agent_qoder_default' ? 'Qoder' : agent.agent_id,
brand,
- model: facet(
- agent.settings?.state ?? agent.configuration_state,
- agent.settings?.model_verified === true,
- ),
+ model: agentHasNoModelConnection(agent) ? 'unsupported'
+ : model ? facet(model.state) : 'unknown',
collaboration: facet(agent.settings?.collaboration?.state),
safeIssue: agent.status_error ?? undefined,
};
diff --git a/apps/desktop/src/ui/BrandIcon.tsx b/apps/desktop/src/ui/BrandIcon.tsx
index cf3585ce..b0e82ef9 100644
--- a/apps/desktop/src/ui/BrandIcon.tsx
+++ b/apps/desktop/src/ui/BrandIcon.tsx
@@ -4,13 +4,15 @@
import codexDark from './assets/codex-dark.png?inline';
import codexLight from './assets/codex-light.png?inline';
import claudeCode from './assets/claude-code.svg';
+import qoder from './assets/qoder.svg';
-export type BrandKind = 'codex' | 'claude-code' | 'agent' | 'model';
+export type BrandKind = 'codex' | 'claude-code' | 'qoder' | 'agent' | 'model';
export function agentBrandFromId(agentId: string): BrandKind {
const normalized = agentId.toLowerCase();
if (normalized.includes('codex')) return 'codex';
if (normalized.includes('claude')) return 'claude-code';
+ if (normalized.includes('qoder')) return 'qoder';
return 'agent';
}
@@ -45,6 +47,12 @@ export function BrandIcon({
);
}
+ if (kind === 'qoder') {
+ return <span className={classes} data-size={size} data-brand="qoder" {...accessibility}>
+ <img src={qoder} alt="" />
+ </span>;
+ }
+
return (
<span className={classes} data-size={size} data-brand={kind} {...accessibility}>
<svg viewBox="0 0 48 48" fill="none" aria-hidden="true">
diff --git a/apps/desktop/src/ui/assets/BRAND_ASSETS.md b/apps/desktop/src/ui/assets/BRAND_ASSETS.md
index bb115ca0..a75efeea 100644
--- a/apps/desktop/src/ui/assets/BRAND_ASSETS.md
+++ b/apps/desktop/src/ui/assets/BRAND_ASSETS.md
@@ -16,6 +16,13 @@ These assets identify third-party Agent integrations inside HiRoute. They do not
- SHA-256: `059e22f525d67c6258c4f64514f0b0e717c914df8a706936d0299d5e6b8082d9`.
- Conditions: the SVG is copied without shape or color changes and appears only with the accurate Claude Code product name. Anthropic owns the mark; this nominative integration label does not imply endorsement.
+## Qoder
+
+- File: `qoder.svg`
+- Source: the official Qoder website icon, <https://qoder.com/favIcon.svg>, retrieved 2026-10-04.
+- SHA-256: `5e1843cb50c4613855024453e76d5c06d2ca5562efebc12b4fcd80cf9ece1dd0`.
+- The SVG is copied without shape or color changes and appears beside the Qoder name to identify the integration. The mark belongs to Qoder and does not imply endorsement.
+
## Fallback
Unknown Agents use HiRoute's neutral inline `Agent` glyph plus their returned display name. A missing known asset is treated as an incomplete integration and must not fall back to initials such as `CX` or `CC`.
diff --git a/apps/desktop/src/ui/assets/qoder.svg b/apps/desktop/src/ui/assets/qoder.svg
new file mode 100644
index 00000000..599212e5
--- /dev/null
+++ b/apps/desktop/src/ui/assets/qoder.svg
@@ -0,0 +1,5 @@
+<svg width="206" height="206" viewBox="0 0 206 206" fill="none" xmlns="http://www.w3.org/2000/svg">
+<rect width="206" height="206" rx="52" fill="#F3F3F3"/>
+<path fill-rule="evenodd" clip-rule="evenodd" d="M104.003 35.8361C104.122 35.8899 104.223 35.938 104.308 35.9805C104.575 36.1139 104.784 36.2211 104.937 36.3023L154.881 62.632L154.9 62.6418C154.992 62.6907 155.084 62.7426 155.173 62.7973C160.753 65.8115 165.083 70.1612 168.163 75.8464C171.221 81.491 172.75 87.925 172.75 95.1484V117.637C172.75 117.795 172.743 117.954 172.728 118.111V158.251C172.728 163.577 170.488 167.682 166.008 170.563C161.529 173.445 156.866 173.781 152.021 171.573L143.479 167.682L143.449 167.699L143.279 167.796C143.276 167.798 143.237 167.821 143.159 167.867C142.593 168.202 142.154 168.454 141.84 168.625C141.789 168.654 141.686 168.709 141.532 168.79C141.479 168.819 141.443 168.837 141.426 168.846L141.174 168.979C140.759 169.203 140.355 169.414 139.961 169.61L139.342 169.911L139.192 169.982C138.849 170.145 138.46 170.326 138.025 170.524L137.252 170.86C136.994 170.973 136.623 171.127 136.137 171.32L136.002 171.374L135.892 171.42C135.835 171.443 135.78 171.466 135.725 171.488C135.49 171.584 135.294 171.661 135.137 171.716C134.872 171.814 134.453 171.961 133.881 172.16L133.879 172.161L133.715 172.219C133.549 172.28 133.366 172.342 133.165 172.407C132.571 172.603 131.9 172.805 131.151 173.012L127.646 173.973C126.996 174.153 126.392 174.306 125.833 174.432L125.437 174.515L125.039 174.596C124.663 174.676 124.363 174.738 124.139 174.782C124.007 174.809 123.855 174.836 123.681 174.864C123.646 174.869 123.625 174.872 123.619 174.874L123.11 174.956C123.106 174.957 123.084 174.961 123.044 174.967C122.729 175.02 122.483 175.059 122.304 175.085C122.178 175.104 121.986 175.129 121.727 175.159L121.331 175.209L120.674 175.285C120.526 175.302 120.362 175.317 120.18 175.33L120.066 175.341L120.015 175.345C119.546 175.384 119.175 175.411 118.903 175.426C118.815 175.433 118.717 175.438 118.608 175.443L118.645 175.439C118.497 175.452 118.347 175.459 118.198 175.459H118.137C117.737 175.478 117.398 175.487 117.121 175.487H116.455C116.418 175.487 116.381 175.487 116.344 175.486C116.298 175.485 116.224 175.484 116.122 175.483C115.843 175.479 115.623 175.473 115.461 175.466C115.335 175.462 115.132 175.452 114.852 175.434L114.824 175.432L114.654 175.426L114.273 175.407C114.212 175.404 114.15 175.399 114.088 175.394L113.388 175.332C112.948 175.29 112.527 175.243 112.124 175.19L111.925 175.166C111.882 175.162 111.839 175.155 111.796 175.149C111.339 175.081 110.875 175.005 110.403 174.921L109.901 174.827L109.871 174.821C109.63 174.777 109.429 174.736 109.27 174.698L109.224 174.687L109.158 174.672L109.037 174.644C108.61 174.549 108.15 174.435 107.656 174.301L107.629 174.294C107.5 174.263 107.358 174.226 107.201 174.181L107.2 174.181C106.608 174.013 106.029 173.831 105.463 173.634C105.307 173.586 105.154 173.53 105.004 173.466L104.884 173.42C104.405 173.241 104.002 173.083 103.675 172.948C103.58 172.909 103.469 172.861 103.342 172.804C103.29 172.781 103.261 172.768 103.255 172.766L103.084 172.692C102.756 172.551 102.39 172.384 101.986 172.19L101.906 172.152L101.891 172.145C101.798 172.103 101.715 172.063 101.64 172.025C101.571 171.99 101.501 171.955 101.431 171.918C101.407 171.906 101.386 171.895 101.369 171.886C101.249 171.835 101.13 171.778 101.012 171.716L101.009 171.715L51.5574 145.645C51.215 145.509 50.8889 145.336 50.5849 145.128C48.367 143.914 46.3274 142.453 44.4659 140.744C44.4647 140.743 44.4635 140.742 44.4623 140.741C44.4584 140.737 44.4546 140.734 44.4507 140.73C44.4362 140.717 44.4214 140.704 44.4064 140.69C43.6029 139.953 42.8113 139.14 42.0317 138.252C42.0244 138.243 42.0171 138.235 42.0097 138.226C42.0082 138.224 42.0067 138.222 42.0051 138.22C41.5797 137.727 41.1892 137.252 40.8338 136.795C40.7387 136.672 40.6464 136.551 40.5567 136.432C35.6857 129.988 33.2502 122.172 33.2502 112.983V90.4946C33.2502 89.8308 33.2644 89.0633 33.2927 88.1921C33.3022 87.9838 33.3174 87.7494 33.3384 87.4888C33.3459 87.3951 33.3511 87.3283 33.3539 87.2882C33.3866 86.7286 33.4259 86.2074 33.4719 85.7247C33.4848 85.5587 33.5136 85.2969 33.5583 84.9392C33.5691 84.8524 33.5769 84.7892 33.5817 84.7498C33.589 84.6881 33.6006 84.5877 33.6166 84.4487C33.672 83.9681 33.7187 83.5958 33.7569 83.3318C33.7999 83.0465 33.8556 82.7028 33.9239 82.3007C33.9303 82.2616 33.9429 82.1836 33.9618 82.0668C34.0386 81.5927 34.1025 81.2235 34.1537 80.9593C34.1539 80.9576 34.1542 80.9559 34.1545 80.9542L34.1507 80.9713C34.1669 80.871 34.1817 80.7851 34.1951 80.7134C34.3125 80.1121 34.4286 79.5636 34.5433 79.0679C34.5554 79.0129 34.5689 78.9553 34.5837 78.895C34.704 78.3592 34.8544 77.7535 35.0349 77.078C35.0683 76.9444 35.1121 76.78 35.1663 76.5847C35.1764 76.5481 35.1839 76.5212 35.1886 76.5042C35.4221 75.6865 35.6047 75.0694 35.7364 74.653C35.7408 74.639 35.7453 74.6249 35.7499 74.6109C35.7573 74.5867 35.7647 74.5627 35.7723 74.539C35.7789 74.517 35.7857 74.495 35.7926 74.473C35.8241 74.3734 35.8643 74.2549 35.9134 74.1174L35.9251 74.085C36.1639 73.3479 36.3895 72.6905 36.6021 72.1127C36.6575 71.9603 36.7417 71.7385 36.8547 71.4475C36.8818 71.3777 36.9019 71.3258 36.9151 71.2917C36.9324 71.247 36.9593 71.177 36.9959 71.0817C37.2171 70.5062 37.3921 70.0651 37.5208 69.7585L37.5168 69.7661C37.5549 69.6676 37.5905 69.5789 37.6236 69.5C37.6858 69.3466 37.7661 69.1613 37.8644 68.944C37.8998 68.8657 37.9232 68.8133 37.9347 68.7869C38.152 68.2878 38.3184 67.9104 38.4338 67.6548C38.5471 67.4055 38.7105 67.0593 38.9238 66.6163C38.9706 66.5208 39.03 66.3991 39.1019 66.2511C39.2648 65.9163 39.392 65.6588 39.4835 65.4786L39.5155 65.4136C39.5653 65.3091 39.6106 65.2167 39.6516 65.1362C39.7258 64.9869 39.8207 64.8074 39.9362 64.5977C39.9744 64.5283 39.9996 64.4822 40.0115 64.4596C40.0477 64.3922 40.0935 64.3066 40.1489 64.2029C40.3258 63.872 40.463 63.6187 40.5605 63.4432C40.7672 63.0697 40.9619 62.726 41.1445 62.4123C41.2987 62.1332 41.489 61.8063 41.7152 61.4316C41.7383 61.3935 41.7619 61.3555 41.786 61.318L41.7824 61.323C41.7846 61.3193 41.7867 61.3156 41.7888 61.3118L41.7824 61.323C41.8335 61.2318 41.8771 61.1561 41.9132 61.0959C42.0161 60.9245 42.159 60.697 42.342 60.4136C42.5227 60.1209 42.7188 59.811 42.9304 59.484C43.0841 59.2469 43.3076 58.9123 43.601 58.4804L43.9154 58.0238L44.2115 57.5939C44.2325 57.5634 44.2537 57.5333 44.2753 57.5034L44.2749 57.5021C44.3548 57.3822 44.4252 57.2801 44.4861 57.1958C44.5458 57.1108 44.6445 56.9765 44.7821 56.7929C44.8446 56.7095 44.8877 56.6514 44.9115 56.6186C45.2257 56.1886 45.4678 55.8625 45.6377 55.6403L45.9946 55.1837L46.3262 54.7597C46.5387 54.4816 46.7902 54.1653 47.0808 53.811C47.0969 53.7914 47.1242 53.7575 47.1628 53.7094C47.2305 53.6246 47.2851 53.5571 47.3267 53.5067C47.4115 53.4034 47.53 53.264 47.6821 53.0885C47.7338 53.0289 47.771 52.9858 47.7938 52.9593C47.8766 52.8642 47.9852 52.7384 48.1197 52.582C48.3585 52.3041 48.544 52.0909 48.6764 51.9423L49.3723 51.1748C49.5804 50.9454 49.8853 50.6178 50.2869 50.1921C50.3199 50.1572 50.3534 50.1227 50.3874 50.0888L50.3985 50.0741C50.5274 49.9324 50.6395 49.8139 50.7349 49.7185C50.7855 49.6679 50.8533 49.6012 50.9383 49.5185C50.99 49.4683 51.0247 49.4343 51.0424 49.4165C51.4915 48.9675 51.9017 48.5656 52.2729 48.2107C52.3283 48.1583 52.4007 48.0891 52.49 48.0029C52.6771 47.8224 52.8271 47.6806 52.9399 47.5775C53.3761 47.1664 53.9052 46.6923 54.5271 46.155C54.5279 46.1543 54.5287 46.1536 54.5295 46.1528L54.5189 46.161C54.617 46.0697 54.7025 45.9924 54.7754 45.9292C54.8391 45.8741 54.904 45.8206 54.9705 45.7688C54.997 45.7476 55.0236 45.7269 55.0503 45.7065L55.0774 45.6851L55.0939 45.6717C55.5288 45.3081 55.9911 44.9311 56.4808 44.5407C56.5166 44.5125 56.5529 44.4839 56.5898 44.4548C56.7923 44.2954 56.9507 44.1724 57.0648 44.0858C57.2979 43.9051 57.6655 43.6275 58.1675 43.253C58.2075 43.2232 58.2479 43.1939 58.2888 43.1654C58.3729 43.1065 58.5143 43.0042 58.7128 42.8586C59.1025 42.577 59.5704 42.2518 60.1163 41.883L60.1145 41.8841L60.1593 41.8524C60.2852 41.7638 60.3942 41.6892 60.4862 41.6287C60.5329 41.5967 60.5792 41.5661 60.6251 41.5367C61.2865 41.1057 61.8541 40.7475 62.3278 40.4623C62.4222 40.4035 62.5743 40.3142 62.7839 40.1944C62.7838 40.1941 62.8182 40.1736 62.8873 40.1328C63.453 39.7986 63.8928 39.5462 64.2065 39.3754L64.8387 39.0383L64.872 39.0207C65.2867 38.7973 65.6911 38.5871 66.0852 38.39C66.2669 38.2991 66.5247 38.1744 66.8586 38.0158C67.1979 37.8542 67.5857 37.6746 68.0218 37.477L68.4373 37.2954L68.7948 37.1398C69.0934 37.0111 69.5097 36.84 70.0435 36.6265C70.1097 36.6005 70.1844 36.5712 70.2678 36.5384C70.5114 36.4427 70.6998 36.3699 70.833 36.3199C71.1527 36.2027 71.5991 36.0447 72.1722 35.8457C72.2132 35.8316 72.2719 35.8109 72.3482 35.7837C72.574 35.7031 72.7593 35.64 72.904 35.5945C73.5201 35.3928 74.1846 35.1929 74.8975 34.9948L78.4057 34.0333C79.0348 33.8574 79.6373 33.7044 80.2131 33.5744C80.378 33.5359 80.5868 33.4913 80.8395 33.4407C81.1612 33.3685 81.5282 33.2925 81.9406 33.2127C82.0871 33.1842 82.2808 33.151 82.5216 33.1131C82.5981 33.101 82.6517 33.0924 82.6826 33.0873C82.7524 33.0758 82.852 33.0591 82.9815 33.0372C83.2985 32.9834 83.5459 32.9435 83.7238 32.9177C83.7635 32.9119 83.8033 32.9066 83.8432 32.9018L84.1737 32.8619L84.504 32.822C84.5516 32.8162 84.6345 32.8056 84.7525 32.7903C85.0348 32.7538 85.2559 32.7271 85.4158 32.7105C85.5254 32.6991 85.6353 32.6913 85.7453 32.6873L86.07 32.6632C86.533 32.6238 86.9091 32.5967 87.1982 32.582C87.3378 32.5734 87.5561 32.5646 87.8533 32.5556L87.8692 32.5551C87.9598 32.5532 88.0717 32.5499 88.205 32.5453C88.4606 32.5364 88.6706 32.5314 88.835 32.5303C88.9748 32.5275 89.1472 32.5271 89.3523 32.529L89.537 32.5302C89.6342 32.5318 89.7388 32.5334 89.851 32.5349C90.1448 32.5389 90.3757 32.5444 90.5436 32.5514C90.6803 32.5549 90.9082 32.5655 91.2273 32.5832C91.2891 32.5871 91.3656 32.5912 91.4568 32.5957C91.6011 32.6026 91.7158 32.6089 91.8012 32.6144C91.9206 32.6204 92.0953 32.6356 92.3254 32.6598L92.6313 32.6871C93.0373 32.7257 93.4523 32.7724 93.8761 32.8271L93.8896 32.8288L93.8913 32.829C94.0015 32.8408 94.0983 32.8527 94.1819 32.8646C94.6093 32.9223 95.085 32.9984 95.6089 33.093C95.6739 33.1047 95.7386 33.1178 95.8031 33.1321L95.8062 33.1318C95.8842 33.1466 95.9548 33.1606 96.0179 33.1737C96.0408 33.1779 96.0713 33.1835 96.1093 33.1905C96.3333 33.2314 96.5177 33.2683 96.6627 33.301C96.7395 33.3173 96.8375 33.3418 96.9566 33.3744C96.9806 33.3797 97.0046 33.385 97.0288 33.3903C97.2476 33.4387 97.4749 33.4924 97.7107 33.5517C97.9063 33.6006 98.1067 33.6529 98.3119 33.7085L98.3072 33.7071L98.3401 33.7149C98.4501 33.742 98.5513 33.7682 98.6438 33.7934C98.6594 33.7976 98.6743 33.8018 98.6886 33.8058C98.7485 33.8224 98.8045 33.8387 98.8566 33.8545C98.8608 33.8557 98.865 33.8569 98.8692 33.8581C99.3732 34.0019 99.9241 34.1774 100.522 34.3846C100.548 34.3932 100.574 34.4019 100.6 34.4109C100.733 34.4556 100.881 34.5109 101.044 34.5769C101.508 34.7451 101.931 34.9089 102.311 35.0684C102.368 35.0928 102.417 35.1139 102.459 35.1317C102.655 35.2169 102.808 35.2839 102.918 35.3328C103.261 35.4856 103.61 35.6469 103.963 35.8169L104.003 35.8361ZM101.032 34.5728L101.03 34.5721C101.033 34.573 101.035 34.5739 101.038 34.5748C101.036 34.5741 101.034 34.5735 101.032 34.5728ZM104.903 162.561L105.666 162.963C105.717 162.991 105.807 163.037 105.935 163.102C105.972 163.121 106.002 163.136 106.025 163.148C106.092 163.178 106.131 163.197 106.145 163.205L106.281 163.269C106.554 163.401 106.811 163.519 107.052 163.622L107.063 163.627C107.148 163.663 107.253 163.708 107.38 163.765C107.425 163.785 107.449 163.796 107.452 163.797C107.68 163.891 107.998 164.015 108.408 164.169L108.458 164.189C108.52 164.211 108.58 164.234 108.641 164.257L108.655 164.263C109.054 164.403 109.476 164.536 109.919 164.661C109.914 164.66 109.885 164.654 109.835 164.643C109.904 164.659 109.973 164.675 110.041 164.693L110.249 164.747C110.596 164.84 110.948 164.927 111.306 165.008L111.379 165.025L111.451 165.041L111.564 165.067L111.672 165.086L111.703 165.092L112.139 165.174C112.496 165.238 112.847 165.295 113.191 165.347L113.391 165.372C113.685 165.41 113.977 165.443 114.269 165.47L114.88 165.525L115.066 165.535L115.442 165.551L115.47 165.553C115.644 165.565 115.787 165.572 115.899 165.576C115.964 165.579 116.087 165.581 116.267 165.584C116.363 165.585 116.443 165.586 116.506 165.587H117.121C117.26 165.587 117.474 165.58 117.764 165.566C117.848 165.561 117.932 165.559 118.015 165.559H118.037C118.081 165.557 118.126 165.555 118.174 165.552L118.156 165.555C118.215 165.55 118.274 165.546 118.334 165.542C118.501 165.534 118.779 165.514 119.169 165.481L119.325 165.467C119.376 165.462 119.427 165.458 119.479 165.455C119.506 165.453 119.53 165.451 119.549 165.449L120.088 165.388L120.592 165.324C120.728 165.308 120.832 165.295 120.904 165.284C121.005 165.27 121.174 165.243 121.411 165.203C121.454 165.196 121.491 165.19 121.522 165.185L121.924 165.119C121.976 165.11 122.042 165.1 122.123 165.087L122.114 165.091C122.152 165.082 122.191 165.074 122.23 165.067C122.398 165.035 122.677 164.977 123.068 164.895L123.398 164.828L123.653 164.775C124.058 164.683 124.517 164.567 125.03 164.425L128.507 163.472C129.101 163.307 129.652 163.141 130.162 162.973C130.219 162.955 130.253 162.943 130.266 162.939C130.308 162.922 130.35 162.907 130.393 162.892L130.632 162.808H130.634C131.154 162.628 131.551 162.487 131.825 162.387C131.834 162.383 131.882 162.364 131.971 162.328C132.052 162.295 132.097 162.276 132.106 162.273L132.326 162.182C132.367 162.166 132.414 162.147 132.467 162.126C132.853 161.972 133.13 161.858 133.299 161.784L133.938 161.506C134.318 161.334 134.65 161.181 134.935 161.045L135.024 161.003L135.533 160.756C135.838 160.604 136.178 160.426 136.553 160.224L136.711 160.141C136.766 160.112 136.839 160.073 136.929 160.025C136.993 159.992 137.052 159.961 137.107 159.93C137.318 159.814 137.658 159.619 138.125 159.343C138.192 159.304 138.261 159.263 138.332 159.221L138.46 159.147H138.461C138.544 159.098 138.619 159.055 138.687 159.017C139.131 158.749 139.551 158.484 139.947 158.224L140.305 157.979C141.736 157.002 143.572 156.845 145.148 157.563L156.125 162.564C157.693 163.279 159.202 163.17 160.652 162.237C162.103 161.304 162.828 159.976 162.828 158.251V117.614C162.828 117.456 162.835 117.298 162.85 117.14V95.1484C162.85 83.7403 158.651 75.8219 150.254 71.3934L149.959 71.2374C149.909 71.2132 149.855 71.1867 149.796 71.158C149.721 71.1217 149.663 71.0932 149.62 71.0724C149.384 70.9567 149.129 70.8386 148.853 70.718C148.676 70.6389 148.548 70.5828 148.468 70.5496C148.234 70.4515 147.944 70.3392 147.597 70.2126L147.415 70.1456L147.313 70.1067C146.939 69.9768 146.534 69.8488 146.096 69.7227L145.999 69.6973L145.777 69.6395C145.321 69.5221 144.979 69.4377 144.751 69.3863C144.724 69.3805 144.683 69.3717 144.629 69.3597C144.371 69.3034 144.185 69.2642 144.072 69.242C144.03 69.2339 143.989 69.2253 143.948 69.2162L143.83 69.1927C143.449 69.1241 143.093 69.0673 142.761 69.0223C142.792 69.0267 142.81 69.0291 142.814 69.0296C142.703 69.0177 142.628 69.0088 142.589 69.0029C142.287 68.9641 141.996 68.931 141.716 68.9037L141.71 68.9033L141.383 68.8734C141.233 68.8611 140.993 68.845 140.663 68.8252C140.435 68.8126 140.276 68.805 140.186 68.8025C140.128 68.8008 140.071 68.7982 140.014 68.7947C139.934 68.7897 139.76 68.7873 139.491 68.7873L138.982 68.7863C138.823 68.7894 138.572 68.7974 138.23 68.8105C138.13 68.8157 138.008 68.8205 137.866 68.8249C137.791 68.8271 137.731 68.8296 137.686 68.8322C137.515 68.8408 137.229 68.8619 136.827 68.8954L136.781 68.899C136.729 68.9029 136.661 68.9074 136.577 68.9127L136.442 68.9231C136.355 68.9316 136.204 68.9492 135.988 68.9761C135.849 68.9934 135.758 69.0044 135.717 69.0091C135.625 69.0209 135.503 69.035 135.352 69.0513C135.248 69.0625 135.179 69.0706 135.146 69.0756C135.049 69.09 134.884 69.1175 134.65 69.158C134.503 69.1832 134.384 69.2036 134.291 69.219C134.229 69.2289 134.145 69.2422 134.038 69.2587C133.907 69.2786 133.814 69.2938 133.759 69.3042C133.645 69.3251 133.444 69.3668 133.157 69.4293C133.028 69.4574 132.949 69.4744 132.92 69.4802C132.827 69.5013 132.7 69.5285 132.54 69.5617C132.451 69.5801 132.403 69.5901 132.396 69.5916C131.906 69.7035 131.445 69.8191 131.014 69.9384L127.538 70.8908C126.968 71.049 126.455 71.2026 125.998 71.3517L125.707 71.4525L125.352 71.575C124.951 71.7086 124.6 71.8325 124.3 71.9467C124.181 71.9913 123.979 72.0708 123.693 72.1852C123.284 72.3461 122.971 72.4736 122.752 72.5678L122.104 72.8516C121.973 72.9113 121.833 72.9757 121.684 73.0449V91.2807C121.684 92.0491 121.665 92.8184 121.628 93.5885C121.622 93.7365 121.609 93.9283 121.591 94.1637L121.59 94.1679L121.571 94.4471L121.57 94.4744C121.528 95.1281 121.491 95.6208 121.457 95.9524C121.439 96.1399 121.414 96.3666 121.381 96.6324L121.329 97.0655C121.322 97.1194 121.312 97.2021 121.299 97.3136C121.248 97.7482 121.207 98.0619 121.178 98.255C121.155 98.4224 121.12 98.6496 121.074 98.9367C121.068 98.9704 121.065 98.9883 121.065 98.9905L121.009 99.3453L121.009 99.3467C120.917 99.902 120.844 100.324 120.788 100.612C120.661 101.278 120.528 101.923 120.389 102.547L120.362 102.657C120.224 103.259 120.071 103.869 119.902 104.487L119.761 104.999C119.578 105.652 119.397 106.263 119.219 106.83L119.068 107.297C118.85 107.97 118.629 108.613 118.405 109.225C118.356 109.361 118.29 109.536 118.205 109.751L118.188 109.793L118.192 109.783L118.08 110.078C118.063 110.121 118.039 110.184 118.007 110.266C117.79 110.827 117.625 111.244 117.512 111.517C117.449 111.674 117.358 111.889 117.239 112.163C117.192 112.273 117.165 112.336 117.158 112.351L117.095 112.503C116.916 112.924 116.752 113.292 116.603 113.609C116.52 113.796 116.401 114.053 116.244 114.381C116.192 114.49 116.148 114.584 116.109 114.664C116.087 114.71 116.055 114.778 116.011 114.868C115.823 115.258 115.676 115.559 115.568 115.77C115.376 116.148 115.2 116.486 115.04 116.784L114.726 117.371L114.51 117.768C114.385 117.994 114.197 118.325 113.947 118.761C113.932 118.786 113.907 118.83 113.871 118.893C113.665 119.251 113.496 119.536 113.364 119.749C113.175 120.066 112.975 120.389 112.764 120.718C112.747 120.745 112.719 120.789 112.68 120.851C112.458 121.207 112.294 121.463 112.191 121.62C112.082 121.789 111.924 122.028 111.715 122.339C111.63 122.465 111.557 122.575 111.495 122.666L111.474 122.698L110.894 123.543L110.828 123.635L110.248 124.44C110.006 124.774 109.774 125.086 109.554 125.376C109.374 125.614 109.136 125.921 108.838 126.296C108.792 126.354 108.722 126.444 108.626 126.564C108.415 126.831 108.255 127.032 108.146 127.165C107.99 127.358 107.765 127.627 107.472 127.971L107.432 128.017L107.427 128.022C107.169 128.329 106.885 128.659 106.573 129.01C106.415 129.187 106.185 129.443 105.883 129.777C105.674 130.009 105.372 130.333 104.979 130.75C104.865 130.87 104.702 131.038 104.49 131.254C104.4 131.346 104.327 131.42 104.271 131.477C103.929 131.825 103.523 132.223 103.055 132.67L102.875 132.844L102.673 133.037L102.415 133.284C101.896 133.765 101.374 134.233 100.848 134.686L100.749 134.772L100.669 134.843L100.589 134.915C100.544 134.955 100.499 134.995 100.452 135.032L100.254 135.197C99.956 135.449 99.52 135.806 98.9463 136.268L98.9399 136.273C98.8505 136.346 98.7376 136.435 98.6012 136.539C98.551 136.577 98.5019 136.615 98.4539 136.652L98.3712 136.715C97.9722 137.023 97.5654 137.329 97.1506 137.632C97.1246 137.65 97.0729 137.688 96.9956 137.746C96.8643 137.844 96.7619 137.919 96.6886 137.971C96.2495 138.286 95.8236 138.581 95.4107 138.856L95.0917 139.078C95.0575 139.102 95.0231 139.126 94.9883 139.148C94.3982 139.537 93.7872 139.923 93.1553 140.305L93.1461 140.31C93.3774 150.816 97.2951 158.232 104.899 162.559C104.9 162.559 104.902 162.56 104.903 162.561ZM85.109 152.14C83.8619 148.186 83.2373 143.919 83.2353 139.337V137.521C83.2347 137.489 83.2344 137.458 83.2344 137.426V116.845C83.2344 116.045 83.2534 115.247 83.2913 114.451C83.2988 114.292 83.313 114.083 83.334 113.822C83.3415 113.729 83.3466 113.663 83.3493 113.626C83.3544 113.552 83.3621 113.44 83.3724 113.29C83.4083 112.76 83.4408 112.342 83.4697 112.035C83.4825 111.908 83.5022 111.733 83.5288 111.511C83.5477 111.353 83.5635 111.213 83.5763 111.091C83.5843 111.024 83.5963 110.921 83.6122 110.782C83.6676 110.301 83.7158 109.919 83.757 109.636C83.797 109.37 83.8504 109.041 83.917 108.649C83.9225 108.616 83.931 108.565 83.9424 108.496C84.0263 107.992 84.0935 107.6 84.144 107.32C84.2642 106.675 84.3948 106.043 84.5356 105.422C84.5486 105.362 84.5632 105.3 84.5794 105.234C84.5829 105.219 84.5864 105.203 84.59 105.188C84.7498 104.507 84.9083 103.874 85.0654 103.29C85.0711 103.27 85.0838 103.223 85.1035 103.148C85.1407 103.006 85.1675 102.907 85.1837 102.851C85.3667 102.187 85.5509 101.565 85.7364 100.984C85.7394 100.975 85.7425 100.965 85.7454 100.956C85.7604 100.907 85.7756 100.859 85.7911 100.812C85.8274 100.699 85.8714 100.57 85.9233 100.425C85.9267 100.416 85.9288 100.41 85.9293 100.409C86.1871 99.6224 86.4078 98.9796 86.5913 98.4808C86.651 98.3166 86.7374 98.0889 86.8505 97.7977C86.8777 97.7276 86.8935 97.687 86.8979 97.6759C87.1126 97.1079 87.3121 96.6018 87.4965 96.1574C87.5769 95.96 87.6945 95.6837 87.8495 95.3284C87.8867 95.2432 87.9153 95.1776 87.9353 95.1316C88.1491 94.6407 88.3155 94.2636 88.4344 94.0001C88.5435 93.7602 88.7034 93.4213 88.9141 92.9835C88.9155 92.9806 88.9169 92.9777 88.9182 92.9749C89.099 92.5951 89.2811 92.2247 89.4646 91.8639C89.5557 91.6816 89.689 91.4218 89.8645 91.0844C89.9194 90.9789 89.9656 90.8899 90.0032 90.8175C90.201 90.4424 90.3841 90.1034 90.5524 89.8004C90.7617 89.4223 90.9573 89.0771 91.1389 88.7647L91.4063 88.3047L91.7037 87.7941C91.8473 87.5548 92.0487 87.2295 92.3079 86.8181C92.4094 86.6532 92.5571 86.4188 92.7509 86.1149C92.8189 86.0084 92.8779 85.9158 92.9281 85.8371C93.0803 85.6022 93.2952 85.2806 93.5727 84.8722C93.8298 84.4867 94.0521 84.1637 94.2398 83.9033C94.4559 83.5971 94.6806 83.2865 94.9138 82.9715C95.2236 82.5476 95.4605 82.2284 95.6245 82.014C95.8073 81.7734 96.0476 81.4661 96.3452 81.0921L96.69 80.6582L97.0805 80.168C97.2347 79.9804 97.4631 79.7075 97.7656 79.3492L97.7895 79.3212C97.8343 79.2689 97.9023 79.1892 97.9935 79.0823C98.2842 78.7413 98.506 78.4851 98.6587 78.3137C98.8175 78.1339 99.0523 77.8728 99.3629 77.5304C99.5705 77.3015 99.8791 76.9701 100.289 76.536C100.534 76.2773 100.774 76.0318 101.006 75.7993C101.356 75.4442 101.766 75.0422 102.236 74.5932C102.529 74.3084 102.75 74.0982 102.898 73.9627C103.423 73.4747 103.975 72.9804 104.555 72.4797L104.568 72.4679C104.572 72.4646 104.575 72.4614 104.579 72.4582L104.568 72.4679C104.69 72.3555 104.78 72.2755 104.837 72.2279C104.93 72.1485 105.043 72.0556 105.178 71.9492C105.67 71.5386 106.104 71.1853 106.48 70.8893C106.615 70.7826 106.802 70.6384 107.041 70.4566C107.478 70.1188 107.863 69.8283 108.196 69.5852L108.738 69.1881C109.156 68.886 109.606 68.5732 110.088 68.2498C110.094 68.2454 110.111 68.2342 110.137 68.2159C110.281 68.1154 110.413 68.0272 110.532 67.9513C111.047 67.6097 111.632 67.2385 112.286 66.8376C112.329 66.8116 112.372 66.7861 112.415 66.7614C112.544 66.6878 112.642 66.6306 112.71 66.59C113.351 66.212 113.817 65.9444 114.107 65.7874C114.195 65.7371 114.288 65.6854 114.387 65.6323C114.427 65.6108 114.467 65.5899 114.507 65.5696C114.569 65.5368 114.639 65.5005 114.715 65.4606C114.784 65.425 114.833 65.3993 114.863 65.3835C115.228 65.1868 115.634 64.9766 116.082 64.7529C116.336 64.6259 116.591 64.5012 116.849 64.3787C117.279 64.1741 117.669 63.9926 118.018 63.8342L118.772 63.5029C119.128 63.3494 119.559 63.1731 120.064 62.9741C120.385 62.8458 120.638 62.7468 120.824 62.6771C121.224 62.5247 121.69 62.36 122.221 62.183L122.468 62.0972L122.76 61.9962C123.466 61.7648 124.175 61.5501 124.888 61.352L128.396 60.3905C128.613 60.3306 128.835 60.2715 129.063 60.213L100.3 45.0496C100.214 45.004 100.083 44.937 99.9066 44.8487C99.9047 44.8478 99.9027 44.8469 99.9007 44.846L99.9075 44.8496C99.7964 44.7991 99.6999 44.7535 99.6181 44.7129C99.4811 44.6472 99.3429 44.5824 99.2036 44.5184C99.1007 44.4713 98.9939 44.4231 98.8832 44.3739C98.8044 44.3386 98.6867 44.2871 98.53 44.2193C98.4876 44.201 98.455 44.1869 98.4322 44.177C98.4314 44.1767 98.4306 44.1763 98.4299 44.176C98.3382 44.1381 98.2427 44.0998 98.1433 44.061C97.9965 44.0041 97.8311 43.9427 97.6473 43.8766C97.5717 43.85 97.4776 43.814 97.3649 43.7686C97.3527 43.7645 97.3407 43.7603 97.3286 43.7561C96.8799 43.5998 96.4567 43.4648 96.059 43.3512L95.9727 43.3283C95.8926 43.3086 95.8272 43.2921 95.7763 43.2788C95.3802 43.1715 95.0531 43.0905 94.795 43.036C94.6972 43.0166 94.5792 42.9882 94.4409 42.9508C94.4084 42.9445 94.3714 42.9375 94.33 42.93C94.2346 42.9125 94.1589 42.8984 94.1029 42.8876C94.0584 42.8789 94.014 42.8697 93.9698 42.8599L93.9667 42.8601C93.9009 42.8477 93.8405 42.8359 93.7854 42.8246C93.4377 42.7625 93.1212 42.7121 92.8358 42.6733C92.725 42.6614 92.6275 42.6495 92.5435 42.6375C92.2732 42.6029 91.997 42.5722 91.7147 42.5453L91.3599 42.5131L91.2927 42.5057L91.289 42.5054L91.1859 42.4959C91.1239 42.4922 91.055 42.4886 90.9793 42.4849C90.835 42.478 90.7203 42.4717 90.6349 42.4662C90.4366 42.4553 90.292 42.4486 90.201 42.446C90.0797 42.4413 89.9183 42.4376 89.7169 42.4349C89.5824 42.433 89.4787 42.4313 89.4058 42.4298C89.4064 42.4305 89.3577 42.4304 89.26 42.4294C89.1424 42.4283 89.0705 42.4281 89.0444 42.4289C88.9973 42.4302 88.9501 42.4309 88.903 42.4309C88.8446 42.4309 88.7268 42.434 88.5495 42.4401C88.3825 42.4459 88.248 42.4499 88.1461 42.4522C87.9529 42.458 87.8209 42.4631 87.7499 42.4674C87.5399 42.4782 87.2415 42.5 86.8546 42.5328L86.5715 42.554L86.3409 42.5711C86.3298 42.572 86.3187 42.5728 86.3077 42.5735C86.2335 42.5825 86.1393 42.5944 86.0254 42.6091C85.8845 42.6274 85.7759 42.6412 85.6996 42.6505L85.3608 42.6915L85.0984 42.7231C84.9951 42.7388 84.8419 42.764 84.6388 42.7985C84.4899 42.8237 84.3759 42.8429 84.2967 42.8558C84.246 42.8643 84.1678 42.8768 84.0619 42.8935C83.9382 42.913 83.8599 42.9259 83.827 42.9323C83.5008 42.9954 83.1868 43.0605 82.885 43.1276C82.6666 43.172 82.5146 43.2042 82.429 43.2242C81.993 43.3228 81.5326 43.4398 81.0478 43.5754L77.5317 44.539C76.9734 44.6941 76.4388 44.8552 75.928 45.0223C75.8676 45.0416 75.7842 45.0701 75.6778 45.1081C75.5623 45.1493 75.4704 45.1817 75.4021 45.2051C74.8937 45.3817 74.5177 45.5145 74.2741 45.6037C74.2132 45.6267 74.085 45.6766 73.8895 45.7534C73.7991 45.7889 73.7301 45.816 73.6823 45.8346C73.2548 46.0058 72.9375 46.1359 72.7303 46.2251L72.3994 46.3693L72.0419 46.5249C71.7073 46.677 71.3972 46.821 71.1115 46.957L71.1072 46.9591C70.8335 47.0891 70.6356 47.1846 70.5135 47.2457C70.2089 47.398 69.8811 47.5686 69.5302 47.7576L69.4965 47.7756L68.9012 48.0927C68.7153 48.1941 68.3892 48.3824 67.9232 48.6577C67.8482 48.702 67.7923 48.735 67.7555 48.7567C67.6073 48.8417 67.518 48.8937 67.4876 48.9125C67.0806 49.1579 66.5958 49.4639 66.0332 49.8305C65.9931 49.8578 65.9533 49.8842 65.9139 49.9097L65.8575 49.9496C65.7862 49.9998 65.7282 50.0401 65.6836 50.0706C65.2073 50.3925 64.8258 50.657 64.5392 50.864C64.3368 51.0125 64.1686 51.1342 64.0344 51.2291C63.607 51.5482 63.2914 51.7866 63.0876 51.9444C62.9946 52.0152 62.8699 52.1121 62.7135 52.2352C62.6748 52.2656 62.6456 52.2887 62.6258 52.3042C62.2109 52.635 61.8299 52.9455 61.4827 53.2357C61.4226 53.2875 61.3346 53.3593 61.2187 53.4512C61.1402 53.5238 61.0704 53.5865 61.0095 53.6393C60.4881 54.0895 60.0428 54.4885 59.6734 54.8362C59.591 54.912 59.488 55.0095 59.3645 55.1286C59.248 55.241 59.1565 55.3286 59.0899 55.3914C58.7889 55.6792 58.4401 56.0213 58.0437 56.4178C57.9931 56.4684 57.9253 56.535 57.8403 56.6177C57.7886 56.6679 57.7539 56.7019 57.7362 56.7197L57.7249 56.7344C57.6255 56.8437 57.536 56.9393 57.4565 57.0211C57.1154 57.3829 56.865 57.6517 56.7055 57.8275L56.0398 58.5614C55.9662 58.6442 55.8292 58.8023 55.6287 59.0355C55.4778 59.2111 55.3624 59.3447 55.2825 59.4363C55.2667 59.4549 55.227 59.5009 55.1632 59.5745C55.0686 59.6836 55.0053 59.7575 54.9736 59.7962C54.9593 59.8136 54.9328 59.8464 54.8943 59.8946C54.8265 59.9794 54.7719 60.047 54.7303 60.0973C54.5152 60.3596 54.3244 60.5997 54.1578 60.8176L53.8013 61.2738L53.4693 61.6981C53.3654 61.8344 53.1797 62.0856 52.9122 62.4515C52.8654 62.5159 52.7968 62.6084 52.7064 62.7292C52.6248 62.8381 52.5706 62.9115 52.5439 62.9494L52.5131 62.9944C52.4514 63.087 52.3954 63.1689 52.345 63.2403L52.0696 63.6401L51.7733 64.0703C51.532 64.4257 51.3545 64.691 51.2409 64.8662C51.0597 65.1463 50.8943 65.4079 50.7447 65.6511C50.7251 65.683 50.7052 65.7146 50.6848 65.7459C50.5481 65.9573 50.4543 66.1054 50.4033 66.1903L50.3824 66.227C50.3045 66.3638 50.2323 66.4853 50.1657 66.5917C50.0113 66.8483 49.8731 67.0865 49.751 67.3064C49.5715 67.6161 49.3943 67.9291 49.2192 68.2454C49.1453 68.3783 49.0325 68.5866 48.881 68.8703C48.8223 68.98 48.7781 69.0627 48.7481 69.1185C48.72 69.1716 48.6738 69.2567 48.6094 69.3736C48.5585 69.4661 48.5308 69.5168 48.5265 69.5259C48.5046 69.571 48.482 69.6157 48.4588 69.66L48.4547 69.6708C48.3897 69.8073 48.3322 69.9233 48.2822 70.0189C48.2355 70.1113 48.1433 70.299 48.0058 70.5818C47.9333 70.7308 47.8767 70.8467 47.8361 70.9296C47.6588 71.2978 47.5309 71.5684 47.4524 71.7412C47.3585 71.9492 47.2134 72.2784 47.0172 72.7288C46.9875 72.7976 46.9436 72.8962 46.8857 73.0244C46.8378 73.1302 46.8106 73.1914 46.8041 73.2079C46.7849 73.2566 46.7649 73.305 46.7441 73.353C46.7433 73.3551 46.7425 73.3573 46.7417 73.3594L46.75 73.3409C46.7166 73.4274 46.6876 73.5004 46.6631 73.5599C46.5646 73.7947 46.4228 74.1529 46.2376 74.6347C46.1998 74.7329 46.1713 74.807 46.152 74.8571C46.1361 74.8984 46.1135 74.9566 46.0843 75.0318C45.9971 75.2565 45.9358 75.4173 45.9005 75.5143C45.7283 75.9826 45.5384 76.5369 45.3309 77.1772C45.3081 77.2459 45.2843 77.3155 45.2595 77.386C45.2346 77.4698 45.2075 77.5532 45.178 77.636C45.1726 77.6528 45.1672 77.6694 45.1617 77.6859C45.0586 78.0149 44.9117 78.5129 44.7212 79.1799L44.7065 79.2334C44.6722 79.3569 44.6508 79.4367 44.6421 79.4728C44.6323 79.5129 44.6222 79.553 44.6115 79.5928C44.4631 80.1463 44.3425 80.6288 44.2497 81.0401C44.2363 81.1019 44.2212 81.1671 44.2043 81.2356C44.2015 81.2478 44.1987 81.2602 44.1958 81.2724C44.1057 81.6601 44.0145 82.0896 43.9222 82.5611C43.9219 82.5631 43.9215 82.5651 43.9212 82.5671L43.9253 82.5485C43.9091 82.6488 43.8943 82.7348 43.8809 82.8064C43.8451 82.9907 43.7966 83.2719 43.7355 83.6497C43.7153 83.7743 43.6999 83.8688 43.6893 83.9332C43.6284 84.2926 43.5824 84.5751 43.5513 84.7805C43.5298 84.9296 43.4969 85.1967 43.4525 85.5819C43.4353 85.7314 43.4221 85.8449 43.4129 85.9225C43.4057 85.9831 43.3956 86.0649 43.3828 86.168C43.3563 86.3799 43.3402 86.5204 43.3347 86.5896C43.2957 87.0031 43.2621 87.4507 43.2337 87.9323C43.2261 88.0425 43.2174 88.1588 43.2075 88.2812C43.1952 88.435 43.1878 88.5377 43.1854 88.5891C43.1625 89.3034 43.1511 89.9389 43.1511 90.4954V112.984C43.1511 119.71 44.7969 125.37 48.0885 129.964C48.2105 130.135 48.3347 130.304 48.4612 130.471C48.7612 130.87 49.1067 131.296 49.4976 131.749C50.0389 132.365 50.5851 132.925 51.1362 133.429C51.1394 133.432 51.1427 133.435 51.146 133.438C51.159 133.45 51.1727 133.462 51.1869 133.475C52.1229 134.329 53.1204 135.091 54.1794 135.76C54.6482 136.057 55.1293 136.336 55.6229 136.597C55.6387 136.605 55.6545 136.613 55.6701 136.622L55.7005 136.637C55.7175 136.646 55.7346 136.655 55.7515 136.664L85.109 152.14ZM93.1353 128.236C93.4493 127.981 93.6922 127.78 93.8641 127.635L94.0621 127.471L94.0756 127.459L94.1552 127.388L94.3292 127.235C94.7991 126.83 95.2489 126.428 95.6787 126.029L95.8253 125.887L96.0277 125.694L96.1784 125.548C96.5995 125.146 96.9459 124.807 97.2176 124.531C97.2581 124.489 97.3285 124.417 97.4289 124.315C97.6004 124.141 97.7231 124.014 97.7971 123.936C98.1301 123.583 98.3794 123.315 98.5452 123.132C98.8197 122.829 99.0227 122.603 99.1543 122.453C99.428 122.145 99.6664 121.87 99.8696 121.627C99.8932 121.599 99.9173 121.571 99.9416 121.543L99.961 121.521C100.189 121.254 100.352 121.059 100.451 120.936C100.54 120.827 100.676 120.657 100.86 120.424C100.962 120.296 101.039 120.198 101.092 120.131C101.332 119.828 101.519 119.588 101.653 119.41C101.842 119.162 102.036 118.901 102.235 118.626L102.797 117.846L102.819 117.815L103.309 117.099L103.311 117.096C103.344 117.047 103.406 116.954 103.499 116.816C103.668 116.564 103.788 116.384 103.858 116.274C103.965 116.111 104.109 115.885 104.29 115.597C104.328 115.536 104.357 115.49 104.378 115.456C104.573 115.153 104.739 114.885 104.877 114.652C104.898 114.616 104.92 114.58 104.942 114.545C105.011 114.435 105.127 114.238 105.289 113.956C105.325 113.894 105.353 113.846 105.371 113.813C105.591 113.43 105.753 113.146 105.856 112.96L106.027 112.645L106.306 112.122C106.44 111.873 106.587 111.591 106.746 111.278C106.819 111.134 106.935 110.898 107.092 110.573C107.137 110.478 107.172 110.405 107.196 110.356C107.213 110.32 107.251 110.241 107.309 110.118C107.427 109.87 107.51 109.694 107.557 109.589C107.708 109.262 107.852 108.94 107.988 108.622L108.004 108.58C108.048 108.477 108.098 108.361 108.153 108.233C108.24 108.031 108.301 107.889 108.334 107.807C108.436 107.558 108.583 107.187 108.773 106.695C108.806 106.611 108.831 106.547 108.849 106.501L108.93 106.284C108.956 106.217 108.98 106.157 109 106.106C109.044 105.996 109.071 105.926 109.082 105.896C109.28 105.353 109.469 104.803 109.649 104.247L109.805 103.768C109.931 103.364 110.073 102.88 110.231 102.318L110.353 101.873C110.486 101.389 110.605 100.913 110.713 100.445L110.766 100.224C110.856 99.8165 110.954 99.3298 111.062 98.7642C111.104 98.5444 111.164 98.2039 111.239 97.7427L111.24 97.7413L111.286 97.4467C111.291 97.4136 111.297 97.3803 111.302 97.3468C111.335 97.1476 111.356 97.0084 111.367 96.9292C111.395 96.7383 111.429 96.4795 111.468 96.1528C111.482 96.0307 111.493 95.9379 111.501 95.8744L111.551 95.4529C111.576 95.2556 111.592 95.114 111.6 95.0279C111.626 94.7717 111.656 94.3788 111.689 93.8493L111.691 93.8218L111.715 93.4636C111.719 93.4193 111.721 93.3886 111.722 93.3716C111.731 93.2627 111.736 93.1977 111.737 93.1766C111.768 92.5227 111.784 91.8907 111.784 91.2807V79.3334C111.683 79.4164 111.58 79.5026 111.473 79.592C111.434 79.6239 111.396 79.6552 111.357 79.6859L111.24 79.7802C111.239 79.7812 111.238 79.7822 111.237 79.7833L111.249 79.7743C111.126 79.8862 111.041 79.9618 110.993 80.0012C110.538 80.3944 110.077 80.8076 109.611 81.2411C109.514 81.3295 109.345 81.4906 109.104 81.7244C108.688 82.1222 108.331 82.4721 108.034 82.7742C107.843 82.9645 107.658 83.1541 107.479 83.3429C107.121 83.7221 106.86 84.0021 106.696 84.1831C106.414 84.4937 106.204 84.7277 106.065 84.8851C105.951 85.0125 105.772 85.2195 105.528 85.5059C105.432 85.6192 105.366 85.6963 105.331 85.7372C105.056 86.0624 104.873 86.2807 104.78 86.3921L104.435 86.827L104.094 87.2552C103.841 87.5734 103.643 87.8273 103.498 88.0169C103.372 88.1822 103.169 88.4556 102.89 88.8374C102.689 89.1089 102.493 89.3801 102.302 89.651C102.166 89.8402 101.994 90.0899 101.787 90.4002C101.534 90.7732 101.359 91.034 101.262 91.1826C101.225 91.2418 101.17 91.3279 101.098 91.4409C100.933 91.6994 100.805 91.9027 100.713 92.0507C100.474 92.4308 100.313 92.6903 100.229 92.8291L99.9616 93.2888L99.698 93.7424C99.551 93.995 99.3887 94.2817 99.2111 94.6025C99.0755 94.8467 98.9312 95.1137 98.7783 95.4034C98.7492 95.4597 98.7058 95.5433 98.6481 95.6541C98.497 95.9446 98.3829 96.1669 98.3057 96.321C98.1488 96.6297 97.9937 96.9454 97.8402 97.268L97.8392 97.2703C97.658 97.6465 97.5293 97.9186 97.453 98.0866C97.3556 98.3021 97.2097 98.633 97.0154 99.0794C96.9949 99.1266 96.9646 99.1963 96.9244 99.2882C96.8019 99.5691 96.7118 99.7803 96.654 99.9218C96.5019 100.289 96.3327 100.718 96.1463 101.211C96.1315 101.25 96.1094 101.306 96.0801 101.382C95.9928 101.607 95.9293 101.774 95.8897 101.882C95.7393 102.291 95.5393 102.876 95.2896 103.637C95.2779 103.671 95.262 103.715 95.242 103.771L95.2393 103.772C95.2279 103.809 95.2161 103.847 95.204 103.884C95.1874 103.939 95.1706 103.991 95.1534 104.043C95.0129 104.485 94.8672 104.979 94.7164 105.526C94.7107 105.546 94.698 105.593 94.6784 105.668C94.6411 105.81 94.6173 105.898 94.607 105.932C94.4938 106.355 94.3708 106.848 94.2382 107.411C94.2266 107.464 94.2138 107.518 94.1998 107.575L94.1965 107.589C94.082 108.092 93.9774 108.598 93.8825 109.107C93.8433 109.324 93.7855 109.662 93.7091 110.122C93.6976 110.191 93.6881 110.247 93.6806 110.293C93.6225 110.634 93.5794 110.898 93.5513 111.084C93.5269 111.253 93.4925 111.53 93.4482 111.915C93.4309 112.065 93.421 112.149 93.4184 112.166C93.4056 112.294 93.3859 112.469 93.3592 112.691C93.3403 112.848 93.3287 112.949 93.3243 112.992C93.3052 113.194 93.2806 113.518 93.2505 113.962C93.2397 114.12 93.2313 114.243 93.2252 114.328C93.2203 114.397 93.213 114.492 93.2032 114.615C93.1908 114.769 93.1834 114.871 93.181 114.923C93.1505 115.562 93.1353 116.203 93.1353 116.846V128.236Z" fill="#0F0D0C"/>
+<path d="M41.7824 61.323L41.786 61.318C41.7619 61.3555 41.7383 61.3935 41.7152 61.4316C41.489 61.8063 41.2987 62.1332 41.1445 62.4123C40.9619 62.726 40.7672 63.0697 40.5605 63.4432C40.463 63.6187 40.3258 63.872 40.1489 64.2029C40.0935 64.3066 40.0477 64.3922 40.0115 64.4596C39.9996 64.4822 39.9744 64.5283 39.9362 64.5977C39.8207 64.8074 39.7258 64.9869 39.6516 65.1362C39.6106 65.2167 39.5653 65.3091 39.5155 65.4136L39.4835 65.4786C39.392 65.6588 39.2648 65.9163 39.1019 66.2511C39.03 66.3991 38.9706 66.5208 38.9238 66.6163C38.7105 67.0593 38.5471 67.4055 38.4338 67.6548C38.3184 67.9104 38.152 68.2878 37.9347 68.7869C37.9232 68.8133 37.8998 68.8657 37.8644 68.944C37.7661 69.1613 37.6858 69.3466 37.6236 69.5C37.5905 69.5789 37.5549 69.6676 37.5168 69.7661L37.5208 69.7585C37.3921 70.0651 37.2171 70.5062 36.9959 71.0817C36.9593 71.177 36.9324 71.247 36.9151 71.2917C36.9019 71.3258 36.8818 71.3777 36.8547 71.4475C36.7417 71.7385 36.6575 71.9603 36.6021 72.1127C36.3895 72.6905 36.1639 73.3479 35.9251 74.085L35.9134 74.1174C35.8643 74.2549 35.8241 74.3734 35.7926 74.473C35.7857 74.495 35.7789 74.517 35.7723 74.539C35.7647 74.5627 35.7573 74.5867 35.7499 74.6109C35.7453 74.6249 35.7408 74.639 35.7364 74.653C35.6047 75.0694 35.4221 75.6865 35.1886 76.5042C35.1839 76.5212 35.1764 76.5481 35.1663 76.5847C35.1121 76.78 35.0683 76.9444 35.0349 77.078C34.8544 77.7535 34.704 78.3592 34.5837 78.895C34.5689 78.9553 34.5554 79.0129 34.5433 79.0679C34.4286 79.5636 34.3125 80.1121 34.1951 80.7134C34.1817 80.7851 34.1669 80.871 34.1507 80.9713L34.1545 80.9542C34.1542 80.9559 34.1539 80.9576 34.1537 80.9593C34.1025 81.2235 34.0386 81.5927 33.9618 82.0668C33.9429 82.1836 33.9303 82.2616 33.9239 82.3007C33.8556 82.7028 33.7999 83.0465 33.7569 83.3318C33.7187 83.5958 33.672 83.9681 33.6166 84.4487C33.6006 84.5877 33.589 84.6881 33.5817 84.7498C33.5769 84.7892 33.5691 84.8524 33.5583 84.9392C33.5136 85.2969 33.4848 85.5587 33.4719 85.7247C33.4259 86.2074 33.3866 86.7286 33.3539 87.2882C33.3511 87.3283 33.3459 87.3951 33.3384 87.4888C33.3174 87.7494 33.3022 87.9838 33.2927 88.1921C33.2644 89.0633 33.2502 89.8308 33.2502 90.4946V112.983C33.2502 122.172 35.6857 129.988 40.5567 136.432C40.6464 136.551 40.7387 136.672 40.8338 136.795C41.1892 137.252 41.5797 137.727 42.0051 138.22C42.0067 138.222 42.0082 138.224 42.0097 138.226C42.0171 138.235 42.0244 138.243 42.0317 138.252C42.8113 139.14 43.6029 139.953 44.4064 140.69C44.4214 140.704 44.4362 140.717 44.4507 140.73C44.4546 140.734 44.4584 140.737 44.4623 140.741C44.4635 140.742 44.4647 140.743 44.4659 140.744C46.3274 142.453 48.367 143.914 50.5849 145.128C50.8889 145.336 51.215 145.509 51.5574 145.645L101.009 171.715L101.012 171.716C101.13 171.778 101.249 171.835 101.369 171.886C101.386 171.895 101.407 171.906 101.431 171.918C101.501 171.955 101.571 171.99 101.64 172.025C101.715 172.063 101.798 172.103 101.891 172.145L101.906 172.152L101.986 172.19C102.39 172.384 102.756 172.551 103.084 172.692L103.255 172.766C103.261 172.768 103.29 172.781 103.342 172.804C103.469 172.861 103.58 172.909 103.675 172.948C104.002 173.083 104.405 173.241 104.884 173.42L105.004 173.466C105.154 173.53 105.307 173.586 105.463 173.634C106.029 173.831 106.608 174.013 107.2 174.181L107.201 174.181C107.358 174.226 107.5 174.263 107.629 174.294L107.656 174.301C108.15 174.435 108.61 174.549 109.037 174.644L109.158 174.672L109.224 174.687L109.27 174.698C109.429 174.736 109.63 174.777 109.871 174.821L109.901 174.827L110.403 174.921C110.875 175.005 111.339 175.081 111.796 175.149C111.839 175.155 111.882 175.162 111.925 175.166L112.124 175.19C112.527 175.243 112.948 175.29 113.388 175.332L114.088 175.394C114.15 175.399 114.212 175.404 114.273 175.407L114.654 175.426L114.824 175.432L114.852 175.434C115.132 175.452 115.335 175.462 115.461 175.466C115.623 175.473 115.843 175.479 116.122 175.483C116.224 175.484 116.298 175.485 116.344 175.486C116.381 175.487 116.418 175.487 116.455 175.487H117.121C117.398 175.487 117.737 175.478 118.137 175.459H118.198C118.347 175.459 118.497 175.452 118.645 175.439L118.608 175.443C118.717 175.438 118.815 175.433 118.903 175.426C119.175 175.411 119.546 175.384 120.015 175.345L120.066 175.341L120.18 175.33C120.362 175.317 120.526 175.302 120.674 175.285L121.331 175.209L121.727 175.159C121.986 175.129 122.178 175.104 122.304 175.085C122.483 175.059 122.729 175.02 123.044 174.967C123.084 174.961 123.106 174.957 123.11 174.956L123.619 174.874C123.625 174.872 123.646 174.869 123.681 174.864C123.855 174.836 124.007 174.809 124.139 174.782C124.363 174.738 124.663 174.676 125.039 174.596L125.437 174.515L125.833 174.432C126.392 174.306 126.996 174.153 127.646 173.973L131.151 173.012C131.9 172.805 132.571 172.603 133.165 172.407C133.366 172.342 133.549 172.28 133.715 172.219L133.879 172.161L133.881 172.16C134.453 171.961 134.872 171.814 135.137 171.716C135.294 171.661 135.49 171.584 135.725 171.488C135.78 171.466 135.835 171.443 135.892 171.42L136.002 171.374L136.137 171.32C136.623 171.127 136.994 170.973 137.252 170.86L138.025 170.524C138.46 170.326 138.849 170.145 139.192 169.982L139.342 169.911L139.961 169.61C140.355 169.414 140.759 169.203 141.174 168.979L141.426 168.846C141.443 168.837 141.479 168.819 141.532 168.79C141.686 168.709 141.789 168.654 141.84 168.625C142.154 168.454 142.593 168.202 143.159 167.867C143.237 167.821 143.276 167.798 143.279 167.796L143.449 167.699L143.479 167.682L152.021 171.573C156.866 173.781 161.529 173.445 166.008 170.563C170.488 167.682 172.728 163.577 172.728 158.251V118.111C172.743 117.954 172.75 117.795 172.75 117.637V95.1484C172.75 87.925 171.221 81.491 168.163 75.8464C165.083 70.1612 160.753 65.8115 155.173 62.7973C155.084 62.7426 154.992 62.6907 154.9 62.6418L154.881 62.632L104.937 36.3023C104.784 36.2211 104.575 36.1139 104.308 35.9805C104.223 35.938 104.122 35.8899 104.003 35.8361L103.963 35.8169C103.61 35.6469 103.261 35.4856 102.918 35.3328C102.808 35.2839 102.655 35.2169 102.459 35.1317C102.417 35.1139 102.368 35.0928 102.311 35.0684C101.931 34.9089 101.508 34.7451 101.044 34.5769C100.881 34.5109 100.733 34.4556 100.6 34.4109C100.574 34.4019 100.548 34.3932 100.522 34.3846C99.9241 34.1774 99.3732 34.0019 98.8692 33.8581C98.865 33.8569 98.8608 33.8557 98.8566 33.8545C98.8045 33.8387 98.7485 33.8224 98.6886 33.8058C98.6743 33.8018 98.6594 33.7976 98.6438 33.7934C98.5513 33.7682 98.4501 33.742 98.3401 33.7149L98.3072 33.7071L98.3119 33.7085C98.1067 33.6529 97.9063 33.6006 97.7107 33.5517C97.4749 33.4924 97.2476 33.4387 97.0288 33.3903C97.0046 33.385 96.9806 33.3797 96.9566 33.3744C96.8375 33.3418 96.7395 33.3173 96.6627 33.301C96.5177 33.2683 96.3333 33.2314 96.1093 33.1905C96.0713 33.1835 96.0408 33.1779 96.0179 33.1737C95.9548 33.1606 95.8842 33.1466 95.8062 33.1318L95.8031 33.1321C95.7386 33.1178 95.6739 33.1047 95.6089 33.093C95.085 32.9984 94.6093 32.9223 94.1819 32.8646C94.0983 32.8527 94.0015 32.8408 93.8913 32.829L93.8896 32.8288L93.8761 32.8271C93.4523 32.7724 93.0373 32.7257 92.6313 32.6871L92.3254 32.6598C92.0953 32.6356 91.9206 32.6204 91.8012 32.6144C91.7158 32.6089 91.6011 32.6026 91.4568 32.5957C91.3656 32.5912 91.2891 32.5871 91.2273 32.5832C90.9082 32.5655 90.6803 32.5549 90.5436 32.5514C90.3757 32.5444 90.1448 32.5389 89.851 32.5349C89.7388 32.5334 89.6342 32.5318 89.537 32.5302L89.3523 32.529C89.1472 32.5271 88.9748 32.5275 88.835 32.5303C88.6706 32.5314 88.4606 32.5364 88.205 32.5453C88.0717 32.5499 87.9598 32.5532 87.8692 32.5551L87.8533 32.5556C87.5561 32.5646 87.3378 32.5734 87.1982 32.582C86.9091 32.5967 86.533 32.6238 86.07 32.6632L85.7453 32.6873C85.6353 32.6913 85.5254 32.6991 85.4158 32.7105C85.2559 32.7271 85.0348 32.7538 84.7525 32.7903C84.6345 32.8056 84.5516 32.8162 84.504 32.822L84.1737 32.8619L83.8432 32.9018C83.8033 32.9066 83.7635 32.9119 83.7238 32.9177C83.5459 32.9435 83.2985 32.9834 82.9815 33.0372C82.852 33.0591 82.7524 33.0758 82.6826 33.0873C82.6517 33.0924 82.5981 33.101 82.5216 33.1131C82.2808 33.151 82.0871 33.1842 81.9406 33.2127C81.5282 33.2925 81.1612 33.3685 80.8395 33.4407C80.5868 33.4913 80.378 33.5359 80.2131 33.5744C79.6373 33.7044 79.0348 33.8574 78.4057 34.0333L74.8975 34.9948C74.1846 35.1929 73.5201 35.3928 72.904 35.5945C72.7593 35.64 72.574 35.7031 72.3482 35.7837C72.2719 35.8109 72.2132 35.8316 72.1722 35.8457C71.5991 36.0447 71.1527 36.2027 70.833 36.3199C70.6998 36.3699 70.5114 36.4427 70.2678 36.5384C70.1844 36.5712 70.1097 36.6005 70.0435 36.6265C69.5097 36.84 69.0934 37.0111 68.7948 37.1398L68.4373 37.2954L68.0218 37.477C67.5857 37.6746 67.1979 37.8542 66.8586 38.0158C66.5247 38.1744 66.2669 38.2991 66.0852 38.39C65.6911 38.5871 65.2867 38.7973 64.872 39.0207L64.8387 39.0383L64.2065 39.3754C63.8928 39.5462 63.453 39.7986 62.8873 40.1328C62.8182 40.1736 62.7838 40.1941 62.7839 40.1944C62.5743 40.3142 62.4222 40.4035 62.3278 40.4623C61.8541 40.7475 61.2865 41.1057 60.6251 41.5367C60.5792 41.5661 60.5329 41.5967 60.4862 41.6287C60.3942 41.6892 60.2852 41.7638 60.1593 41.8524L60.1145 41.8841L60.1163 41.883C59.5704 42.2518 59.1025 42.577 58.7128 42.8586C58.5143 43.0042 58.3729 43.1065 58.2888 43.1654C58.2479 43.1939 58.2075 43.2232 58.1675 43.253C57.6655 43.6275 57.2979 43.9051 57.0648 44.0858C56.9507 44.1724 56.7923 44.2954 56.5898 44.4548C56.5529 44.4839 56.5166 44.5125 56.4808 44.5407C55.9911 44.9311 55.5288 45.3081 55.0939 45.6717L55.0774 45.6851L55.0503 45.7065C55.0236 45.7269 54.997 45.7476 54.9705 45.7688C54.904 45.8206 54.8391 45.8741 54.7754 45.9292C54.7025 45.9924 54.617 46.0697 54.5189 46.161L54.5295 46.1528C54.5287 46.1536 54.5279 46.1543 54.5271 46.155C53.9052 46.6923 53.3761 47.1664 52.9399 47.5775C52.8271 47.6806 52.6771 47.8224 52.49 48.0029C52.4007 48.0891 52.3283 48.1583 52.2729 48.2107C51.9017 48.5656 51.4915 48.9675 51.0424 49.4165C51.0247 49.4343 50.99 49.4683 50.9383 49.5185C50.8533 49.6012 50.7855 49.6679 50.7349 49.7185C50.6395 49.8139 50.5274 49.9324 50.3985 50.0741L50.3874 50.0888C50.3534 50.1227 50.3199 50.1572 50.2869 50.1921C49.8853 50.6178 49.5804 50.9454 49.3723 51.1748L48.6764 51.9423C48.544 52.0909 48.3585 52.3041 48.1197 52.582C47.9852 52.7384 47.8766 52.8642 47.7938 52.9593C47.771 52.9858 47.7338 53.0289 47.6821 53.0885C47.53 53.264 47.4115 53.4034 47.3267 53.5067C47.2851 53.5571 47.2305 53.6246 47.1628 53.7094C47.1242 53.7575 47.0969 53.7914 47.0808 53.811C46.7902 54.1653 46.5387 54.4816 46.3262 54.7597L45.9946 55.1837L45.6377 55.6403C45.4678 55.8625 45.2257 56.1886 44.9115 56.6186C44.8877 56.6514 44.8446 56.7095 44.7821 56.7929C44.6445 56.9765 44.5458 57.1108 44.4861 57.1958C44.4252 57.2801 44.3548 57.3822 44.2749 57.5021L44.2753 57.5034C44.2537 57.5333 44.2325 57.5634 44.2115 57.5939L43.9154 58.0238L43.601 58.4804C43.3076 58.9123 43.0841 59.2469 42.9304 59.484C42.7188 59.811 42.5227 60.1209 42.342 60.4136C42.159 60.697 42.0161 60.9245 41.9132 61.0959C41.8771 61.1561 41.8335 61.2318 41.7824 61.323ZM41.7824 61.323C41.7846 61.3193 41.7867 61.3156 41.7888 61.3118L41.7824 61.323ZM104.568 72.4679L104.555 72.4797C103.975 72.9804 103.423 73.4747 102.898 73.9627C102.75 74.0982 102.529 74.3084 102.236 74.5932C101.766 75.0422 101.356 75.4442 101.006 75.7993C100.774 76.0318 100.534 76.2773 100.289 76.536C99.8791 76.9701 99.5705 77.3015 99.3629 77.5304C99.0523 77.8728 98.8175 78.1339 98.6587 78.3137C98.506 78.4851 98.2842 78.7413 97.9935 79.0823C97.9023 79.1892 97.8343 79.2689 97.7895 79.3212L97.7656 79.3492C97.4631 79.7075 97.2347 79.9804 97.0805 80.168L96.69 80.6582L96.3452 81.0921C96.0476 81.4661 95.8073 81.7734 95.6245 82.014C95.4605 82.2284 95.2236 82.5476 94.9138 82.9715C94.6806 83.2865 94.4559 83.5971 94.2398 83.9033C94.0521 84.1637 93.8298 84.4867 93.5727 84.8722C93.2952 85.2806 93.0803 85.6022 92.9281 85.8371C92.878 85.9158 92.8189 86.0084 92.7509 86.1149C92.5571 86.4188 92.4094 86.6532 92.3079 86.8181C92.0487 87.2295 91.8473 87.5548 91.7037 87.7941L91.4063 88.3047L91.1389 88.7647C90.9573 89.0771 90.7617 89.4223 90.5524 89.8004C90.3841 90.1034 90.201 90.4424 90.0032 90.8175C89.9656 90.89 89.9194 90.9789 89.8645 91.0844C89.689 91.4218 89.5557 91.6816 89.4646 91.8639C89.2811 92.2247 89.099 92.5951 88.9182 92.9749C88.9169 92.9777 88.9155 92.9806 88.9141 92.9835C88.7034 93.4213 88.5435 93.7602 88.4344 94.0001C88.3155 94.2636 88.1491 94.6407 87.9353 95.1316C87.9153 95.1776 87.8867 95.2432 87.8495 95.3284C87.6946 95.6837 87.5769 95.96 87.4965 96.1574C87.3121 96.6018 87.1126 97.1079 86.8979 97.6759C86.8935 97.6871 86.8777 97.7276 86.8505 97.7977C86.7374 98.0889 86.651 98.3166 86.5913 98.4808C86.4078 98.9796 86.1871 99.6224 85.9293 100.409C85.9288 100.41 85.9267 100.416 85.9233 100.425C85.8714 100.57 85.8274 100.699 85.7911 100.812C85.7756 100.859 85.7604 100.907 85.7454 100.956C85.7425 100.965 85.7394 100.975 85.7364 100.984C85.5509 101.565 85.3667 102.187 85.1837 102.851C85.1675 102.907 85.1407 103.006 85.1034 103.148C85.0838 103.223 85.0711 103.27 85.0654 103.29C84.9083 103.874 84.7498 104.507 84.59 105.188C84.5864 105.203 84.5829 105.219 84.5794 105.234C84.5632 105.3 84.5486 105.362 84.5356 105.422C84.3948 106.043 84.2642 106.675 84.144 107.32C84.0935 107.6 84.0263 107.992 83.9424 108.496C83.931 108.565 83.9225 108.616 83.917 108.649C83.8504 109.041 83.797 109.37 83.757 109.636C83.7158 109.919 83.6676 110.301 83.6122 110.782C83.5963 110.921 83.5843 111.024 83.5763 111.091C83.5635 111.213 83.5477 111.353 83.5288 111.511C83.5022 111.733 83.4825 111.908 83.4697 112.035C83.4408 112.342 83.4083 112.76 83.3724 113.29C83.3621 113.44 83.3544 113.552 83.3493 113.626C83.3466 113.663 83.3415 113.729 83.334 113.822C83.313 114.083 83.2988 114.292 83.2913 114.451C83.2534 115.247 83.2344 116.045 83.2344 116.845V137.426C83.2344 137.458 83.2347 137.489 83.2353 137.521V139.337C83.2373 143.919 83.8619 148.186 85.109 152.14L55.7515 136.664C55.7346 136.655 55.7175 136.646 55.7005 136.637L55.6701 136.622C55.6545 136.613 55.6387 136.605 55.6229 136.597C55.1293 136.336 54.6482 136.057 54.1794 135.76C53.1204 135.091 52.1229 134.329 51.1869 133.475C51.1727 133.462 51.159 133.45 51.146 133.438C51.1427 133.435 51.1394 133.432 51.1362 133.429C50.5851 132.925 50.0389 132.365 49.4976 131.749C49.1067 131.296 48.7612 130.87 48.4612 130.471C48.3347 130.304 48.2105 130.135 48.0885 129.964C44.7969 125.37 43.1511 119.71 43.1511 112.984V90.4954C43.1511 89.9389 43.1625 89.3034 43.1854 88.5891C43.1878 88.5377 43.1952 88.435 43.2075 88.2812C43.2174 88.1588 43.2261 88.0425 43.2337 87.9323C43.2621 87.4507 43.2957 87.0031 43.3347 86.5896C43.3402 86.5204 43.3563 86.3799 43.3828 86.168C43.3956 86.0649 43.4057 85.9831 43.4129 85.9225C43.4221 85.8449 43.4353 85.7314 43.4525 85.5819C43.4969 85.1967 43.5298 84.9296 43.5513 84.7805C43.5824 84.5751 43.6284 84.2926 43.6893 83.9332C43.6999 83.8688 43.7153 83.7743 43.7355 83.6497C43.7966 83.2719 43.8451 82.9907 43.8809 82.8064C43.8943 82.7348 43.9091 82.6488 43.9253 82.5485L43.9212 82.5671C43.9215 82.5651 43.9219 82.5631 43.9222 82.5611C44.0145 82.0896 44.1057 81.6601 44.1958 81.2724C44.1987 81.2602 44.2015 81.2478 44.2043 81.2356C44.2212 81.1671 44.2363 81.1019 44.2497 81.0401C44.3425 80.6288 44.4631 80.1463 44.6115 79.5928C44.6222 79.553 44.6323 79.5129 44.6421 79.4728C44.6508 79.4367 44.6722 79.3569 44.7065 79.2334L44.7212 79.1799C44.9117 78.5129 45.0586 78.0149 45.1617 77.6859C45.1672 77.6694 45.1726 77.6528 45.178 77.636C45.2075 77.5532 45.2346 77.4698 45.2595 77.386C45.2843 77.3155 45.3081 77.2459 45.3309 77.1772C45.5384 76.5369 45.7283 75.9826 45.9005 75.5143C45.9358 75.4173 45.9971 75.2564 46.0843 75.0318C46.1135 74.9566 46.1361 74.8984 46.152 74.8571C46.1713 74.807 46.1998 74.7329 46.2376 74.6347C46.4228 74.1529 46.5646 73.7947 46.6631 73.5599C46.6876 73.5004 46.7166 73.4274 46.75 73.3409L46.7417 73.3594C46.7425 73.3573 46.7433 73.3551 46.7441 73.353C46.7649 73.305 46.7849 73.2566 46.8041 73.2079C46.8106 73.1914 46.8378 73.1302 46.8857 73.0244C46.9436 72.8962 46.9875 72.7976 47.0172 72.7288C47.2134 72.2784 47.3585 71.9492 47.4524 71.7412C47.5309 71.5684 47.6588 71.2978 47.8361 70.9296C47.8767 70.8467 47.9333 70.7308 48.0058 70.5818C48.1433 70.2989 48.2355 70.1113 48.2822 70.0189C48.3322 69.9233 48.3897 69.8073 48.4547 69.6708L48.4588 69.66C48.482 69.6157 48.5046 69.571 48.5265 69.5259C48.5308 69.5168 48.5585 69.4661 48.6094 69.3736C48.6738 69.2567 48.72 69.1716 48.7481 69.1184C48.7781 69.0627 48.8223 68.98 48.881 68.8703C49.0325 68.5866 49.1453 68.3783 49.2192 68.2454C49.3943 67.9291 49.5715 67.6161 49.751 67.3064C49.8731 67.0865 50.0113 66.8483 50.1657 66.5917C50.2323 66.4853 50.3045 66.3638 50.3824 66.227L50.4033 66.1903C50.4543 66.1054 50.5481 65.9573 50.6848 65.7459C50.7052 65.7146 50.7251 65.683 50.7447 65.6511C50.8943 65.4079 51.0597 65.1463 51.2409 64.8662C51.3545 64.691 51.532 64.4257 51.7733 64.0703L52.0696 63.6401L52.345 63.2403C52.3954 63.1689 52.4514 63.087 52.5131 62.9944L52.5439 62.9494C52.5706 62.9115 52.6248 62.8381 52.7064 62.7292C52.7968 62.6084 52.8654 62.5159 52.9122 62.4515C53.1797 62.0856 53.3654 61.8344 53.4693 61.6981L53.8013 61.2738L54.1578 60.8176C54.3244 60.5997 54.5152 60.3596 54.7303 60.0973C54.7719 60.047 54.8265 59.9794 54.8943 59.8946C54.9328 59.8464 54.9593 59.8136 54.9736 59.7962C55.0053 59.7575 55.0686 59.6836 55.1632 59.5745C55.227 59.5009 55.2667 59.4549 55.2825 59.4363C55.3624 59.3447 55.4778 59.2111 55.6287 59.0355C55.8292 58.8023 55.9662 58.6442 56.0398 58.5614L56.7055 57.8275C56.865 57.6517 57.1154 57.3829 57.4565 57.0211C57.536 56.9393 57.6255 56.8437 57.7249 56.7344L57.7362 56.7197C57.7539 56.7019 57.7886 56.6679 57.8403 56.6177C57.9253 56.535 57.9931 56.4684 58.0437 56.4178C58.4401 56.0213 58.7889 55.6792 59.0899 55.3914C59.1565 55.3286 59.248 55.241 59.3645 55.1286C59.488 55.0095 59.591 54.912 59.6734 54.8362C60.0428 54.4885 60.4881 54.0895 61.0095 53.6393C61.0704 53.5865 61.1402 53.5238 61.2187 53.4512C61.3346 53.3593 61.4226 53.2875 61.4827 53.2357C61.8299 52.9455 62.2109 52.635 62.6258 52.3042C62.6456 52.2887 62.6748 52.2656 62.7135 52.2352C62.8699 52.1121 62.9946 52.0152 63.0876 51.9444C63.2914 51.7866 63.607 51.5482 64.0344 51.2291C64.1686 51.1342 64.3368 51.0125 64.5392 50.864C64.8258 50.657 65.2073 50.3925 65.6836 50.0706C65.7282 50.0401 65.7862 49.9998 65.8575 49.9496L65.9139 49.9097C65.9533 49.8842 65.9931 49.8578 66.0332 49.8305C66.5958 49.4639 67.0806 49.1579 67.4876 48.9125C67.518 48.8937 67.6073 48.8417 67.7555 48.7567C67.7923 48.735 67.8482 48.702 67.9232 48.6577C68.3892 48.3824 68.7153 48.1941 68.9012 48.0927L69.4965 47.7756L69.5302 47.7576C69.8811 47.5686 70.2089 47.398 70.5135 47.2457C70.6356 47.1846 70.8335 47.0891 71.1072 46.9591L71.1115 46.957C71.3972 46.821 71.7073 46.677 72.0419 46.5249L72.3994 46.3693L72.7303 46.2251C72.9375 46.1359 73.2548 46.0058 73.6823 45.8346C73.7301 45.816 73.7991 45.7889 73.8894 45.7534C74.085 45.6766 74.2132 45.6267 74.2741 45.6037C74.5177 45.5145 74.8937 45.3817 75.4021 45.2051C75.4704 45.1817 75.5623 45.1493 75.6778 45.1081C75.7842 45.0701 75.8676 45.0416 75.928 45.0223C76.4388 44.8552 76.9734 44.6941 77.5317 44.539L81.0478 43.5754C81.5326 43.4398 81.993 43.3228 82.429 43.2242C82.5146 43.2042 82.6666 43.172 82.885 43.1276C83.1868 43.0605 83.5008 42.9954 83.827 42.9323C83.8599 42.9259 83.9382 42.913 84.0619 42.8935C84.1678 42.8768 84.246 42.8643 84.2967 42.8558C84.3759 42.8429 84.4899 42.8237 84.6388 42.7985C84.8419 42.764 84.9951 42.7388 85.0984 42.7231L85.3608 42.6915L85.6996 42.6505C85.7759 42.6412 85.8845 42.6274 86.0254 42.6091C86.1393 42.5944 86.2335 42.5825 86.3077 42.5735C86.3187 42.5728 86.3298 42.572 86.3409 42.5711L86.5715 42.554L86.8546 42.5328C87.2415 42.5 87.5399 42.4782 87.7499 42.4674C87.8209 42.4631 87.9529 42.458 88.1461 42.4522C88.248 42.4499 88.3825 42.4459 88.5495 42.4401C88.7268 42.434 88.8446 42.4309 88.903 42.4309C88.9501 42.4309 88.9973 42.4302 89.0444 42.4289C89.0705 42.4281 89.1424 42.4283 89.26 42.4294C89.3578 42.4304 89.4064 42.4305 89.4058 42.4298C89.4787 42.4313 89.5824 42.433 89.7169 42.4349C89.9183 42.4376 90.0797 42.4413 90.2011 42.446C90.292 42.4486 90.4366 42.4553 90.6349 42.4662C90.7203 42.4717 90.835 42.478 90.9793 42.4849C91.055 42.4886 91.1239 42.4922 91.1859 42.4959L91.289 42.5054L91.2927 42.5057L91.3599 42.5131L91.7147 42.5453C91.997 42.5722 92.2732 42.6029 92.5435 42.6375C92.6275 42.6495 92.725 42.6614 92.8358 42.6733C93.1212 42.7121 93.4377 42.7625 93.7854 42.8246C93.8405 42.8359 93.9009 42.8477 93.9667 42.8601L93.9698 42.8599C94.014 42.8697 94.0584 42.8789 94.1029 42.8876C94.1589 42.8984 94.2346 42.9125 94.33 42.93C94.3714 42.9375 94.4084 42.9445 94.4409 42.9508C94.5792 42.9882 94.6972 43.0166 94.795 43.036C95.0531 43.0905 95.3802 43.1715 95.7763 43.2788C95.8272 43.2921 95.8926 43.3086 95.9727 43.3283L96.059 43.3512C96.4567 43.4648 96.8799 43.5998 97.3286 43.7561C97.3407 43.7603 97.3527 43.7645 97.3649 43.7686C97.4776 43.814 97.5717 43.85 97.6473 43.8766C97.8311 43.9427 97.9965 44.0041 98.1433 44.061C98.2427 44.0998 98.3382 44.1381 98.4299 44.176C98.4306 44.1763 98.4314 44.1767 98.4322 44.177C98.455 44.1869 98.4876 44.201 98.53 44.2193C98.6867 44.2871 98.8044 44.3386 98.8832 44.3739C98.9939 44.4231 99.1007 44.4713 99.2036 44.5184C99.343 44.5824 99.4811 44.6472 99.6181 44.7129C99.6999 44.7535 99.7964 44.7991 99.9075 44.8496L99.9007 44.846C99.9027 44.8469 99.9047 44.8478 99.9066 44.8487C100.083 44.937 100.214 45.004 100.3 45.0496L129.063 60.213C128.835 60.2715 128.613 60.3306 128.396 60.3905L124.888 61.352C124.175 61.5501 123.466 61.7648 122.76 61.9962L122.468 62.0972L122.221 62.183C121.69 62.36 121.224 62.5247 120.824 62.6771C120.638 62.7468 120.385 62.8458 120.064 62.9741C119.559 63.1731 119.128 63.3494 118.772 63.5029L118.018 63.8342C117.669 63.9926 117.279 64.1741 116.849 64.3787C116.591 64.5012 116.336 64.6259 116.082 64.7529C115.634 64.9766 115.228 65.1868 114.863 65.3835C114.833 65.3993 114.784 65.425 114.715 65.4606C114.639 65.5005 114.569 65.5368 114.507 65.5696C114.467 65.5899 114.427 65.6108 114.387 65.6323C114.288 65.6854 114.195 65.7371 114.107 65.7874C113.817 65.9444 113.351 66.212 112.71 66.59C112.642 66.6306 112.544 66.6878 112.415 66.7614C112.372 66.7861 112.329 66.8116 112.286 66.8376C111.632 67.2385 111.047 67.6097 110.532 67.9513C110.413 68.0272 110.281 68.1154 110.137 68.2159C110.111 68.2342 110.094 68.2454 110.088 68.2498C109.606 68.5732 109.156 68.886 108.738 69.1881L108.196 69.5852C107.863 69.8283 107.478 70.1188 107.041 70.4566C106.802 70.6384 106.615 70.7826 106.48 70.8893C106.104 71.1853 105.67 71.5386 105.178 71.9492C105.043 72.0556 104.93 72.1485 104.837 72.2279C104.78 72.2755 104.69 72.3555 104.568 72.4679ZM104.568 72.4679C104.572 72.4646 104.575 72.4614 104.579 72.4582L104.568 72.4679ZM101.032 34.5728L101.03 34.5721C101.033 34.573 101.035 34.5739 101.038 34.5748C101.036 34.5741 101.034 34.5735 101.032 34.5728ZM104.903 162.561L105.666 162.963C105.717 162.991 105.807 163.037 105.935 163.102C105.972 163.121 106.002 163.136 106.025 163.148C106.092 163.178 106.131 163.197 106.145 163.205L106.281 163.269C106.554 163.401 106.811 163.519 107.052 163.622L107.063 163.627C107.148 163.663 107.253 163.708 107.38 163.765C107.425 163.785 107.449 163.796 107.452 163.797C107.68 163.891 107.998 164.015 108.408 164.169L108.458 164.189C108.519 164.211 108.58 164.234 108.641 164.257L108.655 164.263C109.054 164.403 109.476 164.536 109.919 164.661C109.914 164.66 109.885 164.654 109.835 164.643C109.904 164.659 109.973 164.675 110.041 164.693L110.249 164.747C110.596 164.84 110.948 164.927 111.306 165.008L111.379 165.025L111.451 165.041L111.564 165.067L111.672 165.086L111.703 165.092L112.139 165.174C112.496 165.238 112.847 165.295 113.191 165.347L113.391 165.372C113.685 165.41 113.977 165.443 114.269 165.47L114.88 165.525L115.066 165.535L115.442 165.551L115.47 165.553C115.644 165.565 115.787 165.572 115.899 165.576C115.964 165.579 116.087 165.581 116.267 165.584C116.363 165.585 116.443 165.586 116.506 165.587H117.121C117.26 165.587 117.474 165.58 117.764 165.566C117.848 165.561 117.932 165.559 118.015 165.559H118.037C118.081 165.557 118.126 165.555 118.174 165.552L118.156 165.555C118.215 165.55 118.274 165.546 118.334 165.542C118.501 165.534 118.779 165.514 119.169 165.481L119.325 165.467C119.376 165.462 119.427 165.458 119.479 165.455C119.506 165.453 119.53 165.451 119.549 165.449L120.088 165.388L120.592 165.324C120.728 165.308 120.832 165.295 120.904 165.284C121.005 165.27 121.174 165.243 121.411 165.203C121.454 165.196 121.491 165.19 121.522 165.185L121.924 165.119C121.976 165.11 122.042 165.1 122.123 165.087L122.114 165.091C122.152 165.082 122.191 165.074 122.23 165.067C122.398 165.035 122.677 164.977 123.068 164.895L123.398 164.828L123.653 164.775C124.058 164.683 124.517 164.567 125.03 164.425L128.507 163.472C129.101 163.307 129.652 163.141 130.162 162.973C130.219 162.955 130.253 162.943 130.266 162.939C130.308 162.922 130.35 162.907 130.393 162.892L130.632 162.808H130.634C131.154 162.628 131.551 162.487 131.825 162.387C131.834 162.383 131.882 162.364 131.971 162.328C132.052 162.295 132.097 162.276 132.106 162.273L132.326 162.182C132.367 162.166 132.414 162.147 132.467 162.126C132.853 161.972 133.13 161.858 133.299 161.784L133.938 161.506C134.318 161.334 134.65 161.181 134.935 161.045L135.024 161.003L135.533 160.756C135.838 160.604 136.178 160.426 136.553 160.224L136.711 160.141C136.766 160.112 136.839 160.073 136.929 160.025C136.993 159.992 137.052 159.961 137.107 159.93C137.318 159.814 137.658 159.619 138.125 159.343C138.192 159.304 138.261 159.263 138.332 159.221L138.46 159.147H138.461C138.544 159.098 138.619 159.055 138.687 159.017C139.131 158.749 139.551 158.484 139.947 158.224L140.305 157.979C141.736 157.002 143.572 156.845 145.148 157.563L156.125 162.564C157.693 163.279 159.202 163.17 160.652 162.237C162.103 161.304 162.828 159.976 162.828 158.251V117.614C162.828 117.456 162.835 117.298 162.85 117.14V95.1484C162.85 83.7403 158.651 75.8219 150.254 71.3934L149.959 71.2374C149.909 71.2132 149.855 71.1867 149.796 71.158C149.721 71.1217 149.663 71.0932 149.62 71.0724C149.384 70.9567 149.129 70.8386 148.853 70.718C148.676 70.6389 148.548 70.5828 148.468 70.5496C148.234 70.4515 147.944 70.3392 147.597 70.2126L147.415 70.1456L147.313 70.1067C146.939 69.9768 146.534 69.8488 146.096 69.7227L145.999 69.6973L145.777 69.6395C145.321 69.5221 144.979 69.4377 144.751 69.3863C144.724 69.3805 144.683 69.3717 144.629 69.3597C144.371 69.3034 144.185 69.2642 144.072 69.242C144.03 69.2339 143.989 69.2253 143.948 69.2162L143.83 69.1927C143.449 69.1241 143.093 69.0673 142.761 69.0223C142.792 69.0267 142.81 69.0291 142.814 69.0296C142.703 69.0177 142.628 69.0088 142.589 69.0029C142.287 68.9641 141.996 68.931 141.716 68.9037L141.71 68.9033L141.383 68.8734C141.233 68.8611 140.993 68.845 140.663 68.8252C140.435 68.8126 140.276 68.805 140.186 68.8025C140.128 68.8008 140.071 68.7982 140.014 68.7947C139.934 68.7897 139.76 68.7872 139.491 68.7872L138.982 68.7863C138.823 68.7894 138.572 68.7974 138.23 68.8105C138.13 68.8157 138.008 68.8205 137.866 68.8249C137.791 68.8271 137.731 68.8296 137.686 68.8322C137.515 68.8408 137.229 68.8619 136.827 68.8954L136.781 68.899C136.729 68.9029 136.661 68.9074 136.577 68.9127L136.442 68.9231C136.355 68.9316 136.204 68.9492 135.988 68.9761C135.849 68.9934 135.758 69.0044 135.717 69.0091C135.625 69.0209 135.503 69.035 135.352 69.0513C135.248 69.0625 135.179 69.0706 135.146 69.0756C135.049 69.09 134.884 69.1175 134.65 69.158C134.503 69.1832 134.384 69.2036 134.291 69.219C134.229 69.2289 134.145 69.2422 134.038 69.2587C133.907 69.2786 133.814 69.2938 133.759 69.3042C133.645 69.3251 133.444 69.3668 133.157 69.4293C133.028 69.4574 132.949 69.4744 132.92 69.4802C132.827 69.5013 132.7 69.5285 132.54 69.5617C132.451 69.5801 132.403 69.5901 132.396 69.5916C131.906 69.7035 131.445 69.8191 131.014 69.9384L127.538 70.8908C126.968 71.049 126.455 71.2026 125.998 71.3517L125.707 71.4525L125.352 71.575C124.951 71.7086 124.6 71.8325 124.3 71.9467C124.181 71.9913 123.979 72.0708 123.693 72.1852C123.284 72.3461 122.971 72.4736 122.752 72.5678L122.104 72.8516C121.973 72.9113 121.833 72.9757 121.684 73.0449V91.2807C121.684 92.0491 121.665 92.8184 121.628 93.5885C121.622 93.7365 121.609 93.9283 121.591 94.1637L121.59 94.1679L121.571 94.4471L121.57 94.4744C121.528 95.1281 121.491 95.6208 121.457 95.9524C121.439 96.1399 121.414 96.3666 121.381 96.6324L121.329 97.0655C121.322 97.1194 121.312 97.2021 121.299 97.3136C121.248 97.7482 121.207 98.0619 121.178 98.255C121.155 98.4224 121.12 98.6496 121.074 98.9367C121.068 98.9704 121.065 98.9883 121.065 98.9905L121.009 99.3453L121.009 99.3467C120.917 99.902 120.844 100.324 120.788 100.612C120.661 101.278 120.528 101.923 120.389 102.547L120.362 102.657C120.224 103.259 120.071 103.869 119.902 104.487L119.761 104.999C119.578 105.652 119.397 106.263 119.219 106.83L119.068 107.297C118.85 107.97 118.629 108.613 118.405 109.225C118.356 109.361 118.29 109.536 118.205 109.751L118.188 109.793L118.192 109.783L118.08 110.078C118.063 110.121 118.039 110.184 118.007 110.266C117.79 110.827 117.625 111.244 117.512 111.517C117.449 111.674 117.358 111.889 117.239 112.163C117.192 112.273 117.165 112.336 117.158 112.351L117.095 112.503C116.916 112.924 116.752 113.292 116.603 113.609C116.52 113.796 116.401 114.053 116.244 114.381C116.192 114.49 116.148 114.584 116.109 114.664C116.087 114.71 116.055 114.778 116.011 114.868C115.823 115.258 115.676 115.559 115.568 115.77C115.376 116.148 115.2 116.486 115.04 116.784L114.726 117.371L114.51 117.768C114.385 117.994 114.197 118.325 113.947 118.761C113.932 118.786 113.907 118.83 113.871 118.893C113.665 119.251 113.496 119.536 113.364 119.749C113.175 120.066 112.975 120.389 112.764 120.718C112.747 120.745 112.719 120.789 112.68 120.851C112.458 121.207 112.294 121.463 112.191 121.62C112.082 121.789 111.924 122.028 111.715 122.339C111.63 122.465 111.557 122.575 111.495 122.666L111.474 122.698L110.894 123.543L110.828 123.635L110.248 124.44C110.006 124.774 109.774 125.086 109.554 125.376C109.374 125.614 109.136 125.921 108.838 126.296C108.792 126.354 108.722 126.444 108.626 126.564C108.415 126.831 108.255 127.032 108.146 127.165C107.99 127.358 107.765 127.627 107.472 127.971L107.432 128.017L107.427 128.022C107.169 128.329 106.885 128.659 106.573 129.01C106.415 129.187 106.185 129.443 105.883 129.777C105.674 130.009 105.372 130.333 104.979 130.75C104.865 130.87 104.702 131.038 104.49 131.254C104.4 131.346 104.327 131.42 104.271 131.477C103.929 131.825 103.523 132.223 103.055 132.67L102.875 132.844L102.673 133.037L102.415 133.284C101.896 133.765 101.374 134.233 100.848 134.686L100.749 134.772L100.669 134.843L100.589 134.915C100.544 134.955 100.499 134.995 100.452 135.032L100.254 135.197C99.956 135.449 99.52 135.806 98.9463 136.268L98.9399 136.273C98.8505 136.346 98.7376 136.435 98.6012 136.539C98.551 136.577 98.5019 136.615 98.4539 136.652L98.3712 136.715C97.9722 137.023 97.5654 137.329 97.1506 137.632C97.1246 137.65 97.0729 137.688 96.9956 137.746C96.8643 137.844 96.7619 137.919 96.6886 137.971C96.2495 138.286 95.8236 138.581 95.4107 138.856L95.0917 139.078C95.0575 139.102 95.0231 139.126 94.9883 139.148C94.3982 139.537 93.7872 139.923 93.1553 140.305L93.1461 140.31C93.3774 150.816 97.2951 158.232 104.899 162.559C104.9 162.559 104.902 162.56 104.903 162.561ZM93.1353 128.236C93.4493 127.981 93.6922 127.78 93.8641 127.635L94.0621 127.471L94.0756 127.459L94.1552 127.388L94.3292 127.235C94.7991 126.83 95.2489 126.428 95.6787 126.029L95.8253 125.887L96.0277 125.694L96.1784 125.548C96.5995 125.146 96.9459 124.807 97.2176 124.531C97.2581 124.489 97.3285 124.417 97.429 124.315C97.6004 124.141 97.7231 124.014 97.7971 123.936C98.1301 123.583 98.3794 123.315 98.5452 123.132C98.8197 122.829 99.0227 122.603 99.1543 122.453C99.428 122.145 99.6664 121.87 99.8696 121.627C99.8932 121.599 99.9173 121.571 99.9416 121.543L99.961 121.521C100.189 121.254 100.352 121.059 100.451 120.936C100.54 120.827 100.676 120.657 100.86 120.424C100.962 120.296 101.039 120.198 101.092 120.131C101.332 119.828 101.519 119.588 101.653 119.41C101.842 119.162 102.036 118.901 102.235 118.626L102.797 117.846L102.819 117.815L103.309 117.099L103.311 117.096C103.344 117.047 103.406 116.954 103.499 116.816C103.668 116.564 103.788 116.384 103.858 116.274C103.965 116.111 104.109 115.885 104.29 115.597C104.328 115.536 104.357 115.49 104.378 115.456C104.573 115.153 104.739 114.885 104.877 114.652C104.898 114.616 104.92 114.58 104.942 114.545C105.011 114.435 105.127 114.238 105.289 113.956C105.325 113.894 105.353 113.846 105.371 113.813C105.591 113.43 105.753 113.146 105.856 112.96L106.027 112.645L106.306 112.122C106.44 111.873 106.587 111.591 106.746 111.278C106.819 111.134 106.935 110.898 107.092 110.573C107.137 110.478 107.172 110.405 107.196 110.356C107.213 110.32 107.251 110.241 107.309 110.118C107.427 109.87 107.51 109.694 107.557 109.589C107.708 109.262 107.852 108.94 107.988 108.622L108.004 108.58C108.048 108.477 108.098 108.361 108.153 108.233C108.24 108.031 108.301 107.889 108.334 107.807C108.436 107.558 108.583 107.187 108.773 106.695C108.806 106.611 108.831 106.547 108.849 106.501L108.93 106.284C108.956 106.217 108.98 106.157 109 106.106C109.044 105.996 109.071 105.926 109.082 105.896C109.28 105.353 109.469 104.803 109.649 104.247L109.805 103.768C109.931 103.364 110.073 102.88 110.231 102.318L110.353 101.873C110.486 101.389 110.605 100.913 110.713 100.445L110.766 100.224C110.856 99.8165 110.954 99.3298 111.062 98.7642C111.104 98.5444 111.164 98.2039 111.239 97.7427L111.24 97.7413L111.286 97.4468C111.291 97.4136 111.297 97.3803 111.302 97.3468C111.335 97.1476 111.356 97.0084 111.367 96.9292C111.395 96.7383 111.429 96.4795 111.468 96.1528C111.482 96.0307 111.493 95.9379 111.501 95.8744L111.551 95.4529C111.576 95.2556 111.592 95.114 111.6 95.0279C111.626 94.7717 111.656 94.3788 111.689 93.8493L111.691 93.8218L111.715 93.4636C111.719 93.4193 111.721 93.3886 111.722 93.3716C111.731 93.2627 111.736 93.1977 111.737 93.1766C111.768 92.5227 111.784 91.8907 111.784 91.2807V79.3334C111.683 79.4164 111.58 79.5026 111.473 79.592C111.434 79.6239 111.396 79.6552 111.357 79.6859L111.24 79.7802C111.239 79.7812 111.238 79.7822 111.237 79.7833L111.249 79.7743C111.126 79.8862 111.041 79.9618 110.993 80.0012C110.538 80.3944 110.077 80.8076 109.611 81.2411C109.514 81.3295 109.345 81.4906 109.104 81.7244C108.688 82.1222 108.331 82.4721 108.034 82.7741C107.843 82.9645 107.658 83.1541 107.479 83.3429C107.121 83.7221 106.86 84.0021 106.696 84.1831C106.414 84.4937 106.204 84.7277 106.065 84.8851C105.951 85.0125 105.772 85.2195 105.528 85.5059C105.432 85.6192 105.366 85.6963 105.331 85.7372C105.056 86.0624 104.873 86.2807 104.78 86.3921L104.435 86.827L104.094 87.2552C103.841 87.5734 103.643 87.8273 103.498 88.0169C103.372 88.1822 103.169 88.4556 102.89 88.8374C102.689 89.1089 102.493 89.3801 102.302 89.651C102.166 89.8402 101.994 90.0899 101.787 90.4002C101.534 90.7732 101.359 91.034 101.262 91.1826C101.225 91.2418 101.17 91.3279 101.098 91.4409C100.933 91.6994 100.805 91.9027 100.713 92.0507C100.474 92.4308 100.313 92.6903 100.229 92.8291L99.9616 93.2888L99.698 93.7424C99.551 93.995 99.3887 94.2817 99.2111 94.6025C99.0755 94.8467 98.9312 95.1137 98.7783 95.4034C98.7492 95.4597 98.7058 95.5433 98.6481 95.6541C98.497 95.9446 98.3829 96.1669 98.3057 96.321C98.1488 96.6297 97.9937 96.9454 97.8403 97.268L97.8392 97.2703C97.658 97.6465 97.5293 97.9186 97.453 98.0866C97.3556 98.3021 97.2097 98.633 97.0154 99.0794C96.9949 99.1266 96.9646 99.1963 96.9244 99.2882C96.8019 99.5691 96.7118 99.7803 96.6541 99.9218C96.502 100.289 96.3327 100.718 96.1463 101.211C96.1314 101.25 96.1094 101.306 96.0801 101.382C95.9928 101.607 95.9293 101.774 95.8897 101.882C95.7393 102.291 95.5393 102.876 95.2897 103.637C95.2779 103.671 95.262 103.715 95.2419 103.771L95.2393 103.772C95.2279 103.809 95.2161 103.847 95.204 103.884C95.1874 103.939 95.1706 103.991 95.1534 104.043C95.0129 104.485 94.8672 104.979 94.7164 105.526C94.7107 105.546 94.698 105.593 94.6784 105.668C94.6411 105.81 94.6173 105.898 94.607 105.932C94.4938 106.355 94.3708 106.848 94.2382 107.411C94.2266 107.464 94.2138 107.518 94.1998 107.575L94.1965 107.589C94.082 108.092 93.9774 108.598 93.8825 109.107C93.8433 109.324 93.7855 109.662 93.7091 110.122C93.6976 110.191 93.6881 110.247 93.6806 110.293C93.6225 110.634 93.5794 110.898 93.5513 111.084C93.5269 111.253 93.4925 111.53 93.4482 111.915C93.4309 112.065 93.421 112.149 93.4184 112.166C93.4056 112.294 93.3859 112.469 93.3592 112.691C93.3403 112.848 93.3287 112.949 93.3243 112.992C93.3052 113.194 93.2806 113.518 93.2505 113.962C93.2397 114.12 93.2313 114.243 93.2252 114.328C93.2203 114.397 93.213 114.492 93.2032 114.615C93.1908 114.769 93.1834 114.871 93.1809 114.923C93.1505 115.562 93.1353 116.203 93.1353 116.846V128.236Z" stroke="#0F0D0C" stroke-width="3.5"/>
+</svg>
diff --git a/apps/desktop/tests/README.md b/apps/desktop/tests/README.md
new file mode 100644
index 00000000..2e786f4c
--- /dev/null
+++ b/apps/desktop/tests/README.md
@@ -0,0 +1,93 @@
+# Desktop behavior tests
+
+Start with the user capability, then choose the smallest layer that can observe its
+contract. Node state tests explain decision rules; browser scenarios exercise the
+production React components and their wiring through synthetic IPC. Neither layer
+proves native authorization, persistence, process cleanup or real model calls.
+
+## Capability map
+
+| User capability | Representative tests | Unique guarantee |
+| --- | --- | --- |
+| Enable or edit Codex routing | `codex.enable.draft-cancel`, `codex.routing.fixed-binding`, `codex.routing.mixed-native-default` in [Agent scenarios](v3/browser/agent-trust-scenarios.mjs) | Cancelling never applies; configured fixed overrides, native reasoning and the chosen default survive save; service responsibility is explained. |
+| Configure Claude routing and collaboration | `claude.enable.shared-presets`, `agent.configuration.independent-facets`, `claude.collaboration.check-before-save`, `claude.collaboration.retry-preserves-edit` | Ordinary Claude entry and account Default limitations remain clear; prerequisite checks precede mutation; retry preserves edits. |
+| Enable, recover or disable Qoder task collaboration | `qoder.collaboration.enable-without-model`, `qoder.collaboration.retry-and-restore` | No model connection or published Plan is required; required capability checks happen during save. Login and changed-Skill failures retain edits and enabled collaboration with the shared retry action; restore keeps model configuration unchanged. |
+| Add and adjust Qoder model routes | `qoder.routing.additional-plans`, `qoder.routing.adjust-and-restore` | Cancelled drafts do not write; only selected Plans are submitted; unavailable choices stay visible; token changes and independent restores keep the other facet. Native default/provider preservation and real model calls require production acceptance. |
+| Configure Agents through common interactions | `agent.configuration.shared-interactions`; [Agent status projection](agent-status.test.mjs) | Codex, Claude Code and Qoder show configured routing without verification badges or extra check buttons. Ordinary navigation never probes a model; backend verification facts cannot hide actual configuration/recovery state. |
+| Diagnose or recover an Agent | `codex.restore.conflict-active`, `agent.recovery.non-runnable` | A file conflict preserves current access and unrelated settings; executable diagnostics do not hide recovery. |
+| Choose or replace a Worker installation | `worker.discovery.visible-only`, `worker.installation.harness-isolation`, `worker.installation.replace`, `worker.installation.latest-edit` in [routing/Worker scenarios](v3/browser/routing-worker-scenarios.mjs) | Discovery follows visible configuration; installations stay independent; one explicit save commits the latest edit exactly once. |
+| Resume incomplete Qoder model configuration | `qoder.routing.resume-pending` | Recovery requires trusted authority and the exact original context/Operation; it refreshes backend state, creates no new setup, preserves collaboration and does not fabricate verification. |
+| Select Qoder as a Worker | `qoder.installation.single-cli` | A single CLI is saved through the existing confirmation flow without adapter/Node placeholders; switching execution Agents preserves each installation. |
+| Continue editing after route save | `routing.save.unobserved-editable` | An unobserved result does not lock the editor or other routes. |
+| Publish a smaller budget used by Qoder | `routing.publish.qoder-budget-conflict`, `desktop.routing.qoder-budget-checkpoint` | Both immediate rejection and an accepted operation's checkpoint failure keep edits and explain disabling only Qoder model routing before publication and reconfiguration; neither disables collaboration nor calls models. |
+| Follow a submitted operation | `desktop.operation.dismiss-observes`, `desktop.operation.identity-retry-converges`, `desktop.operation.repeated-submission` in [shell scenarios](v3/browser/product-shell-scenarios.mjs); [operation rules](operation-feedback.test.mjs) | Dismissal does not cancel observation; mismatched identity stays neutral through grace/retry; repeated accepted or unknown saves restart observation; success refreshes and dismisses. Pure tests retain identity, sequence and terminal-state edges. |
+| Adjust presentation | `desktop.settings.persisted-scale`; [preference tests](presentation-preferences.test.mjs) | All supported scales reach the real shell and storage; parsing/storage failure rules remain separately testable. |
+| Return to routing or configure a classifier | `desktop.routing.reactivation-models`, `desktop.routing.classifier-protocol` | An existing editor refreshes saved model names; quality uses active models; selection, curl copy and native-save outcomes are visible. |
+| Inspect a model or open its documentation | `desktop.models.documentation-retains-input`; [model-to-route scenario](v3/browser/model-to-route-scenarios.mjs) | Local readiness does not claim inference success; browser failure retains form input; web anchors retain their default action; route creation uses the selected model. |
+
+The focused Agent fixture explicitly spans the application grid and keeps its evidence
+note outside the page viewport. Layout assertions must observe usable component width;
+a DOM element that exists outside a valid viewport does not establish readability.
+
+The shell fixture mounts the real `DesktopApp`, including navigation, forms and
+observation effects. It controls only IPC responses and records boundary calls;
+it does not call private component callbacks. In particular, browser checks of
+`save_classifier_openapi` and `open_external_url` verify UI dispatch/outcomes, not
+the native OS action.
+
+## Run levels
+
+From `apps/desktop`, with the repository's Node 24 and installed dependencies:
+
+```sh
+npm test
+npm run build
+node_modules/.bin/tsc -p tests/v3/browser/tsconfig.json --noEmit
+CHROME_BIN=/path/to/chrome node tests/v3/visual/agent-trust.mjs /tmp/hiroute-agent-tests
+```
+
+The full browser run discovers all Agent, routing/Worker and shell scenarios, plus
+the model-to-route scenario. Focused browser flags remain available:
+`--claude-collaboration-only`, `--worker-replacement-only`, `--route-save-only`,
+and `--shell-only` (after the output directory). Unknown flags fail. For selection
+logic alone, run `node --test tests/scenario-selection.test.mjs`.
+
+Choose the configured native Desktop/Pilot entry separately for real authorization,
+recovery, file changes, task cancellation and external-browser/download acceptance.
+See [validation runner](../../../scripts/validation.py) and
+[test planner](../../../scripts/test-plan.py). Do not cite a mock-IPC report as
+native or daemon acceptance.
+
+## Keep selection and assertions stable
+
+Scenarios carry a stable `id`, capability tags and a display name. IDs describe the
+user guarantee and remain stable when names, files or implementation details change.
+The reviewed [required sets](v3/browser/scenario-requirements.mjs) are independent of
+the discovered catalog: deleting a required scenario, selecting nothing, returning
+duplicate results or omitting a selected case fails. Full runs include newly added
+scenarios automatically. Batch size is a transport detail, never a scenario selector.
+Keep required-ID changes in the same review as an explicit replacement of the
+removed guarantee. `green`, `red` and missing execution remain distinct.
+
+[UI consistency](ui-consistency.test.mjs) retains static stylesheet conventions,
+shared Disclosure usage, localized copy, native capabilities and the public OpenAPI
+byte contract. The native command authority check compares all bundled Tauri handlers
+with the AppManifest, generated permission files and explicit main-window permissions.
+Adding a command requires reviewing all four together; mock IPC and native compilation
+cannot establish that the real WebView may invoke it. Its former source-shape assertions for Agent forms are covered by the
+Agent IDs above; settings, classifier actions, model links, route reactivation and
+operation effect wiring are covered by the shell IDs. Moving a component no longer
+requires preserving a callback expression, a hook dependency spelling or a source
+file location. Keep pure state tests when they protect independent identity,
+cancellation, ordering or recovery edges that one browser path cannot cover.
+
+When reviewing churn, use `git log -p -- <test> <producer>` to distinguish a product
+contract change from fixture repair. Do not use test-count reduction as an acceptance
+target, or rewrite an expectation merely to match the implementation. Current
+fixtures follow current product types; historical recovery fixtures keep their
+separate registration and meaning.
+
+Remaining work outside this batch: Observation contract constants that compare to
+themselves need a producer/consumer oracle; duplicated Rust process harnesses need
+an ownership review before extraction. Those changes must preserve their unique
+cancellation, identity and cleanup assertions and do not belong in these UI fixtures.
diff --git a/apps/desktop/tests/agent-collaboration-check-feedback.test.mjs b/apps/desktop/tests/agent-collaboration-check-feedback.test.mjs
new file mode 100644
index 00000000..58440b45
--- /dev/null
+++ b/apps/desktop/tests/agent-collaboration-check-feedback.test.mjs
@@ -0,0 +1,85 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { collaborationCheckFailureMessage } from '../src/features/agents/collaboration-check-feedback.ts';
+
+const schema = 'hiroute.agent-collaboration-check-failure/v1';
+const reasons = [
+ 'login_required', 'installed_skill_missing', 'installed_skill_changed', 'installed_skill_invalid',
+ 'native_context_unavailable', 'native_context_changed', 'dependency_unavailable',
+ 'check_timed_out', 'verification_failed',
+];
+const sensitive = 'private-stage /private/native/settings token=secret-login-token';
+const failure = reason => ({
+ source: 'backend',
+ envelope: {
+ error: { details_schema: schema, message_key: sensitive },
+ data: { schema, reason, stage: sensitive, path: sensitive, secret: sensitive },
+ },
+});
+
+test('login failure directs the user to sign in normally with the selected client and retry', () => {
+ assert.match(collaborationCheckFailureMessage(failure('login_required'), 'zh'), /正常打开已选客户端完成登录.*重试/);
+ assert.match(collaborationCheckFailureMessage(failure('login_required'), 'en'), /selected client.*Open it normally, sign in, then retry/);
+});
+
+test('missing, changed and invalid installed Skills require target review and explicit safe recovery', () => {
+ for (const reason of ['installed_skill_missing', 'installed_skill_changed', 'installed_skill_invalid']) {
+ const zh = collaborationCheckFailureMessage(failure(reason), 'zh');
+ const en = collaborationCheckFailureMessage(failure(reason), 'en');
+ assert.match(zh, /检查协作目标.*安全恢复或重新启用.*重试/);
+ assert.match(zh, /不会自动覆盖/);
+ assert.match(en, /Review the collaboration target.*safely restore or re-enable.*retry/);
+ assert.match(en, /will not be overwritten automatically/);
+ }
+});
+
+test('unavailable or changed context and dependencies guide the user to select a usable target again', () => {
+ for (const reason of ['native_context_unavailable', 'native_context_changed', 'dependency_unavailable']) {
+ assert.match(collaborationCheckFailureMessage(failure(reason), 'zh'), /重新.*选择.*重试/);
+ assert.match(collaborationCheckFailureMessage(failure(reason), 'en'), /[Ss]elect.*again.*retry/);
+ }
+});
+
+test('timeout and failed verification remain unsuccessful and offer a retry', () => {
+ assert.match(collaborationCheckFailureMessage(failure('check_timed_out'), 'zh'), /超时.*尚未确认协作可用.*重试/);
+ assert.match(collaborationCheckFailureMessage(failure('check_timed_out'), 'en'), /timed out.*has not been verified.*retry/);
+ assert.match(collaborationCheckFailureMessage(failure('verification_failed'), 'zh'), /验证未通过.*重试/);
+ assert.match(collaborationCheckFailureMessage(failure('verification_failed'), 'en'), /verification failed.*retry/);
+});
+
+test('only a matching typed backend failure can produce collaboration feedback', () => {
+ const wrongDetails = failure('login_required');
+ wrongDetails.envelope.error.details_schema = 'hiroute.other-failure/v1';
+ const wrongData = failure('login_required');
+ wrongData.envelope.data.schema = 'hiroute.agent-collaboration-check-failure/v2';
+ const noDetails = failure('login_required');
+ delete noDetails.envelope.error.details_schema;
+ const noData = failure('login_required');
+ delete noData.envelope.data;
+ for (const error of [
+ null, undefined, sensitive, new Error(sensitive), [],
+ wrongDetails, wrongData, noDetails, noData,
+ { ...failure('login_required'), source: 'transport' },
+ { schema, reason: 'login_required' },
+ failure('future_reason'), failure(sensitive), failure('toString'), failure('__proto__'),
+ failure({ reason: 'login_required', sensitive }), failure(['login_required']),
+ ]) {
+ for (const language of ['zh', 'en']) {
+ assert.equal(collaborationCheckFailureMessage(error, language), null);
+ }
+ }
+});
+
+test('known failures never expose raw native details or claim a successful delegation', () => {
+ for (const reason of reasons) {
+ const error = failure(reason);
+ const before = structuredClone(error);
+ for (const language of ['zh', 'en']) {
+ const message = collaborationCheckFailureMessage(error, language);
+ assert.equal(typeof message, 'string');
+ assert.doesNotMatch(message, /private-stage|\/private\/native|secret-login-token|token=/);
+ assert.doesNotMatch(message, /Qoder|Codex|Claude|验证通过|完成委派|verification succeeded|delegation completed/);
+ }
+ assert.deepEqual(error, before);
+ }
+});
diff --git a/apps/desktop/tests/agent-editor-state.test.mjs b/apps/desktop/tests/agent-editor-state.test.mjs
index 38192292..b15f6db0 100644
--- a/apps/desktop/tests/agent-editor-state.test.mjs
+++ b/apps/desktop/tests/agent-editor-state.test.mjs
@@ -1,6 +1,8 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { agentEditorSeed, codexDefaultChoiceValid, commonClaudePlan, sharedClaudePlan, editorFingerprint } from '../src/agent-editor-state.ts';
+import { agentModelFormInvalid } from '../src/features/agents/editor-state.ts';
+import { agentModelStatus } from '../src/features/agents/status.ts';
const codexSelection = {
mode: 'codex_default',
@@ -54,6 +56,31 @@ test('collaboration retains only its task trigger mode', () => {
assert.equal(value.triggerMode, 'delegate_by_default');
});
+test('Qoder collaboration-only status seeds its trigger without making a model editor or selecting model routes', () => {
+ for (const collaboration of [
+ { state: 'not_configured', restore_point_ref: null, current_selection: null },
+ { state: 'configured', restore_point_ref: 'restore/qoder-skill', current_selection: { trigger_mode: 'explicit' } },
+ { state: 'configured', restore_point_ref: 'restore/qoder-skill', current_selection: { trigger_mode: 'delegate_by_default' } },
+ ]) {
+ const qoder = {
+ agent_id: 'agent_qoder_default', context_id: 'context/qoder', status_error: null,
+ settings: {
+ schema: 'hiroute.agent-collaboration-only-settings-status/v2', context_id: 'context/qoder', collaboration,
+ },
+ };
+ assert.equal(agentModelStatus(qoder), null);
+ const model = agentEditorSeed(qoder, 'model', ['only-route']);
+ assert.equal(model.known, false);
+ assert.deepEqual(model.allowedPlanIds, []);
+ assert.deepEqual(model.fixedModels, []);
+ assert.equal(commonClaudePlan(model.claudePresets), '');
+ const seed = agentEditorSeed(qoder, 'collaboration', ['only-route']);
+ assert.equal(seed.known, true);
+ assert.equal(seed.triggerMode, collaboration.current_selection?.trigger_mode ?? 'explicit');
+ assert.deepEqual(seed.allowedPlanIds, []);
+ }
+});
+
test('unknown, drift and unavailable status cannot become empty authorization', () => {
for (const state of ['configured', 'drift', 'pending', 'needs_attention']) {
assert.equal(agentEditorSeed({ ...codex, settings: { state } }, 'model').known, false);
@@ -61,6 +88,28 @@ test('unknown, drift and unavailable status cannot become empty authorization',
assert.equal(agentEditorSeed({ ...codex, status_error: 'UNAVAILABLE' }, 'model').known, false);
});
+test('Qoder preserves route selections without a native catalog and retains unavailable choices for repair', () => {
+ const agent = { agent_id: 'agent_qoder_default', status_error: null, native_model_catalog: null,
+ settings: { state: 'not_configured', current_selection: null } };
+ const initial = agentEditorSeed(agent, 'model', ['only-route']);
+ assert.equal(initial.known, true);
+ assert.deepEqual(initial.allowedPlanIds, ['only-route']);
+ assert.deepEqual(initial.fixedModels, []);
+ assert.deepEqual(initial.defaultChoice, { kind: 'preserve_native' });
+ assert.equal(agentModelFormInvalid(agent, initial, ['only-route']), false);
+ assert.equal(agentModelFormInvalid(agent, initial, []), true);
+ const saved = { ...agent, settings: { state: 'configured', current_selection: {
+ mode: 'qoder_additional', allowed_plan_ids: ['route/retired', 'route/current'],
+ } } };
+ const seed = agentEditorSeed(saved, 'model', ['route/new']);
+ assert.equal(seed.known, true);
+ assert.deepEqual(seed.allowedPlanIds, ['route/retired', 'route/current']);
+ assert.equal(agentModelFormInvalid(saved, seed, ['route/current']), true);
+ const repaired = { ...seed, allowedPlanIds: ['route/current'] };
+ assert.equal(agentModelFormInvalid(saved, repaired, ['route/current']), false);
+ assert.notEqual(editorFingerprint(seed), editorFingerprint(repaired));
+});
+
test('Codex discovery facts do not change the initial shared configuration', () => {
const desktop = agentEditorSeed({ ...codex, available_surfaces: ['codex_desktop'], settings: { state: 'not_configured' } }, 'model');
const cli = agentEditorSeed({
@@ -100,7 +149,18 @@ test('configured collaboration requires an explicit current selection', () => {
test('all model and collaboration choices participate in dirty tracking', () => {
const { known, ...values } = agentEditorSeed(codex, 'model');
assert.equal(known, true);
- assert.notEqual(editorFingerprint(values), editorFingerprint({ ...values, triggerMode: 'delegate_by_default' }));
+ const edits = [
+ { triggerMode: 'delegate_by_default' },
+ { nativeModelMode: 'hiroute_only' },
+ { allowedPlanIds: ['a'] },
+ { defaultChoice: { kind: 'fixed_model', client_model_id: 'native-model' } },
+ { fixedModels: [{ client_model_id: 'native-model', candidate: { binding_id: 'binding/other-account' } }] },
+ { fixedModels: [{ client_model_id: 'native-model', candidate: { binding_id: 'binding/native', reasoning: { kind: 'toggle', enabled: false } } }] },
+ { claudePresets: { ...values.claudePresets, haiku: { kind: 'plan', plan_id: 'a' } } },
+ ];
+ for (const edit of edits) {
+ assert.notEqual(editorFingerprint(values), editorFingerprint({ ...values, ...edit }), JSON.stringify(edit));
+ }
assert.equal(
editorFingerprint(values),
editorFingerprint({ ...values, allowedPlanIds: [...values.allowedPlanIds].reverse() }),
@@ -156,3 +216,13 @@ test('collaboration and unreadable initial settings do not pick model routes', (
assert.equal(seed.known, false);
assert.deepEqual(seed.allowedPlanIds, []);
});
+
+test('an existing model selection from another ecosystem cannot become an editable draft', () => {
+ for (const [agent, other] of [[codex, claude], [claude, codex]]) {
+ const seed = agentEditorSeed({
+ ...agent,
+ settings: { ...agent.settings, current_selection: other.settings.current_selection },
+ }, 'model', ['replacement']);
+ assert.equal(seed.known, false);
+ }
+});
diff --git a/apps/desktop/tests/agent-settings-request.test.mjs b/apps/desktop/tests/agent-settings-request.test.mjs
new file mode 100644
index 00000000..74956d84
--- /dev/null
+++ b/apps/desktop/tests/agent-settings-request.test.mjs
@@ -0,0 +1,200 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { agentSettingsSpec, agentTokenSpec, prerequisiteCheck } from '../src/features/agents/settings-request.ts';
+import { agentEditorSeed, agentModelFormInvalid, EMPTY_EDITOR_VALUES } from '../src/features/agents/editor-state.ts';
+
+const codex = {
+ agent_id: 'agent_codex_default', context_id: 'context/current', status_error: null,
+ settings: { state: 'configured', restore_point_ref: 'restore/model', collaboration: { restore_point_ref: 'restore/skill' } },
+ codex_access: {
+ slot_occupied: false, selected_mode: 'profile',
+ profile_context_id: 'context/profile', root_context_id: 'context/root',
+ },
+};
+const claude = { ...codex, agent_id: 'agent_claude_default', codex_access: undefined };
+const qoder = {
+ agent_id: 'agent_qoder_default', context_id: 'context/qoder', status_error: null,
+ settings: {
+ schema: 'hiroute.agent-collaboration-only-settings-status/v2', context_id: 'context/qoder',
+ collaboration: { state: 'configured', restore_point_ref: 'restore/qoder-skill', current_selection: { trigger_mode: 'explicit' } },
+ },
+};
+const fixed = { client_model_id: 'native-a', candidate: { binding_id: 'binding/account-a', reasoning: { kind: 'profile', profile: 'high' } } };
+const draft = {
+ values: {
+ ...EMPTY_EDITOR_VALUES, fixedModels: [fixed], nativeModelMode: 'preserve_available',
+ allowedPlanIds: ['route/b', 'route/a'], defaultChoice: { kind: 'plan', plan_id: 'route/b' },
+ claudePresets: { opus: { kind: 'plan', plan_id: 'route/a' }, sonnet: { kind: 'preserve_native' }, haiku: { kind: 'plan', plan_id: 'route/b' } },
+ triggerMode: 'delegate_by_default',
+ },
+ codexMode: 'profile', restoreNativeModel: 'native-on-restore',
+};
+const wire = value => JSON.parse(JSON.stringify(value));
+
+test('Codex configuration submits its exact allowlist, default and account-bound fixed model without changing collaboration', () => {
+ const before = structuredClone({ codex, draft });
+ assert.deepEqual(wire(agentSettingsSpec(codex, 'model', false, draft)), {
+ schema_version: { major: 2, minor: 0 }, context_id: 'context/profile',
+ model: { intent: 'configure', settings: {
+ mode: 'codex_default', native_model_mode: 'preserve_available', fixed_models: [fixed],
+ allowed_plan_ids: ['route/b', 'route/a'], default_selection: { kind: 'plan', plan_id: 'route/b' },
+ } },
+ collaboration: { intent: 'keep' },
+ });
+ assert.deepEqual({ codex, draft }, before);
+});
+
+test('new Codex access targets the chosen mode while an occupied slot retains its current context', () => {
+ assert.equal(agentSettingsSpec(codex, 'model', false, { ...draft, codexMode: 'root' }).context_id, 'context/root');
+ const occupied = { ...codex, codex_access: { ...codex.codex_access, slot_occupied: true } };
+ assert.equal(agentSettingsSpec(occupied, 'model', false, { ...draft, codexMode: 'root' }).context_id, 'context/current');
+});
+
+test('Claude configuration preserves independent native preset mappings and does not acquire a Codex default or allowlist', () => {
+ assert.deepEqual(wire(agentSettingsSpec(claude, 'model', false, draft)), {
+ schema_version: { major: 2, minor: 0 }, context_id: 'context/current',
+ model: { intent: 'configure', settings: {
+ mode: 'claude_launcher', surfaces: ['claude_cli'], fixed_models: [fixed],
+ preset_mappings: { opus: { kind: 'plan', plan_id: 'route/a' }, sonnet: { kind: 'preserve_native' }, haiku: { kind: 'plan', plan_id: 'route/b' } },
+ } },
+ collaboration: { intent: 'keep' },
+ });
+});
+
+test('ordinary disable requests restoration from the saved reference and keeps model and collaboration recovery separate', () => {
+ const profile = wire(agentSettingsSpec(codex, 'model', true, draft));
+ assert.deepEqual(profile, {
+ schema_version: { major: 2, minor: 0 }, context_id: 'context/profile',
+ model: { intent: 'restore', restore_point_ref: 'restore/model' }, collaboration: { intent: 'keep' },
+ });
+ const root = { ...codex, codex_access: { ...codex.codex_access, slot_occupied: true, selected_mode: 'root' } };
+ assert.equal(agentSettingsSpec(root, 'model', true, draft).restore_native_model, 'native-on-restore');
+ assert.equal(agentSettingsSpec(claude, 'model', true, draft).restore_native_model, undefined);
+ assert.deepEqual(wire(agentSettingsSpec(codex, 'collaboration', true, draft)), {
+ schema_version: { major: 2, minor: 0 }, context_id: 'context/root',
+ model: { intent: 'keep' }, collaboration: { intent: 'restore', restore_point_ref: 'restore/skill' },
+ });
+});
+
+test('enabling task routing sends only the trigger preference, independently of the model draft', () => {
+ assert.deepEqual(wire(agentSettingsSpec(codex, 'collaboration', false, draft)), {
+ schema_version: { major: 2, minor: 0 }, context_id: 'context/root', model: { intent: 'keep' },
+ collaboration: { intent: 'configure', settings: { trigger_mode: 'delegate_by_default' } },
+ });
+});
+
+test('Qoder configures either collaboration trigger and restores only its Skill without a model facet', () => {
+ const before = structuredClone({ qoder, draft });
+ for (const triggerMode of ['explicit', 'delegate_by_default']) {
+ assert.deepEqual(wire(agentSettingsSpec(qoder, 'collaboration', false, {
+ ...draft, values: { ...draft.values, triggerMode },
+ })), {
+ schema_version: { major: 2, minor: 0 }, context_id: 'context/qoder',
+ model: { intent: 'keep' },
+ collaboration: { intent: 'configure', settings: { trigger_mode: triggerMode } },
+ });
+ }
+ assert.deepEqual(wire(agentSettingsSpec(qoder, 'collaboration', true, draft)), {
+ schema_version: { major: 2, minor: 0 }, context_id: 'context/qoder',
+ model: { intent: 'keep' },
+ collaboration: { intent: 'restore', restore_point_ref: 'restore/qoder-skill' },
+ });
+ assert.deepEqual({ qoder, draft }, before);
+});
+
+test('collaboration-only Qoder and cross-ecosystem selections cannot authorize models or tokens', () => {
+ const stale = {
+ ...qoder,
+ settings: { ...claude.settings, current_selection: agentSettingsSpec(claude, 'model', false, draft).model.settings },
+ };
+ for (const agent of [qoder, stale]) {
+ for (const restore of [false, true]) {
+ assert.throws(() => agentSettingsSpec(agent, 'model', restore, draft), /AGENT_INPUT_INVALID/);
+ }
+ for (const regenerate of [false, true]) {
+ assert.throws(() => agentTokenSpec(agent, regenerate), /AGENT_INPUT_INVALID/);
+ }
+ }
+});
+
+test('Qoder adds only selected routes and keeps token rotation and both restores independent', () => {
+ const capable = { ...qoder, settings: { state: 'not_configured', collaboration: qoder.settings.collaboration } };
+ const configure = wire(agentSettingsSpec(capable, 'model', false, draft));
+ assert.deepEqual(configure, {
+ schema_version: { major: 2, minor: 0 }, context_id: 'context/qoder',
+ model: { intent: 'configure', settings: { mode: 'qoder_additional', allowed_plan_ids: ['route/b', 'route/a'] } },
+ collaboration: { intent: 'keep' },
+ });
+ const saved = { ...capable, settings: {
+ state: 'configured', current_selection: configure.model.settings, restore_point_ref: 'restore/qoder-model',
+ collaboration: qoder.settings.collaboration,
+ } };
+ assert.deepEqual(agentTokenSpec(saved, true), {
+ schema_version: { major: 2, minor: 0 }, context_id: 'context/qoder',
+ model: configure.model, collaboration: { intent: 'keep' }, access_token: { intent: 'regenerate' },
+ });
+ assert.deepEqual(wire(agentSettingsSpec(saved, 'model', true, draft)), {
+ schema_version: { major: 2, minor: 0 }, context_id: 'context/qoder',
+ model: { intent: 'restore', restore_point_ref: 'restore/qoder-model' }, collaboration: { intent: 'keep' },
+ });
+ assert.deepEqual(wire(agentSettingsSpec(saved, 'collaboration', true, draft)), {
+ schema_version: { major: 2, minor: 0 }, context_id: 'context/qoder',
+ model: { intent: 'keep' }, collaboration: { intent: 'restore', restore_point_ref: 'restore/qoder-skill' },
+ });
+ for (const agent of [codex, claude]) {
+ const mixed = { ...agent, settings: saved.settings };
+ assert.equal(agentEditorSeed(mixed, 'model').known, false);
+ assert.throws(() => agentSettingsSpec(mixed, 'model', false, draft), /AGENT_INPUT_INVALID/);
+ assert.throws(() => agentTokenSpec(mixed, true), /AGENT_INPUT_INVALID/);
+ }
+});
+
+test('token rotation retains the saved selection without consulting an unsaved model draft', () => {
+ const saved = { ...claude, settings: { ...claude.settings, current_selection: agentSettingsSpec(claude, 'model', false, draft).model.settings } };
+ for (const regenerate of [false, true]) {
+ assert.deepEqual(agentTokenSpec(saved, regenerate), {
+ schema_version: { major: 2, minor: 0 }, context_id: 'context/current',
+ model: { intent: 'configure', settings: saved.settings.current_selection },
+ collaboration: { intent: 'keep' }, access_token: { intent: regenerate ? 'regenerate' : 'keep' },
+ });
+ }
+});
+
+test('a discovered but unsupported ecosystem never borrows the Claude editor or produces a settings intent', () => {
+ const configured = agentSettingsSpec(claude, 'model', false, draft).model.settings;
+ for (const current_selection of [null, configured]) {
+ const unknown = { ...claude, agent_id: 'agent_unregistered', settings: { state: current_selection ? 'configured' : 'not_configured', current_selection } };
+ assert.equal(agentEditorSeed(unknown, 'model', ['only-route']).known, false);
+ assert.equal(agentModelFormInvalid(unknown, draft.values, ['route/a', 'route/b']), true);
+ for (const facet of ['model', 'collaboration']) {
+ for (const restore of [false, true]) assert.throws(() => agentSettingsSpec(unknown, facet, restore, draft), /AGENT_INPUT_INVALID/);
+ }
+ assert.throws(() => agentTokenSpec(unknown, true), /AGENT_INPUT_INVALID/);
+ }
+ assert.throws(() => agentSettingsSpec({ ...codex, context_id: null }, 'model', false, draft), /AGENT_INPUT_INVALID/);
+});
+
+test('pre-save checks follow authoritative capability blockers rather than the ecosystem or the visible form', () => {
+ const blocked = (...capabilities) => ({ applicable: false, blockers: [{ reason: 'capability', capabilities: capabilities.map(capability => ({ capability, reason: 'unconfirmed' })) }] });
+ for (const facet of ['model', 'collaboration']) {
+ assert.equal(prerequisiteCheck(blocked('ingress_authentication', 'skill_loading'), facet), 'native_authentication');
+ assert.equal(prerequisiteCheck({ ...blocked('ingress_authentication'), applicable: true }, facet), null);
+ }
+ assert.equal(prerequisiteCheck(blocked('skill_loading'), 'collaboration'), 'collaboration');
+ assert.equal(prerequisiteCheck(blocked('trusted_cli_execution'), 'collaboration'), 'collaboration');
+ assert.equal(prerequisiteCheck(blocked('skill_loading'), 'model'), null);
+ assert.equal(prerequisiteCheck(blocked('unknown_capability'), 'model'), null);
+});
+
+test('editing model routes retains distinct Codex authorization and Claude preset requirements', () => {
+ const initial = agent => ({ ...agent, settings: { state: 'not_configured', current_selection: null } });
+ for (const agent of [initial(codex), initial(claude)]) {
+ const values = agentEditorSeed(agent, 'model', ['only-route']);
+ assert.equal(agentModelFormInvalid(agent, values, ['only-route']), false);
+ assert.equal(agentModelFormInvalid(agent, values, []), true, 'a route removed while editing must block Save');
+ }
+ const retained = { ...codex, settings: { ...codex.settings, protected_native_model_ids: ['native-a'] } };
+ assert.equal(agentModelFormInvalid(retained, draft.values, ['route/a', 'route/b']), false, 'a protected binding does not need reselection');
+ assert.equal(agentModelFormInvalid(codex, draft.values, ['route/a', 'route/b']), true, 'an unproven independent fixed source must block Save');
+ assert.equal(agentModelFormInvalid(claude, { ...EMPTY_EDITOR_VALUES, fixedModels: [fixed] }, []), false, 'an existing Claude fixed model can survive without a preset route');
+});
diff --git a/apps/desktop/tests/agent-status.test.mjs b/apps/desktop/tests/agent-status.test.mjs
new file mode 100644
index 00000000..ad3abb55
--- /dev/null
+++ b/apps/desktop/tests/agent-status.test.mjs
@@ -0,0 +1,47 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { projectHomeAgents } from '../src/product/home-projections.ts';
+import { deriveHomePrimaryMode } from '../src/features/home/state.ts';
+
+test('a collaboration-only connection does not invent a missing model setup or count as configured before enable', () => {
+ const agent = {
+ agent_id: 'agent_qoder_default', context_id: 'context/native', configuration_state: 'configured',
+ settings: { schema: 'hiroute.agent-collaboration-only-settings-status/v2', context_id: 'context/native',
+ collaboration: { state: 'not_configured', restore_point_ref: null } },
+ };
+ const project = value => projectHomeAgents({ agents: [value] });
+ const projected = project(agent);
+ assert.equal(projected.agents[0].model, 'unsupported');
+ assert.equal(projected.agents[0].collaboration, 'unconfigured');
+ assert.equal(project({ ...agent, agent_id: 'another-collaboration-only-agent' }).agents[0].model, 'unsupported');
+ assert.equal(project({ ...agent, settings: null }).agents[0].model, 'unknown');
+ const reads = {
+ compute: { status: 'ready', data: { sources: [], saveAttempts: [] } },
+ plans: { status: 'ready', data: { plans: [], drafts: [] } },
+ agents: { status: 'ready', data: projected },
+ activity: { status: 'ready', data: { sessions: [], tasks: [] } },
+ };
+ assert.equal(deriveHomePrimaryMode(reads), 'first-use');
+ agent.settings.collaboration = { state: 'configured', restore_point_ref: 'restore/skill', current_selection: { trigger_mode: 'explicit' } };
+ reads.agents.data = project(agent);
+ assert.equal(reads.agents.data.agents[0].model, 'unsupported');
+ assert.equal(reads.agents.data.agents[0].collaboration, 'configured');
+ assert.equal(deriveHomePrimaryMode(reads), 'partial');
+});
+
+test('Agent presentation follows configuration and recovery rather than model verification', () => {
+ const agent = { agent_id: 'agent_qoder_default', context_id: 'context/native', configuration_state: 'configured',
+ settings: { state: 'not_configured', model_verified: false,
+ collaboration: { state: 'configured', restore_point_ref: 'restore/skill' } } };
+ const project = () => projectHomeAgents({ agents: [agent] }).agents[0];
+ assert.equal(project().model, 'unconfigured');
+ assert.equal(project().collaboration, 'configured');
+ agent.settings.state = 'configured';
+ assert.equal(project().model, 'configured');
+ agent.settings.model_verified = true;
+ assert.equal(project().model, 'configured');
+ agent.settings.state = 'drift';
+ assert.equal(project().model, 'degraded');
+ agent.settings.state = 'pending';
+ assert.equal(project().model, 'pending');
+});
diff --git a/apps/desktop/tests/plan-editor-errors.test.mjs b/apps/desktop/tests/plan-editor-errors.test.mjs
index 35bad8b2..65f47213 100644
--- a/apps/desktop/tests/plan-editor-errors.test.mjs
+++ b/apps/desktop/tests/plan-editor-errors.test.mjs
@@ -15,3 +15,13 @@ test('stale route and draft revisions have actionable messages', () => {
assert.match(planErrorMessage('PLAN_HEAD_STALE', 'zh'), /生效配置/);
assert.match(planErrorMessage('DRAFT_REVISION_STALE', 'en'), /latest draft/);
});
+test('a Qoder budget conflict requires model reconnection and preserves independent task collaboration', () => {
+ const failure = { source: 'backend', envelope: { error: {
+ code: 'QODER_MODEL_BUDGET_CONFLICT', message_key: 'agent.error.qoder_model_budget_conflict', details: 'private-native-config',
+ } } };
+ assert.equal(planErrorCode(failure), 'QODER_MODEL_BUDGET_CONFLICT');
+ assert.match(planErrorMessage(failure, 'zh'), /停用 Qoder 的模型路由.*再发布此计划并重新配置模型路由/);
+ assert.match(planErrorMessage(failure, 'zh'), /任务协作无需停用/);
+ assert.match(planErrorMessage(failure, 'en'), /Disable Qoder model routing.*publish this plan.*configure model routing again/);
+ assert.ok(!planErrorMessage(failure, 'zh').includes('private-native-config'));
+});
diff --git a/apps/desktop/tests/scenario-selection.test.mjs b/apps/desktop/tests/scenario-selection.test.mjs
new file mode 100644
index 00000000..e5f43838
--- /dev/null
+++ b/apps/desktop/tests/scenario-selection.test.mjs
@@ -0,0 +1,73 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { selectScenarios, assertScenarioResults, runScenarios } from './v3/browser/scenario-selection.mjs';
+import { agentTrustScenarioCatalog } from './v3/browser/agent-trust-scenarios.mjs';
+import { routingWorkerScenarioCatalog } from './v3/browser/routing-worker-scenarios.mjs';
+import { productShellScenarioCatalog } from './v3/browser/product-shell-scenarios.mjs';
+import { agentTrustRequired, routingWorkerRequired, productShellRequired, focusedRequirements } from './v3/browser/scenario-requirements.mjs';
+
+const catalogs = [
+ [agentTrustScenarioCatalog, agentTrustRequired],
+ [routingWorkerScenarioCatalog, routingWorkerRequired],
+ [productShellScenarioCatalog, productShellRequired],
+];
+
+test('full mode discovers every current scenario and checks the independent required set', () => {
+ for (const [catalog, requiredIds] of catalogs) {
+ assert.deepEqual(selectScenarios(catalog, { requiredIds }), catalog);
+ const extra = { id: 'future.capability', name: 'A newly added scenario', capabilities: ['future'] };
+ assert.equal(selectScenarios([...catalog, extra], { requiredIds }).at(-1), extra);
+ for (const missing of requiredIds) {
+ assert.throws(() => selectScenarios(catalog.filter(item => item.id !== missing), { requiredIds }), /Required scenario is missing/);
+ }
+ }
+});
+
+test('focused capabilities survive reordering and renamed display copy', () => {
+ const all = catalogs.flatMap(([catalog]) => catalog);
+ for (const [capability, requiredIds] of Object.entries(focusedRequirements)) {
+ const reordered = all.toReversed().map(item => ({ ...item, name: 'Reworded user-facing scenario' }));
+ const actual = selectScenarios(reordered, { capability, requiredIds }).map(item => item.id);
+ assert.deepEqual(actual.toSorted(), requiredIds.toSorted());
+ assert.throws(() => selectScenarios(reordered, { capability: 'other', requiredIds }), /No scenarios selected/);
+ }
+});
+
+test('empty, unknown, duplicate and silently excluded selections fail before execution', () => {
+ const catalog = agentTrustScenarioCatalog;
+ assert.throws(() => selectScenarios(catalog, 3), /options object/);
+ assert.throws(() => selectScenarios(catalog, { requiredIds: 'not-a-list' }), /must be a list/);
+ assert.throws(() => selectScenarios(catalog, { capability: '' }), /nonempty string/);
+ assert.throws(() => selectScenarios([]), /catalog is empty/);
+ assert.throws(() => selectScenarios(catalog, { ids: [] }), /nonempty unique/);
+ assert.throws(() => selectScenarios(catalog, { ids: ['missing.scenario'] }), /missing/);
+ assert.throws(() => selectScenarios([...catalog, catalog[0]]), /duplicate scenario/);
+ for (const id of [undefined, null, { toString: () => 'coerced.id' }]) {
+ assert.throws(() => selectScenarios([{ ...catalog[0], id }]), /Invalid or duplicate scenario/);
+ }
+ assert.throws(() => selectScenarios(catalog, { ids: [catalog[0].id, catalog[0].id] }), /nonempty unique/);
+ assert.throws(() => selectScenarios(catalog, { ids: [catalog[0].id], requiredIds: [catalog[1].id] }), /not selected/);
+});
+
+test('count equality alone cannot hide duplicate, missing, foreign or unexecuted results', () => {
+ const selected = agentTrustScenarioCatalog.slice(0, 2);
+ const green = selected.map(({ id }) => ({ id, state: 'green' }));
+ assert.doesNotThrow(() => assertScenarioResults(selected, green));
+ for (const results of [[], [green[0], green[0]], [green[0], { id: 'foreign.scenario', state: 'green' }],
+ [green[0], { ...green[1], state: 'not-executed' }]]) {
+ assert.throws(() => assertScenarioResults(selected, results));
+ }
+});
+
+test('execution reports each selected ID and preserves red outcomes', async () => {
+ const fixture = [
+ { id: 'fixture.pass', name: 'Pass', capabilities: ['fixture'], run: async () => {} },
+ { id: 'fixture.fail', name: 'Fail', capabilities: ['fixture'], run: async () => { throw new Error('expected fixture failure'); } },
+ ];
+ const report = await runScenarios(fixture);
+ assert.equal(report.tests, 2);
+ assert.equal(report.passed, 1);
+ assert.equal(report.failed, 1);
+ assert.deepEqual(report.results.map(item => item.id), fixture.map(item => item.id));
+ await assert.rejects(runScenarios(fixture, { ids: [] }), /nonempty unique/);
+});
diff --git a/apps/desktop/tests/ui-consistency.test.mjs b/apps/desktop/tests/ui-consistency.test.mjs
index 3373c3db..adec12b5 100644
--- a/apps/desktop/tests/ui-consistency.test.mjs
+++ b/apps/desktop/tests/ui-consistency.test.mjs
@@ -34,15 +34,10 @@ test('all fixed product font declarations participate in text scaling', () => {
}
});
-test('the product settings expose all three persisted text scales', () => {
- const settings = read('src/product/SettingsPage.tsx');
- assert.match(settings, /\(\[1, 1\.5, 2\] as const\)/);
- assert.match(settings, /onTextScaleChange\(scale\)/);
- const app = read('src/product/DesktopApp.tsx');
- assert.match(app, /textScale=\{preferences\.textScale\}/);
- assert.match(app, /onTextScaleChange=\{preferences\.setTextScale\}/);
- const pages = read('src/occami/styles/pages.css');
- assert.doesNotMatch(pages, /height:\s*calc\(100%\s*-\s*(?:72|104|112)px\)/);
+// Interactive behavior is covered by stable IDs in v3/browser/*-scenarios.mjs.
+// Keep this file for stylesheet conventions, native capabilities and byte contracts.
+test('page layouts do not subtract fixed header heights from scaled content', () => {
+ assert.doesNotMatch(read('src/occami/styles/pages.css'), /height:\s*calc\(100%\s*-\s*(?:72|104|112)px\)/);
});
test('the shared sidebar keeps every navigation action reachable at high text scale', () => {
@@ -68,10 +63,6 @@ test('product collapsibles use the shared accessible Disclosure', () => {
};
visit(sourceRoot);
assert.deepEqual(offenders, []);
- const disclosure = read('src/ui/Disclosure.tsx');
- assert.match(disclosure, /<summary aria-expanded=\{open\}>/);
- assert.match(disclosure, /disclosureActionLabel\(open, language\)/);
- assert.match(disclosure, /<div className="disclosure-body">\{children\}<\/div>/);
});
test('the routing connection name is direct and documents its stable Agent identity', () => {
@@ -81,43 +72,18 @@ test('the routing connection name is direct and documents its stable Agent ident
assert.doesNotMatch(editor, /Agent 调用名称|稳定模型名/);
});
-test('classifier choices expose an unmistakable selected state and left-aligned copy', () => {
- const editor = read('src/plan-editor.tsx');
- assert.match(editor, /className="option-row classifier-choice"/);
- assert.match(editor, /任务判断/);
- assert.match(editor, /内置规则/);
- assert.match(editor, /自定义分类服务/);
- assert.match(editor, /Jev、LLM 或其他自定义策略/);
- assert.doesNotMatch(editor, /BERT/);
- assert.match(editor, /aria-pressed=\{classifier\.kind === 'local_rules'\}/);
- assert.match(editor, /aria-pressed=\{classifier\.kind === 'rest'\}/);
- assert.match(editor, /classifier\.kind === 'local_rules' && <UiIcon name="check"/);
- assert.match(editor, /classifier\.kind === 'rest' && <UiIcon name="check"/);
+test('selected classifier choices retain a distinct border and left-aligned copy', () => {
const pages = read('src/occami/styles/pages.css');
assert.match(pages, /button\.option-row\[aria-pressed='true'\]\s*\{[^}]*border-color:\s*var\(--accent\)/);
assert.match(pages, /\.option-row > div\s*\{[^}]*text-align:\s*left/);
});
-test('the custom classifier protocol dialog exposes curl and the native OpenAPI save action', () => {
- const dialog = read('src/features/ClassifierProtocolDialog.tsx');
- assert.match(dialog, /查看|接入协议/);
- assert.match(dialog, /复制 curl/);
- assert.match(dialog, /保存 OpenAPI/);
- assert.match(dialog, /save_classifier_openapi/);
- assert.match(dialog, /请选择保存位置/);
- assert.match(dialog, /已取消保存/);
- assert.doesNotMatch(dialog, /createObjectURL|document\.createElement\('a'\)/);
- assert.match(dialog, /hiroute-decision\.openapi\.json/);
- for (const field of ['branches', 'latest_user', 'visible_conversation', 'history_partial', 'assessment_from']) {
- assert.match(dialog, new RegExp(`"${field}"`));
- }
-
+test('the native classifier download embeds the public OpenAPI contract byte for byte', () => {
const contractPath = join(desktop, '..', '..', 'decision-extensions', 'api', 'decision.openapi.json');
const openapi = JSON.parse(readFileSync(contractPath, 'utf8'));
assert.equal(openapi.openapi, '3.1.0');
assert.equal(openapi.info.title, 'HiRoute Decision API');
assert.deepEqual(Object.keys(openapi.paths), ['/v1/decisions']);
- assert.match(dialog, /https:\/\/classifier\.example\/v1\/decisions/);
const native = read('src-tauri/src/bridge/classifier.rs');
assert.match(native, /hiroute-decision\.openapi\.json/);
const embedded = native.match(/include_str!\("([^"]+)"\)/)[1];
@@ -143,13 +109,6 @@ test('the classifier diagnostic warning is fully localized', () => {
assert.doesNotMatch(editor, /This is a synthetic connectivity test/);
});
-test('plan performance automatically scopes model presentation without a typed model id', () => {
- const editor = read('src/plan-editor.tsx');
- const quality = read('src/features/PlanQuality.tsx');
- assert.match(editor, /currentModels=\{activePlanQualityModels\(plan, options\?\.candidates \?\? \[\]\)\}/);
- assert.match(quality, /当前生效版本模型/);
- assert.doesNotMatch(quality, /quality-model-filter|实际模型 ID|Executed model ID/);
-});
test('native window configuration keeps macOS controls and shared localization', () => {
const config = JSON.parse(read('src-tauri/tauri.conf.json'));
@@ -170,81 +129,47 @@ test('native window configuration keeps macOS controls and shared localization',
assert.match(plist, /<string>zh-Hans<\/string>/);
});
-test('external links use the bounded native browser command and retain web preview behavior', () => {
- const form = read('src/features/model-connections/ModelConnectionForm.tsx');
- assert.match(form, /"__TAURI_INTERNALS__" in window/);
- assert.match(form, /invoke\('open_external_url', \{ url \}\)/);
- assert.match(form, /target="_blank"/);
- assert.match(form, /当前表单内容已保留/);
+test('the native documentation browser command is explicitly permitted', () => {
const capability = JSON.parse(read('src-tauri/capabilities/main.json'));
assert.ok(capability.permissions.includes('allow-open-external-url'));
});
-test('Codex routing form only shows configured native overrides and explains the chosen default', () => {
- const agents = read('src/agents.tsx');
- assert.match(agents, /const fixedModelRows = editorValues\.fixedModels\.map/);
- assert.match(agents, /fixedModelRows\.length > 0 && <fieldset data-agent-fixed-models>/);
- assert.doesNotMatch(agents, /hiddenCatalogModelCount/);
- assert.match(agents, /defaultChoice\.kind === 'plan'[\s\S]*Codex 将默认使用所选智能路由/);
- assert.match(agents, /保留当前默认模型名称;请求仍经过 HiRoute/);
- assert.match(agents, /data-agent-service-responsibility/);
- assert.match(agents, /使用路由时请保持 HiRoute 运行/);
- assert.match(agents, /启用不会自动设置开机启动/);
-});
-
-test('Agent home does not offer duplicate paid per-client live probes', () => {
- const agents = read('src/agents.tsx');
- assert.doesNotMatch(agents, /check_agent_live|data-agent-surface-status|真实验证(最多/);
- assert.match(agents, /data-codex-shared-scope/);
-});
-
-test('Claude routing promises the normal CLI entry and does not ask for a special launcher', () => {
- const agents = read('src/agents.tsx');
- assert.match(agents, /直接启动 claude,使用 Opus、Sonnet、Haiku 原生预设/);
- assert.match(agents, /账号 Default 仍需真实调用验证/);
- assert.match(agents, /路由已配置 · 调用未验证/);
- assert.doesNotMatch(agents, /hiroute agent launch --agent claude-code/);
-});
-
-test('model readiness copy does not claim that an upstream call was verified', () => {
- const models = read('src/features/models/Models.tsx');
- assert.match(models, /available: \['good', zh \? '接入就绪' : 'Connection ready'\]/);
- assert.match(models, /不代表上游推理或工具调用已验证/);
-});
-
-test('returning to the routing editor refreshes saved-model choices', () => {
- const editor = read('src/plan-editor.tsx');
- assert.match(editor, /if \(!active\) return;[\s\S]*'compute_management_snapshot'[\s\S]*\}, \[active, language\]\)/);
- assert.match(editor, /'plan_editor_options'[\s\S]*\}, \[active, editor, language, optionsRetry\]\)/);
-});
-
-test('closing operation feedback does not stop or cancel observation', () => {
- const app = read('src/product/DesktopApp.tsx');
- const dismiss = app.slice(app.indexOf('function dismissOperation'), app.indexOf('function retryOperationObservation'));
- assert.match(dismiss, /setDismissedOperationId/);
- assert.doesNotMatch(dismiss, /setObserving|stop_observing|cancel/);
-});
-
-test('terminal success converges while an unknown result keeps an explicit retry', () => {
- const app = read('src/product/DesktopApp.tsx');
- assert.match(app, /operationView\.phase !== 'succeeded'/);
- assert.match(app, /setTimeout\(\(\) => setDismissedOperationId\(feedbackId\), 4500\)/);
- assert.match(app, /operationView\.phase === 'unverified'[\s\S]*retryOperationObservation/);
- assert.match(app, /\['pending', 'unverified'\]\.includes\(operationView\.phase\) && <span className="oc-spinner"/);
- assert.match(app, /OBSERVATION_GRACE_MS/);
- assert.match(app, /noteUnconfirmed\('OPERATION_IDENTITY_MISMATCH'\)/);
- assert.doesNotMatch(app, /setOperationError\(pendingOperationId \? '' : OPERATION_RESULT_UNVERIFIED\)/);
- assert.match(app, /currentPendingHint\(snapshotPending, supersededPendingKey\.current\)/);
- assert.match(app, /data-observation-error-code=\{presentedOperationError \|\| undefined\}/);
- assert.doesNotMatch(app, /presentedOperationError && <div className="callout bad"/);
-});
-
-test('every accepted or unverified operation restarts the polling effect', () => {
- const app = read('src/product/DesktopApp.tsx');
- const accept = app.slice(app.indexOf('function acceptOperation'), app.indexOf('function dismissOperation'));
- assert.match(accept, /setPollingRevision\(current => current \+ 1\)/);
- assert.match(accept, /function acceptUnverifiedOperation/);
- const pollingEffectEnd = app.indexOf('useEffect(() => {\n const pendingOperationId');
- const pollingEffect = app.slice(app.indexOf('const generation = ++pollingGeneration.current'), pollingEffectEnd);
- assert.match(pollingEffect, /pollingRevision/);
+test('native command authority agrees across handlers, manifest and main-window permissions', () => {
+ const commandList = (source, pattern, itemPattern, label) => {
+ const blocks = [...source.matchAll(pattern)];
+ assert.equal(blocks.length, 1, `${label}: expected one command registry`);
+ const items = blocks[0][1].split(',').map(item => item.trim()).filter(Boolean);
+ const commands = items.map(item => {
+ const match = item.match(itemPattern);
+ assert.ok(match, `${label}: unrecognized registry item ${item}`);
+ return match[1];
+ });
+ assert.ok(commands.length > 0, `${label}: command registry must not be empty`);
+ assert.equal(new Set(commands).size, commands.length, `${label}: duplicate command`);
+ return commands.sort();
+ };
+ const handlers = commandList(
+ read('src-tauri/src/bridge.rs'), /tauri::generate_handler!\[([\s\S]*?)\]/g,
+ /^([a-z][a-z0-9_]*)$/, 'Tauri handlers',
+ );
+ const manifest = commandList(
+ read('src-tauri/build.rs'), /AppManifest::new\(\)\.commands\(&\[([\s\S]*?)\]\)/g,
+ /^"([a-z][a-z0-9_]*)"$/, 'AppManifest',
+ );
+ assert.deepEqual(manifest, handlers, 'every bundled command needs a generated ACL manifest entry');
+ const capability = JSON.parse(read('src-tauri/capabilities/main.json'));
+ const permissions = capability.permissions.filter(permission => permission.startsWith('allow-')).sort();
+ assert.deepEqual(permissions, handlers.map(command => `allow-${command.replaceAll('_', '-')}`).sort(),
+ 'the main window must explicitly permit each bundled product command');
+ const generatedDirectory = 'src-tauri/permissions/autogenerated';
+ assert.deepEqual(readdirSync(join(desktop, generatedDirectory)).filter(name => name.endsWith('.toml')).sort(),
+ handlers.map(command => `${command}.toml`).sort(), 'generated permissions must cover the same commands');
+ for (const command of handlers) {
+ const permission = read(`${generatedDirectory}/${command}.toml`);
+ const name = command.replaceAll('_', '-');
+ assert.ok(permission.includes(`identifier = "allow-${name}"`), `${command}: missing allow permission`);
+ assert.ok(permission.includes(`commands.allow = ["${command}"]`), `${command}: wrong allowed command`);
+ assert.ok(permission.includes(`identifier = "deny-${name}"`), `${command}: missing deny permission`);
+ assert.ok(permission.includes(`commands.deny = ["${command}"]`), `${command}: wrong denied command`);
+ }
});
diff --git a/apps/desktop/tests/v3/browser/agent-trust-scenarios.mjs b/apps/desktop/tests/v3/browser/agent-trust-scenarios.mjs
index ab3ad501..cd5946e9 100644
--- a/apps/desktop/tests/v3/browser/agent-trust-scenarios.mjs
+++ b/apps/desktop/tests/v3/browser/agent-trust-scenarios.mjs
@@ -1,3 +1,6 @@
+import { scenario, scenarioCatalog, runScenarios } from './scenario-selection.mjs';
+import { agentTrustRequired } from './scenario-requirements.mjs';
+
const c = () => window.agentTrust;
const tick = () => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));
const assert = (condition, message) => { if (!condition) throw new Error(message); };
@@ -57,21 +60,32 @@ function changeSelect(select, value) {
const configureSpecs = () => calls('preview_agent_settings').map(item => item.payload.input.spec);
const scenarios = [
- ['Codex file conflicts preserve active access and allow other settings', async () => {
+ scenario('codex.restore.conflict-active', ['agent-recovery'], 'Codex file conflicts preserve active access and allow other settings', async () => {
await freshCodex('splitCodexStatus');
const agent = c().agents.agents.find(agent => agent.agent_id === 'agent_codex_default');
agent.codex_access.conflict_fields = ['model_providers.hiroute.name'];
+ agent.codex_access.target_file = `/fixture/${'configuration'.repeat(16)}/codex/config.toml`;
c().refresh(); await tick();
await until(() => document.querySelector('[data-codex-restore-conflict]'), 'file conflict diagnosis');
const alert = document.querySelector('[data-codex-restore-conflict]');
assert(alert.textContent.includes('原连接仍有效') && alert.textContent.includes('model_providers.hiroute.name'), 'Conflict hides active access or fields');
assert(!alert.textContent.includes('旧令牌已失效') && !alert.textContent.includes('新的配置保存会暂停'), 'Ordinary conflict claims revoked access or globally blocked settings');
assert(!facet('model').disabled, 'Unrelated configuration action is blocked');
- }],
- ['Codex first enable is a ready-to-submit draft and cancel does not apply', async () => {
+ await openEditor('model');
+ const location = [...dialog().querySelectorAll('details')].find(node => node.querySelector('summary')?.textContent.includes('配置位置与会话历史'));
+ assert(location, 'The real configuration location is not available');
+ location.open = true; await tick();
+ const path = [...location.querySelectorAll('code')].find(node => node.textContent === agent.codex_access.target_file);
+ assert(path, 'The real configuration path was hidden or replaced with an internal identity');
+ const bounds = location.getBoundingClientRect();
+ assert(bounds.width > 200, 'The component fixture did not give configuration details a usable viewport');
+ assert([...path.getClientRects()].every(rect => rect.left >= bounds.left && rect.right <= bounds.right), 'Long configuration paths overflow the configuration details');
+ }),
+ scenario('codex.enable.draft-cancel', ['agent-model-routing'], 'Codex first enable is a ready-to-submit draft and cancel does not apply', async () => {
await freshCodex('cliOnly', true);
await openEditor('model', false);
assert(!dialog().querySelector('[role="switch"]'), 'Redundant enable switch remains');
+ assert(dialog().querySelector('[data-agent-service-responsibility]')?.textContent.includes('启用不会自动设置开机启动'), 'Enabling routing promises automatic startup');
const route = dialog().querySelector('[data-agent-plan-id] input');
assert(route?.checked && !submit().disabled, 'Sole route is not ready to submit');
assert(!dialog().querySelector('details').open, 'Advanced settings are open on first enable');
@@ -80,8 +94,8 @@ const scenarios = [
const cancel = [...dialog().querySelectorAll('button')].find(button => button.textContent.trim() === '取消');
cancel.click(); await tick();
assert(!dialog() && calls('preview_agent_settings').length === 0 && c().operations.length === 0, 'Cancel applied a draft');
- }],
- ['Claude first enable shares one route while retaining independent advanced presets', async () => {
+ }),
+ scenario('claude.enable.shared-presets', ['agent-model-routing'], 'Claude first enable shares one route while retaining independent advanced presets', async () => {
await fresh('notRunnable', true);
await openEditor('model', false);
assert(!dialog().querySelector('[role="switch"]'), 'Redundant enable switch remains');
@@ -90,12 +104,14 @@ const scenarios = [
assert(!dialog().querySelector('details').open, 'Advanced presets are open by default');
assert(!dialog().querySelector('[data-agent-capability-preview]') && calls('plan_editor_options').length === 0, 'Enable still loads a read-only capacity preview');
assert(dialog().textContent.includes('重新启动 Claude Code'), 'Claude activation step is missing');
+ assert(dialog().textContent.includes('账号 Default 仍需真实调用验证'), 'Preset routing overstates account Default verification');
+ assert(!text().includes('hiroute agent launch --agent claude-code'), 'Claude routing requires a special launcher');
await save();
const spec = configureSpecs().at(-1).model.settings;
assert(Object.values(spec.preset_mappings).every(choice => choice.kind === 'plan' && choice.plan_id === route.value), 'Shared route did not cover all three presets');
assert(!Object.hasOwn(spec, 'model'), 'Shortcut changed the native current model');
- }],
- ['Codex copies the confirmed profile command through native IPC when browser copying rejects', async () => {
+ }),
+ scenario('codex.enable.confirmed-command', ['agent-model-routing'], 'Codex copies the confirmed profile command through native IPC when browser copying rejects', async () => {
await freshCodex('cliOnly', true);
const agent = c().agents.agents.find(agent => agent.agent_id === 'agent_codex_default');
const command = `CODEX_HOME='/path with spaces' codex --profile hiroute`;
@@ -134,8 +150,8 @@ const scenarios = [
if (previousCopy) Object.defineProperty(document, 'execCommand', previousCopy); else delete document.execCommand;
if (previousNative) Object.defineProperty(window, 'isTauri', previousNative); else delete window.isTauri;
}
- }],
- ['Desktop-only Codex repairs an existing fixed-model binding without a surface selector', async () => {
+ }),
+ scenario('codex.routing.fixed-binding', ['agent-model-routing'], 'Desktop-only Codex repairs an existing fixed-model binding without a surface selector', async () => {
await freshCodex('desktopWithFixed');
await openEditor('model');
assert(!document.querySelector('[data-agent-surface-option]'), 'Legacy surface selector is still rendered');
@@ -143,6 +159,7 @@ const scenarios = [
assert(document.querySelector('[data-agent-surface-fact="codex_desktop"]').getAttribute('data-agent-surface-detected') === 'true', 'Desktop discovery fact missing');
assert(document.querySelector('[data-agent-surface-fact="codex_cli"]').getAttribute('data-agent-surface-detected') === 'false', 'Missing CLI was not reported as a fact');
assert(submit().disabled, 'Unavailable existing source did not block save');
+ assert(document.querySelectorAll('[data-agent-fixed-models] [data-client-model-id]').length === 1, 'Unconfigured catalog overrides appeared in the form');
const fixed = document.querySelector('[data-client-model-id="gpt-5.6-sol"] select');
changeSelect(fixed, 'binding/codex/gpt-5.6-sol');
await tick();
@@ -156,8 +173,8 @@ const scenarios = [
assert(!Object.hasOwn(spec, 'surfaces'), 'Desktop discovery leaked into the persisted configuration');
assert(spec.fixed_models.length === 1 && spec.allowed_plan_ids.length === 0, 'Fixed-only selection was not preserved');
assert(spec.fixed_models[0].candidate.reasoning.profile === 'high', 'Native effort was not submitted');
- }],
- ['CLI-only Codex saves one shared plan configuration without selecting Desktop', async () => {
+ }),
+ scenario('codex.routing.plan-only', ['agent-model-routing'], 'CLI-only Codex saves one shared plan configuration without selecting Desktop', async () => {
await freshCodex('cliOnly');
await openEditor('model');
assert(!document.querySelector('#hr-agent-settings [role="switch"]'), 'Enable requires a redundant switch');
@@ -171,12 +188,13 @@ const scenarios = [
const planId = plan.getAttribute('data-agent-plan-id');
if (document.querySelector('[data-agent-default]')) changeSelect(document.querySelector('[data-agent-default]'), `plan:${planId}`);
await tick();
+ assert(!dialog().querySelector('[data-agent-fixed-models]'), 'Plan-only routing exposes unconfigured fixed overrides');
await save();
const spec = configureSpecs().at(-1).model.settings;
assert(!Object.hasOwn(spec, 'surfaces'), 'CLI discovery leaked into the persisted configuration');
assert(spec.fixed_models.length === 0 && spec.allowed_plan_ids.length === 1, 'Plan-only selection was not preserved');
- }],
- ['Codex mixed selection repairs a fixed route and adds a Plan while preserving the covered native default', async () => {
+ }),
+ scenario('codex.routing.mixed-native-default', ['agent-model-routing'], 'Codex mixed selection repairs a fixed route and adds a Plan while preserving the covered native default', async () => {
await freshCodex('desktopWithFixed');
await openEditor('model');
changeSelect(document.querySelector('[data-client-model-id="gpt-5.6-sol"] select'), 'binding/codex/gpt-5.6-sol');
@@ -184,29 +202,55 @@ const scenarios = [
if (!plan.querySelector('input').checked) plan.querySelector('input').click();
await tick();
assert(document.querySelector('[data-agent-default]').value === 'native', 'Native default was changed without user action');
+ assert(dialog().textContent.includes('保留当前默认模型名称;请求仍经过 HiRoute'), 'Preserved native default routing is not explained');
+ changeSelect(document.querySelector('[data-agent-default]'), `plan:${plan.getAttribute('data-agent-plan-id')}`);
+ await tick();
+ assert(dialog().textContent.includes('Codex 将默认使用所选智能路由'), 'Selected default route is not explained');
+ changeSelect(document.querySelector('[data-agent-default]'), 'native');
+ await tick();
await save();
const spec = configureSpecs().at(-1).model.settings;
assert(spec.fixed_models.length === 1 && spec.allowed_plan_ids.length === 1, 'Mixed selection lost a route family');
assert(spec.default_selection.kind === 'preserve_native', 'Covered native default was not preserved');
- }],
- ['Codex renders CLI passed and Desktop not verified as independent current-revision states', async () => {
- await freshCodex('splitCodexStatus');
- const cli = document.querySelector('[data-agent-surface="codex_cli"]');
- const desktop = document.querySelector('[data-agent-surface="codex_desktop"]');
- assert(cli?.textContent.includes('已验证') && cli.textContent.includes('r19'), 'CLI passed state missing');
- assert(desktop?.textContent.includes('尚未验证') && desktop.textContent.includes('r19'), 'Desktop not-verified state missing');
- assert(!text().includes('全部模型可用'), 'Partial evidence was generalized to the full catalog');
- c().agents.agents.find(agent => agent.agent_id === 'agent_codex_default').settings.surface_results[0].applied_revision = 18;
- c().refresh();
- await until(() => document.querySelector('[data-agent-surface="codex_cli"]')?.textContent.includes('r19'), 'current CLI revision');
- const staleCli = document.querySelector('[data-agent-surface="codex_cli"]');
- assert(staleCli.textContent.includes('尚未验证') && !staleCli.textContent.includes('已验证'), 'A prior-revision pass was shown as current');
- }],
- ['Codex recovery keeps native model selection and local token controls together', async () => {
+ }),
+ scenario('agent.configuration.shared-interactions', ['agent-configuration', 'qoder'], 'Codex, Claude and Qoder share configuration actions without model verification steps', async () => {
+ const snapshots = [c().splitCodexStatus(), c().registered(), c().qoderRouted()];
+ for (const snapshot of snapshots) {
+ const id = snapshot.agents.some(agent => agent.agent_id === 'agent_qoder_default')
+ ? 'agent_qoder_default' : snapshot === snapshots[0] ? 'agent_codex_default' : 'agent_claude_default';
+ for (const state of ['not_verified', 'passed', 'failed']) {
+ c().reset();
+ c().agents = structuredClone(snapshot);
+ c().agents.agents = c().agents.agents.filter(agent => agent.agent_id === id);
+ const agent = c().agents.agents[0];
+ agent.settings.model_verified = state === 'passed';
+ agent.settings.surface_results = agent.available_surfaces.map(surface => ({
+ surface, applied_revision: agent.settings.applied_revision - 1, state, reason_code: null,
+ }));
+ await tick();
+ await until(() => document.querySelector(`[data-agent-id="${id}"]`), `${id} configured detail`);
+ assert(text().includes('路由已配置'), `${id} lost its configured status`);
+ assert(!/尚未验证|调用未验证|路由已验证|验证未通过/.test(text()), `${id} exposed model verification as configuration status`);
+ assert(!document.querySelector('[data-agent-surface]'), `${id} exposes revision-scoped verification results`);
+ assert(![...document.querySelectorAll('button')].some(button => /验证模型调用|验证任务协作|检查协作能力/.test(button.textContent)), `${id} requires an extra verification step`);
+ assert(facet('model')?.textContent === '调整' && !facet('model').disabled, `${id} cannot edit model routing`);
+ assert(facet('collaboration')?.textContent === '调整' && !facet('collaboration').disabled, `${id} cannot edit task routing`);
+ assert([...document.querySelectorAll('button')].some(button => button.textContent === '停用' && !button.disabled), `${id} lost model recovery`);
+ assert(calls('check_agent_live').length === 0 && calls('check_agent_authentication').length === 0, `${id} probes on ordinary navigation`);
+ }
+ }
+ }),
+ scenario('codex.recovery.token-controls', ['agent-recovery'], 'Codex recovery keeps native model selection and local token controls together', async () => {
await freshCodex('splitCodexStatus');
const details = document.querySelector('.native-details');
- details.querySelector('summary').click();
+ const summary = details.querySelector('summary');
+ const actionLabel = () => summary.querySelector('.disclosure-action').textContent.trim();
+ assert(!details.open && summary.getAttribute('aria-expanded') === 'false', 'Closed recovery disclosure is not announced as collapsed');
+ assert(actionLabel() === '展开', 'Closed recovery disclosure does not offer Expand');
+ summary.click();
await tick();
+ assert(details.open && summary.getAttribute('aria-expanded') === 'true', 'Open recovery disclosure is not announced as expanded');
+ assert(actionLabel() === '收起', 'Open recovery disclosure does not offer Collapse');
assert(visible(details.querySelector('input[list="codex-native-restore-models"]')), 'Native model restore selector is missing');
const controls = details.querySelector('[data-agent-token-controls]');
assert(visible(controls), 'Local token controls are missing beside native recovery');
@@ -221,8 +265,12 @@ const scenarios = [
assert(!details.querySelector('.agent-token-form'), 'Token edit form did not close');
const restore = [...document.querySelectorAll('.detail-section-head button')].find(button => button.textContent.trim() === '停用');
assert(restore && !restore.disabled, 'Model recovery became unavailable after token edit');
- }],
- ['a Codex plan rejected by Preview explains the Responses boundary without applying it', async () => {
+ summary.click();
+ await tick();
+ assert(!details.open && summary.getAttribute('aria-expanded') === 'false', 'Closing recovery disclosure did not restore its collapsed announcement');
+ assert(actionLabel() === '展开' && !controls.checkVisibility(), 'Closing recovery disclosure did not restore Expand and hide its controls');
+ }),
+ scenario('codex.routing.preview-rejection', ['agent-model-routing'], 'a Codex plan rejected by Preview explains the Responses boundary without applying it', async () => {
await freshCodex('cliOnly');
c().handlers.preview_agent_settings = () => ({
preview: { applicable: false, blockers: [{ reason: 'model_plan_unavailable' }] },
@@ -241,8 +289,8 @@ const scenarios = [
await until(() => calls('preview_agent_settings').length === 1, 'incompatible plan preview');
assert(dialog()?.textContent.includes('Codex Responses') && dialog().textContent.includes('配置未修改'), 'The blocker did not explain why nothing was applied');
assert(c().operations.length === 0 && c().mutations === 0, 'An incompatible plan reached the mutation path');
- }],
- ['a non-runnable executable reports the real reason without becoming a trust gate', async () => {
+ }),
+ scenario('agent.diagnostics.non-runnable', ['agent-diagnostics'], 'a non-runnable executable reports the real reason without becoming a trust gate', async () => {
await fresh('notRunnable');
const callout = executableCallout();
assert(visible(callout), 'Executable diagnostic missing');
@@ -253,16 +301,16 @@ const scenarios = [
await openEditor('model');
assert(visible(dialog()), 'Editor did not open alongside the executable diagnostic');
assert(calls('preview_agent_settings').length === 0, 'Opening the editor dispatched a mutation request');
- }],
- ['rescan replaces a non-runnable diagnostic with the current installation state', async () => {
+ }),
+ scenario('agent.diagnostics.rescan', ['agent-diagnostics'], 'rescan replaces a non-runnable diagnostic with the current installation state', async () => {
await fresh('notRunnable');
assert(visible(executableCallout()), 'Executable diagnostic missing');
c().agents = c().registered();
executableCallout().querySelector('button').click();
await until(() => !executableCallout(), 'executable diagnostic cleared after rescan');
assert(!facet('model').disabled, 'Configure entry changed after rescan');
- }],
- ['a late executable failure remains diagnostic while the shared configuration stays editable', async () => {
+ }),
+ scenario('agent.diagnostics.late-failure', ['agent-diagnostics'], 'a late executable failure remains diagnostic while the shared configuration stays editable', async () => {
await fresh('registered');
await openEditor('model');
assert(!submit().disabled && !executableCallout(dialog()), 'Registered editor unexpectedly restricted');
@@ -274,8 +322,8 @@ const scenarios = [
const before = calls('preview_agent_settings').length;
await save();
assert(calls('preview_agent_settings').length === before + 1, 'Executable diagnostic prevented a shared configuration save');
- }],
- ['a non-runnable install keeps the managed recovery entry reachable', async () => {
+ }),
+ scenario('agent.recovery.non-runnable', ['agent-recovery'], 'a non-runnable install keeps the managed recovery entry reachable', async () => {
await fresh('notRunnableWithRestore');
assert(visible(executableCallout()), 'Executable diagnostic missing');
const details = document.querySelector('.native-details');
@@ -287,9 +335,11 @@ const scenarios = [
await until(() => calls('preview_agent_settings').length === 1, 'recovery request dispatched');
assert(configureSpecs()[0].model.intent === 'restore', 'Recovery entry dispatched a configure request');
assert(!dialog(), 'Recovery reply opened a configuration editor');
- }],
- ['registered installs keep both facets configurable in one step', async () => {
+ }),
+ scenario('agent.configuration.independent-facets', ['agent-model-routing', 'agent-collaboration'], 'registered installs keep both facets configurable in one step', async () => {
await fresh('registered');
+ assert(text().includes('直接启动 claude,使用 Opus、Sonnet、Haiku 原生预设'), 'Claude preset routing does not explain the ordinary CLI entry');
+ assert(text().includes('路由已配置'), 'Configured routing status missing');
await openEditor('model');
assert(!executableCallout(dialog()), 'Registered install wrongly reported an executable failure');
await save();
@@ -302,8 +352,8 @@ const scenarios = [
assert(specs.length === 2 && specs[1].collaboration.intent === 'configure', 'Task delegation skill did not save independently');
assert(specs[1].collaboration.settings.trigger_mode === 'delegate_by_default', 'Task trigger mode was not preserved');
assert(c().mutations === 2, 'Saves were not reported to the host');
- }],
- ['registered installs still pass the prerequisite check before saving', async () => {
+ }),
+ scenario('agent.configuration.prerequisite', ['agent-verification'], 'registered installs still pass the prerequisite check before saving', async () => {
await fresh('registered');
let previews = 0;
c().handlers.preview_agent_settings = () => {
@@ -317,8 +367,8 @@ const scenarios = [
assert(calls('check_agent_authentication').length === 1, 'Prerequisite check was skipped');
assert(calls('preview_agent_settings').length === 2, 'Save did not re-preview after the prerequisite check');
assert(!executableCallout() && !executableCallout(dialog()), 'A prerequisite gap was reported as an executable failure');
- }],
- ['Claude collaboration checks Skill and trusted CLI before Preview and Apply', async () => {
+ }),
+ scenario('claude.collaboration.check-before-save', ['claude-collaboration'], 'Claude collaboration checks Skill and trusted CLI before Preview and Apply', async () => {
await fresh('registered');
let previews = 0;
let finishCheck;
@@ -344,8 +394,8 @@ const scenarios = [
assert(checks[0].payload.input.agent_id === 'agent_claude_default' && checks[0].payload.input.scope === 'collaboration', 'Claude check did not use the collaboration scope');
assert(calls('preview_agent_settings').length === 2, 'Claude save did not re-preview after the formal check');
assert(!dialog(), 'Claude collaboration editor remained open after Apply');
- }],
- ['Claude collaboration check failure offers a retry and preserves the edit', async () => {
+ }),
+ scenario('claude.collaboration.retry-preserves-edit', ['claude-collaboration'], 'Claude collaboration check failure offers a retry and preserves the edit', async () => {
await fresh('registered');
c().handlers.preview_agent_settings = () => ({ preview: { applicable: false, blockers: [{ reason: 'capability_unavailable', capabilities: [
{ capability: 'skill_loading', reason: 'unverified' },
@@ -361,8 +411,8 @@ const scenarios = [
retry.click();
await until(() => text().includes('任务委派技能检查通过'), 'Claude collaboration check retried');
assert(calls('check_agent_authentication').length === 2, 'Retry did not dispatch a new formal check');
- }],
- ['an unrelated Agent preview failure clears an obsolete prerequisite blocker', async () => {
+ }),
+ scenario('claude.collaboration.obsolete-blocker', ['claude-collaboration'], 'an unrelated Agent preview failure clears an obsolete prerequisite blocker', async () => {
await fresh('registered');
c().handlers.preview_agent_settings = () => ({ preview: { applicable: false, blockers: [{ reason: 'capability_unavailable', capabilities: [
{ capability: 'skill_loading', reason: 'unverified' },
@@ -376,16 +426,16 @@ const scenarios = [
await until(() => dialog()?.querySelector('[role="alert"]'), 'new preview failure');
assert(!dialog().querySelector('button')?.textContent.includes('重新检查任务委派技能'), 'Obsolete blocker remained');
assert(!visible(dialog().querySelector('.callout.warn')), 'Obsolete blocker remained visible');
- }],
- ['non-executable states keep their own diagnostics', async () => {
+ }),
+ scenario('agent.diagnostics.configuration-state', ['agent-diagnostics'], 'non-executable states keep their own diagnostics', async () => {
await fresh('unregisteredEndpoint');
assert(!executableCallout(), 'Configuration state was generalized to an executable failure');
assert(!facet('model').disabled, 'Configure entry wrongly blocked for a configuration state');
await openEditor('model');
assert(visible(dialog()), 'Editor did not open for a configuration state');
assert(calls('preview_agent_settings').length === 0, 'Opening the editor dispatched a mutation request');
- }],
- ['Codex explains unproven cache names and can switch to HiRoute-only without native bindings', async () => {
+ }),
+ scenario('codex.routing.unproven-native-model', ['agent-model-routing'], 'Codex explains unproven cache names and can switch to HiRoute-only without native bindings', async () => {
await freshCodex('protectedCodex');
c().handlers.preview_agent_settings = ({ input }) => input.spec.model.settings.native_model_mode === 'preserve_available'
? { preview: { applicable: false, blockers: [{ reason: 'native_model_coverage_unavailable' }], unproven_native_model_ids: ['gpt-unproven'] }, mutation: null }
@@ -405,16 +455,170 @@ const scenarios = [
await save();
const spec = configureSpecs().at(-1).model.settings;
assert(spec.native_model_mode === 'hiroute_only' && spec.fixed_models.length === 0, 'Native model leaked into HiRoute-only save');
- }],
+ }),
+ scenario('qoder.collaboration.enable-without-model', ['qoder', 'qoder-collaboration'], 'Qoder enables task collaboration without a model connection or published plan', async () => {
+ c().reset(); c().agents = c().qoderFresh(); await tick();
+ await until(() => document.querySelector('[data-agent-id="agent_qoder_default"]'), 'Qoder detail');
+ assert(facet('model') && !document.querySelector('[data-agent-token-controls]'), 'Optional model routing requires a connection or token');
+ assert(c().agents.plans.plans.length === 0 && !c().agents.agents[0].settings.current_selection, 'Collaboration fixture already has a route');
+ const context = c().agents.agents[0].context_id;
+ assert(!text().includes(context) && !text().includes('当前配置范围'), 'An opaque authority ID was presented as a readable configuration scope');
+ let previews = 0;
+ c().handlers.preview_agent_settings = () => ++previews === 1
+ ? { preview: { applicable: false, blockers: [{ reason: 'capability_unavailable', capabilities: [{ capability: 'skill_loading', reason: 'unverified' }] }] }, mutation: null }
+ : { preview: { applicable: true, blockers: [] }, mutation: { state: 'applied', operation: { operation_id: 'operation/agent-settings-fixture', state: 'succeeded', sequence: 1, cancellable: false } } };
+ await openEditor('collaboration');
+ document.querySelector('input[name="agent-collaboration-trigger"][value="delegate_by_default"]').click();
+ await tick(); await save();
+ const check = calls('check_agent_authentication').at(-1)?.payload.input;
+ assert(check?.agent_id === 'agent_qoder_default' && check.scope === 'collaboration', 'Saving Qoder skipped the required collaboration check');
+ assert(previews === 2, 'Qoder did not re-preview after its automatic check');
+ const spec = configureSpecs().at(-1);
+ assert(spec.model.intent === 'keep' && !spec.model.settings && !spec.access_token, 'Qoder save invented model configuration');
+ assert(spec.context_id === context, 'Hiding the internal identity changed the authoritative save target');
+ assert(spec.collaboration.settings.trigger_mode === 'delegate_by_default', 'The chosen trigger mode was lost');
+ assert(calls('check_agent_live').length === 0, 'Task collaboration called model verification');
+ }),
+ scenario('qoder.collaboration.retry-and-restore', ['qoder', 'qoder-collaboration'], 'Qoder preserves edits through prerequisite failures and independently restores collaboration', async () => {
+ c().reset(); c().agents = c().qoderConfigured(); await tick();
+ await until(() => document.querySelector('[data-agent-id="agent_qoder_default"]'), 'configured Qoder');
+ c().handlers.preview_agent_settings = () => ({ preview: { applicable: false, blockers: [{ reason: 'capability_unavailable', capabilities: [{ capability: 'skill_loading', reason: 'unverified' }] }] }, mutation: null });
+ await openEditor('collaboration');
+ let attempts = 0;
+ c().handlers.check_agent_authentication = () => {
+ if (++attempts <= 2) {
+ const schema = 'hiroute.agent-collaboration-check-failure/v1';
+ throw { source: 'backend', envelope: {
+ error: { details_schema: schema, code: 'ACTION_REQUIRED' },
+ data: { schema, reason: attempts === 1 ? 'login_required' : 'installed_skill_changed' },
+ } };
+ }
+ return true;
+ };
+ submit().click();
+ await until(() => text().includes('正常打开已选客户端完成登录'), 'normal sign-in recovery');
+ assert(!text().includes('用户协作技能验证通过'), 'Failed verification was presented as success');
+ assert(facet('collaboration').textContent === '调整' && dialog(), 'Failed check discarded the enabled collaboration or edit');
+ const retry = () => [...dialog().querySelectorAll('button')].find(button => button.textContent.includes('重新检查任务委派技能'));
+ assert(retry() && !retry().disabled, 'Qoder check failure has no shared retry action');
+ retry().click();
+ await until(() => text().includes('已安装的协作 Skill 内容发生变化'), 'changed skill recovery');
+ assert(text().includes('不会自动覆盖'), 'Changed user skill was not protected');
+ assert(c().operations.length === 0 && c().mutations === 1, 'A failed prerequisite applied or restored a user Skill');
+ assert(configureSpecs().every(spec => spec.model.intent === 'keep' && spec.collaboration.intent === 'configure'), 'Retry changed the pending intent');
+ retry().click();
+ await until(() => text().includes('用户协作技能验证通过;未执行委派任务。'), 'installed user skill verification');
+ assert(calls('check_agent_live').length === 0, 'Qoder invoked model verification');
+ [...dialog().querySelectorAll('button')].find(button => button.textContent === '取消').click();
+ await until(() => !dialog(), 'collaboration editor cancelled');
+ c().handlers.preview_agent_settings = () => ({ preview: { applicable: true, blockers: [] }, mutation: { state: 'applied', operation: { operation_id: 'operation/agent-settings-fixture', state: 'succeeded', sequence: 1, cancellable: false } } });
+ const details = document.querySelector('.native-details'); details.querySelector('summary').click(); await tick();
+ assert(!details.querySelector('input[type="password"]'), 'Qoder recovery exposed a model token');
+ [...details.querySelectorAll('button')].find(button => button.textContent === '停用任务路由').click();
+ await until(() => configureSpecs().some(spec => spec.collaboration.intent === 'restore'), 'collaboration restore submitted');
+ const spec = configureSpecs().at(-1);
+ assert(spec.model.intent === 'keep' && spec.collaboration.restore_point_ref === 'task-restore/qoder', 'Restore changed a model facet or used the wrong Skill owner');
+ }),
+ scenario('qoder.routing.additional-plans', ['qoder', 'qoder-model-routing'], 'Qoder adds selected routes without replacing native models or applying a cancelled draft', async () => {
+ c().reset(); c().agents = c().qoderFresh(); c().agents.plans = c().registered().plans; await tick();
+ await until(() => facet('model'), 'Qoder optional model routing');
+ await openEditor('model');
+ const pick = () => [...dialog().querySelectorAll('[data-agent-plan-id] input')].slice(0, 2).forEach(input => input.click());
+ pick(); await tick();
+ assert(dialog().textContent.includes('当前默认模型保持不变') && dialog().textContent.includes('/model'), 'Additional routing does not explain native preservation and selection');
+ assert(!dialog().querySelector('[data-agent-default], [data-client-model-id], [data-agent-fixed-models], select'), 'Qoder borrowed native model, source or default controls');
+ [...dialog().querySelectorAll('button')].find(button => button.textContent === '取消').click(); await tick();
+ assert(configureSpecs().length === 0 && !dialog(), 'Cancelling Qoder model draft changed configuration');
+ await openEditor('model'); pick(); await tick();
+ const selected = [...dialog().querySelectorAll('[data-agent-plan-id]')].filter(row => row.querySelector('input').checked).map(row => row.dataset.agentPlanId);
+ await save();
+ const spec = configureSpecs().at(-1);
+ assert(JSON.stringify(spec.model.settings) === JSON.stringify({ mode: 'qoder_additional', allowed_plan_ids: selected }), 'Qoder submitted another ecosystem or changed the route set');
+ assert(spec.collaboration.intent === 'keep' && !spec.restore_native_model, 'Model save changed collaboration or a native default');
+ assert(!c().commands.some(({ command }) => /subscription|discovered_model|model_catalog/.test(command)), 'Additional routing opened model discovery or import');
+ assert(calls('check_agent_live').length === 0, 'Saving routes implicitly invoked a model');
+ }),
+ scenario('qoder.routing.adjust-and-restore', ['qoder', 'qoder-model-routing'], 'Qoder repairs selected routes, rotates their token and restores each facet independently', async () => {
+ c().reset(); c().agents = c().qoderRouted();
+ const unavailablePlan = c().agents.agents[0].settings.current_selection.allowed_plan_ids[1];
+ c().agents.plans.plans = c().agents.plans.plans.filter(plan => plan.agent_plan_id !== unavailablePlan);
+ await tick();
+ await until(() => facet('model')?.textContent === '调整', 'configured Qoder model routing');
+ const agent = c().agents.agents[0];
+ let restoreBlocker = null;
+ c().handlers.preview_agent_settings = ({ input: { spec } }) => {
+ if (spec.model.intent === 'restore' && restoreBlocker) return {
+ preview: { applicable: false, blockers: [{ reason: restoreBlocker }] }, mutation: null,
+ };
+ if (spec.model.intent === 'configure') agent.settings.current_selection = structuredClone(spec.model.settings);
+ if (spec.model.intent === 'restore') {
+ agent.settings.state = 'not_configured'; agent.settings.current_selection = null; agent.settings.restore_point_ref = null;
+ }
+ if (spec.collaboration.intent === 'restore') agent.settings.collaboration = { state: 'restored', current_selection: null, restore_point_ref: null };
+ return { preview: { applicable: true, blockers: [] }, mutation: { state: 'applied', operation: { operation_id: 'operation/agent-settings-fixture', state: 'succeeded', sequence: 1, cancellable: false } } };
+ };
+ await openEditor('model');
+ const retired = dialog().querySelector(`[data-agent-plan-id="${unavailablePlan}"] input`);
+ assert(retired?.checked && submit().disabled, 'An unavailable saved route disappeared or was silently replaced');
+ retired.click();
+ const added = [...dialog().querySelectorAll('[data-agent-plan-id] input')].find(input => !input.checked); added.click();
+ await tick(); await save();
+ const saved = structuredClone(configureSpecs().at(-1).model.settings);
+ const details = document.querySelector('.native-details'); details.querySelector('summary').click(); await tick();
+ [...details.querySelectorAll('button')].find(button => button.textContent === '重新生成').click();
+ await until(() => configureSpecs().some(spec => spec.access_token?.intent === 'regenerate'), 'Qoder token regeneration');
+ assert(JSON.stringify(configureSpecs().at(-1).model.settings) === JSON.stringify(saved), 'Token rotation used another selection');
+ await until(() => ![...document.querySelectorAll('.detail-section-head button')].find(button => button.textContent === '停用')?.disabled, 'model restore ready');
+ const beforeRestore = c().operations.length;
+ for (const [reason, guidance] of [['qoder_default_in_use', '通过 /model 切换到其他模型'], ['qoder_model_file_conflict', '不会覆盖冲突字段或无关配置']]) {
+ restoreBlocker = reason;
+ [...document.querySelectorAll('.detail-section-head button')].find(button => button.textContent === '停用').click();
+ await until(() => document.querySelector('.agent-feedback')?.textContent.includes(guidance), `restore guidance: ${reason}`);
+ assert(c().operations.length === beforeRestore && agent.settings.current_selection.mode === 'qoder_additional', 'A blocked restore changed the connection');
+ assert(agent.settings.collaboration.state === 'configured', 'A model conflict disabled collaboration');
+ }
+ restoreBlocker = null;
+ [...document.querySelectorAll('.detail-section-head button')].find(button => button.textContent === '停用').click();
+ await until(() => c().operations.length === beforeRestore + 1 && agent.settings.state === 'not_configured', 'model restore request');
+ assert(configureSpecs().at(-1).collaboration.intent === 'keep' && agent.settings.collaboration.state === 'configured', 'Model restore removed task collaboration');
+ agent.settings = c().qoderRouted().agents[0].settings; c().refresh(); await tick();
+ await until(() => facet('model')?.textContent === '调整' && !facet('model').disabled, 'model connection refreshed');
+ const recovery = document.querySelector('.native-details'); if (!recovery.open) recovery.querySelector('summary').click(); await tick();
+ [...recovery.querySelectorAll('button')].find(button => button.textContent === '停用任务路由').click();
+ await until(() => configureSpecs().some(spec => spec.collaboration.intent === 'restore'), 'independent collaboration restore');
+ assert(configureSpecs().at(-1).model.intent === 'keep' && agent.settings.current_selection.mode === 'qoder_additional', 'Collaboration restore removed model routes');
+ }),
+ scenario('qoder.routing.resume-pending', ['qoder', 'qoder-model-routing'], 'Qoder resumes the original incomplete model operation without replacing task collaboration', async () => {
+ c().reset(); c().agents = c().qoderRouted();
+ const agent = c().agents.agents[0];
+ const configured = structuredClone(agent.settings);
+ agent.settings = { ...configured, state: 'pending', current_selection: null, operation_id: 'operation/qoder-pending', operation_state: 'activating' };
+ c().agents.trusted_authority = false;
+ await tick();
+ const retry = () => document.querySelector('[data-qoder-model-recovery] button');
+ await until(() => retry(), 'pending model recovery');
+ assert(retry().disabled, 'Untrusted status authorized recovery');
+ c().agents.trusted_authority = true; c().refresh();
+ await until(() => retry() && !retry().disabled, 'trusted original-operation retry');
+ c().handlers.retry_agent_settings = ({ input }) => {
+ assert(input.schema === 'hiroute.agent-settings-retry/v1'
+ && input.context_id === agent.context_id && input.operation_id === 'operation/qoder-pending', 'Retry changed the authorized operation or context');
+ agent.settings = configured;
+ return { operation_id: input.operation_id, state: 'succeeded' };
+ };
+ retry().click();
+ await until(() => !retry() && facet('model') && !facet('model').disabled, 'authoritative recovered status');
+ assert(c().commands.filter(item => item.command === 'retry_agent_settings').length === 1, 'Recovery was duplicated');
+ assert(!c().commands.some(item => item.command === 'preview_agent_settings'), 'Recovery created a new settings operation');
+ assert(agent.settings.collaboration.current_selection.trigger_mode === configured.collaboration.current_selection.trigger_mode, 'Recovery changed collaboration');
+ assert(!agent.settings.model_verified, 'Recovery fabricated a model verification');
+ }),
+
];
-export const agentTrustScenarioNames = scenarios.map(([name]) => name);
+export const agentTrustScenarioCatalog = scenarioCatalog(scenarios);
+export const agentTrustScenarioNames = agentTrustScenarioCatalog.map(item => item.name);
-export async function runAgentTrustScenarios(start = 0, end = Infinity) {
- const results = [];
- for (const [name, run] of scenarios.slice(start, end)) {
- try { await run(); results.push({ name, state: 'green' }); }
- catch (error) { results.push({ name, state: 'red', error: error.message }); }
- }
- return { evidence: 'React components + mock IPC only; not native/Tauri', tests: results.length, passed: results.filter(item => item.state === 'green').length, failed: results.filter(item => item.state === 'red').length, results };
+export async function runAgentTrustScenarios(selection = { requiredIds: agentTrustRequired }) {
+ return runScenarios(scenarios, selection);
}
diff --git a/apps/desktop/tests/v3/browser/agent-trust.tsx b/apps/desktop/tests/v3/browser/agent-trust.tsx
index 36b6b4bc..5cdbe67e 100644
--- a/apps/desktop/tests/v3/browser/agent-trust.tsx
+++ b/apps/desktop/tests/v3/browser/agent-trust.tsx
@@ -1,14 +1,19 @@
import React, { useState } from 'react';
import { createRoot } from 'react-dom/client';
import { mockIPC } from '@tauri-apps/api/mocks';
-import { Agents, type AgentSnapshot } from '../../../src/agents';
+import { Agents, type Agent, type AgentSnapshot, type ModelStatus } from '../../../src/agents';
import type { OperationReference } from '../../../src/features/model-connections/types';
import { PresentationRoot } from '../../../src/ui';
import { readyAgents } from './product-fixtures';
import '../../../src/occami/styles.css';
-const claudeOf = (snapshot: AgentSnapshot) => snapshot.agents.find(agent => agent.agent_id === 'agent_claude_default')!;
-const codexOf = (snapshot: AgentSnapshot) => snapshot.agents.find(agent => agent.agent_id === 'agent_codex_default')!;
+function modelAgent(snapshot: AgentSnapshot, id: string): Agent & { settings: ModelStatus } {
+ const agent = snapshot.agents.find(agent => agent.agent_id === id);
+ if (!agent?.settings || !('state' in agent.settings)) throw new Error('Model scenario requires model settings');
+ return agent as Agent & { settings: ModelStatus };
+}
+const claudeOf = (snapshot: AgentSnapshot) => modelAgent(snapshot, 'agent_claude_default');
+const codexOf = (snapshot: AgentSnapshot) => modelAgent(snapshot, 'agent_codex_default');
function registered(): AgentSnapshot {
return structuredClone(readyAgents);
@@ -34,7 +39,7 @@ function notRunnableWithRestore(): AgentSnapshot {
}
function unregisteredEndpoint(): AgentSnapshot {
const snapshot = registered();
- const agent = claudeOf(snapshot);
+ const agent = snapshot.agents.find(agent => agent.agent_id === 'agent_claude_default')!;
agent.configuration_state = 'unregistered_endpoint';
agent.version = '';
agent.settings = null;
@@ -78,6 +83,8 @@ function protectedCodex(): AgentSnapshot {
function splitCodexStatus(): AgentSnapshot {
const snapshot = registered();
const agent = codexOf(snapshot);
+ const selection = agent.settings?.current_selection;
+ if (selection?.mode !== 'codex_default') throw new Error('Codex status fixture requires a Codex selection');
agent.codex_access = {
codex_home: '/fixture/codex', slot_id: 'slot/fixture',
profile_context_id: 'context/fixture/profile', root_context_id: agent.context_id!,
@@ -91,10 +98,42 @@ function splitCodexStatus(): AgentSnapshot {
{ surface: 'codex_cli', applied_revision: 19, state: 'passed', reason_code: null },
{ surface: 'codex_desktop', applied_revision: 19, state: 'not_verified', reason_code: null },
],
- current_selection: {
- ...agent.settings!.current_selection!,
- mode: 'codex_default',
- },
+ current_selection: selection,
+ };
+ return snapshot;
+}
+
+function qoder(configured: boolean): AgentSnapshot {
+ const context = `agent-context/qoder/sha256:${'a'.repeat(64)}`;
+ return {
+ trusted_authority: true, plans: { plans: [] },
+ agents: [{
+ agent_id: 'agent_qoder_default', version: 'fixture', context_id: context,
+ configuration_state: configured ? 'configured' : 'not_configured',
+ available_surfaces: ['qoder_cli'], native_model_catalog: null, status_error: null,
+ settings: {
+ state: 'not_configured', model_verified: false, restore_point_ref: null, current_selection: null,
+ collaboration: {
+ state: configured ? 'configured' : 'not_configured',
+ restore_point_ref: configured ? 'task-restore/qoder' : null,
+ current_selection: configured ? { trigger_mode: 'explicit' } : null,
+ },
+ },
+ }],
+ };
+}
+
+function qoderRouted(): AgentSnapshot {
+ const snapshot = qoder(true);
+ snapshot.plans = structuredClone(readyAgents.plans);
+ const agent = modelAgent(snapshot, 'agent_qoder_default');
+ const plans = snapshot.plans.plans.slice(0, 2);
+ agent.settings = {
+ ...agent.settings, state: 'configured', applied_revision: 23, restore_point_ref: 'model-restore/qoder',
+ current_selection: { mode: 'qoder_additional', allowed_plan_ids: plans.map(plan => plan.agent_plan_id) },
+ live_check_targets: [{ context_id: agent.context_id!, surface: 'qoder_cli', expected_applied_revision: 23,
+ client_model_ids: plans.map(plan => `fixture-hiroute/${plan.model_alias}`) }],
+ surface_results: [{ surface: 'qoder_cli', applied_revision: 23, state: 'not_verified', reason_code: null }],
};
return snapshot;
}
@@ -117,6 +156,9 @@ const control = {
protectedCodex,
cliOnly: () => freshCodex('codex_cli'),
splitCodexStatus,
+ qoderFresh: () => qoder(false),
+ qoderConfigured: () => qoder(true),
+ qoderRouted,
};
Object.assign(window, { agentTrust: control });
@@ -151,8 +193,9 @@ function Harness() {
setGeneration(value => value + 1);
};
return <PresentationRoot language="zh" theme="dark" textScale={1}>
- <div className="app-window"><main className="main" style={{ marginLeft: 0 }}>
- <div role="note">组件测试:所有 IPC 为 mock;不连接 Tauri、daemon 或真实安装。</div>
+ <div className="app-window">
+ <div role="note" style={{ gridColumn: '1 / -1', gridRow: 1 }}>组件测试:所有 IPC 为 mock;不连接 Tauri、daemon 或真实安装。</div>
+ <main className="main" style={{ gridColumn: '1 / -1', gridRow: 2 }}>
<Agents key={generation} language="zh" refreshVersion={refresh} operation={operation} mutationAllowed onMutation={() => { control.mutations += 1; }} onOperation={(operation, presentation) => { control.operations.push({ operation, presentation }); setOperation(operation); }} />
</main></div>
</PresentationRoot>;
diff --git a/apps/desktop/tests/v3/browser/plan-editor-ux.tsx b/apps/desktop/tests/v3/browser/plan-editor-ux.tsx
index 4ffc205a..c9223d7b 100644
--- a/apps/desktop/tests/v3/browser/plan-editor-ux.tsx
+++ b/apps/desktop/tests/v3/browser/plan-editor-ux.tsx
@@ -182,7 +182,9 @@ function Harness() {
async function run() {
setRunning(true);
if (workerChecks) {
- const outcome = await runRoutingWorkerScenarios(0, 5);
+ const ids = ['routing.capabilities.candidate-vs-fixed', 'worker.discovery.visible-only',
+ 'worker.installation.harness-isolation', 'worker.installation.replace', 'worker.installation.latest-edit'];
+ const outcome = await runRoutingWorkerScenarios({ ids, requiredIds: ids });
setResults(outcome.results);
setRunning(false);
return;
diff --git a/apps/desktop/tests/v3/browser/product-fixtures.ts b/apps/desktop/tests/v3/browser/product-fixtures.ts
index abf5cfcd..2c3f7cac 100644
--- a/apps/desktop/tests/v3/browser/product-fixtures.ts
+++ b/apps/desktop/tests/v3/browser/product-fixtures.ts
@@ -10,10 +10,11 @@ import { fixture as legacyHomeFixture } from '../../mvp16/browser/fixtures';
export type ProductScenario = 'fresh' | 'ready' | 'collaboration' | 'gap' | 'configured_no_sessions' | 'drift' | 'cooling' | 'free_exhausted' | 'api_failure' | 'unknown_model' | 'agent_blocked' | 'task_cancelled';
-export const fixtureTrace: { commands: string[]; clipboard: string[] } = { commands: [], clipboard: [] };
+export const fixtureTrace: { commands: string[]; requests: { command: string; payload: Record<string, any> | undefined }[]; clipboard: string[]; planPublicationError: string | null } = { commands: [], requests: [], clipboard: [], planPublicationError: null };
let agentPrerequisiteChecked = false;
let preparedWorkerSelection: Record<string, any> | null = null;
-export function resetFixtureTrace() { fixtureTrace.commands.length = 0; fixtureTrace.clipboard.length = 0; agentPrerequisiteChecked = false; preparedWorkerSelection = null; }
+const workerSelections = new Map<string, Record<string, any>>();
+export function resetFixtureTrace() { fixtureTrace.commands.length = 0; fixtureTrace.requests.length = 0; fixtureTrace.clipboard.length = 0; fixtureTrace.planPublicationError = null; agentPrerequisiteChecked = false; preparedWorkerSelection = null; workerSelections.clear(); }
const fixtureNow = new Date();
fixtureNow.setHours(14, 28, 0, 0);
@@ -166,6 +167,7 @@ const discoveredClaudeCandidate: ComputeCandidateView = {
upstream_model_id: 'glm-5.3',
display_name: 'GLM-5.3',
membership: 'catalog',
+ fact_basis: 'registered_catalog',
selectable: true,
}],
input_state: 'provided',
@@ -374,18 +376,18 @@ export function productTaskRead(scenario: ProductScenario): AgentTaskRead {
const cancelled = scenario === 'task_cancelled';
return { status: 'ready', tasks: [
{
- taskId: 'task/code-boundaries', runId: 'run/code-boundaries/1', title: '补齐边界条件测试', mainAgent: 'Claude Code', executor: 'Codex', routeName: '代码实现', createdAtMs: now - 8 * 60_000, status: 'complete',
- brief: '只修改路由编译器测试,覆盖空候选和不支持的能力。不要修改生产逻辑。', result: '已补齐两个边界测试,测试范围内通过;未修改生产逻辑。', sessionId: 'session/boundary-test', nativeSessionId: 'codex-thread-code', mainUsesOriginalModel: true,
- facts: [{ model: 'GPT-5.6-Sol', reasoning: 'max', tokens: '8.1K' }], scope: { directory: '~/Projects/HiRoute', files: '读写项目文件', network: '未授予网络访问' },
+ taskId: 'task/code-boundaries', runId: 'run/code-boundaries/1', title: '补齐边界条件测试', executor: 'Codex', routeName: '代码实现', createdAtMs: now - 8 * 60_000, status: 'complete',
+ brief: '只修改路由编译器测试,覆盖空候选和不支持的能力。不要修改生产逻辑。', result: '已补齐两个边界测试,测试范围内通过;未修改生产逻辑。', sessionId: 'session/boundary-test',
+ facts: [{ model: 'GPT-5.6-Sol', reasoning: 'max', tokens: '8.1K' }],
},
{
- taskId: 'task/route-review', runId: 'run/route-review/1', title: '评审路由编译边界', mainAgent: 'Codex', executor: 'Claude Code', routeName: '日常编码', createdAtMs: now - 40 * 60_000, status: 'complete',
- brief: '检查请求级与 Attempt 级作用域是否正确,给出证据,不修改文件。', result: '完成评审并给出两处代码定位。执行期间发生提交前模型接力,详见会话。', sessionId: 'session/route-review', nativeSessionId: 'claude-session-review',
- facts: [{ model: 'Claude Sonnet', reasoning: '16,000 tokens' }, { model: 'GPT-5.6-Sol', reasoning: 'max', tokens: '42.8K' }], scope: { directory: '~/Projects/HiRoute', files: '只读项目文件', network: '未授予网络访问' },
+ taskId: 'task/route-review', runId: 'run/route-review/1', title: '评审路由编译边界', executor: 'Claude Code', routeName: '日常编码', createdAtMs: now - 40 * 60_000, status: 'complete',
+ brief: '检查请求级与 Attempt 级作用域是否正确,给出证据,不修改文件。', result: '完成评审并给出两处代码定位。执行期间发生提交前模型接力,详见会话。', sessionId: 'session/route-review',
+ facts: [{ model: 'Claude Sonnet', reasoning: '16,000 tokens' }, { model: 'GPT-5.6-Sol', reasoning: 'max', tokens: '42.8K' }],
},
{
- taskId: 'task/fix-empty-list', runId: 'run/fix-empty-list/1', title: '修复空列表显示', mainAgent: 'Claude Code', executor: 'Codex', routeName: '代码实现', createdAtMs: now - 46 * 60_000, status: cancelled ? 'cancelled' : 'running',
- brief: '按现有组件修复空列表显示,不修改路由规则。', result: null, sessionId: null, nativeSessionId: null, mainUsesOriginalModel: true, facts: [], scope: { directory: '~/Projects/HiRoute', files: '读写项目文件', network: '未授予网络访问' },
+ taskId: 'task/fix-empty-list', runId: 'run/fix-empty-list/1', title: '修复空列表显示', executor: 'Codex', routeName: '代码实现', createdAtMs: now - 46 * 60_000, status: cancelled ? 'cancelled' : 'running',
+ brief: '按现有组件修复空列表显示,不修改路由规则。', result: null, sessionId: null, facts: [],
},
] };
}
@@ -456,6 +458,7 @@ function agentSnapshotFor(scenario: ProductScenario): AgentSnapshot {
export function mockProductInvoke(command: string, payload: Record<string, any> | undefined, scenario: ProductScenario) {
fixtureTrace.commands.push(command);
+ fixtureTrace.requests.push({ command, payload: structuredClone(payload) });
const fresh = scenario === 'fresh';
if (command === 'compute_management_snapshot') return fresh ? { ...readyManagement, sources: [] } : readyManagement;
if (command === 'compute_connection_options') return {
@@ -504,6 +507,7 @@ export function mockProductInvoke(command: string, payload: Record<string, any>
executors: fresh ? [
{ harness: 'codex_cli', state: 'unavailable', reason: 'installation_not_configured', start_approve_all: unavailable, cancel: unavailable, continue_session: unavailable, restricted_policy: unavailable },
{ harness: 'claude_code', state: 'unavailable', reason: 'installation_not_configured', start_approve_all: unavailable, cancel: unavailable, continue_session: unavailable, restricted_policy: unavailable },
+ { harness: 'qoder_cli', state: 'unavailable', reason: 'installation_not_configured', start_approve_all: unavailable, cancel: unavailable, continue_session: unavailable, restricted_policy: unavailable },
] : [
{
harness: 'codex_cli', state: 'ready',
@@ -516,27 +520,37 @@ export function mockProductInvoke(command: string, payload: Record<string, any>
continue_session: { state: 'unavailable', reason: 'resume_unavailable' },
restricted_policy: { state: 'unknown', reason: 'restricted_policy_unverified' },
},
+ { harness: 'qoder_cli', state: 'unavailable', reason: workerSelections.has('qoder_cli') ? 'runtime_unverified' : 'installation_not_configured', start_approve_all: unavailable, cancel: unavailable, continue_session: unavailable, restricted_policy: unavailable },
],
};
}
if (command === 'worker_dependencies_discover' || command === 'worker_dependencies_select_confirm') {
const confirmed = command === 'worker_dependencies_select_confirm' ? preparedWorkerSelection : null;
const harness = confirmed?.harness ?? payload?.input?.harness ?? 'claude_code';
- const name = harness === 'codex_cli' ? 'codex' : 'claude';
- const selection = confirmed ?? {
+ const name = harness === 'codex_cli' ? 'codex' : harness === 'qoder_cli' ? 'qoder' : 'claude';
+ if (confirmed) {
+ const { expected_selection_revision: _revision, ...installation } = confirmed;
+ workerSelections.set(harness, installation);
+ }
+ const selected = workerSelections.get(harness);
+ const selection = selected ?? {
harness,
cli_path: `/usr/local/bin/${name}`,
- adapter_path: `/usr/local/lib/${name}-acp/adapter.js`,
- node_path: '/usr/local/bin/node',
+ ...(harness === 'qoder_cli' ? {} : {
+ adapter_path: `/usr/local/lib/${name}-acp/adapter.js`,
+ node_path: '/usr/local/bin/node',
+ }),
};
const data = {
schema: 'hiroute.worker-dependencies-view/v1',
selection_revisions: [{ harness, revision: 1 }],
- selected: [selection],
+ selected: harness === 'qoder_cli' && !selected ? [] : [selection],
candidates: [
{ harness, component: 'cli', path: selection.cli_path, source: 'selected', state: 'found' },
- { harness, component: 'adapter', path: selection.adapter_path, source: 'selected', state: 'found' },
- { harness, component: 'node', path: selection.node_path, source: 'selected', state: 'found' },
+ ...(harness === 'qoder_cli' ? [] : [
+ { harness, component: 'adapter', path: selection.adapter_path, source: 'selected', state: 'found' },
+ { harness, component: 'node', path: selection.node_path, source: 'selected', state: 'found' },
+ ]),
],
install_hints: [],
};
@@ -601,7 +615,12 @@ export function mockProductInvoke(command: string, payload: Record<string, any>
: { preview: { applicable: true, blockers: [] }, mutation: { state: 'applied', operation: { state: 'succeeded' } } };
if (command === 'check_agent_authentication') { agentPrerequisiteChecked = true; return true; }
if (command === 'check_agent_live') return { accepted: true, scope: 'live', model_call: true, state: 'passed', call_count: 1, requested_call_count: 1 };
- if (command === 'preview_plan_editor') return { state: 'succeeded', operation: { state: 'succeeded' } };
+ if (command === 'preview_plan_editor') {
+ if (payload?.input?.action === 'publish' && fixtureTrace.planPublicationError) {
+ throw { source: 'backend', envelope: { error: { code: fixtureTrace.planPublicationError } } };
+ }
+ return { state: 'succeeded', operation: { state: 'succeeded' } };
+ }
if (command === 'preview_restore_name') return { operation: { state: 'succeeded' } };
if (command === 'preview_compute_save') return {
candidate: payload?.change?.subject?.candidate,
diff --git a/apps/desktop/tests/v3/browser/product-shell-scenarios.mjs b/apps/desktop/tests/v3/browser/product-shell-scenarios.mjs
new file mode 100644
index 00000000..77dede82
--- /dev/null
+++ b/apps/desktop/tests/v3/browser/product-shell-scenarios.mjs
@@ -0,0 +1,195 @@
+import { scenario, scenarioCatalog, runScenarios } from './scenario-selection.mjs';
+import { productShellRequired } from './scenario-requirements.mjs';
+const c = () => window.productShell;
+const pause = ms => new Promise(resolve => setTimeout(resolve, ms));
+const assert = (condition, message) => { if (!condition) throw new Error(message); };
+const visible = element => Boolean(element?.getClientRects().length);
+const all = selector => [...document.querySelectorAll(selector)].filter(visible);
+const text = () => document.body.innerText;
+const button = label => all('button').find(element => element.textContent.trim() === label);
+const calls = command => c().commands.filter(item => item.command === command);
+async function until(predicate, label, timeout = 6000) {
+ const deadline = Date.now() + timeout;
+ while (!predicate()) { if (Date.now() > deadline) throw new Error(`Timed out: ${label}; ${text().slice(-500)}`); await pause(25); }
+ await pause(30);
+}
+async function click(label) { await until(() => button(label), label); button(label).click(); await pause(40); }
+async function fresh(setup = () => {}) {
+ c().reset(); setup(); await until(() => text().includes('仅在本机运行'), 'ready DesktopApp');
+}
+function setInput(input, value) {
+ assert(input, 'Expected an editable input');
+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value').set.call(input, value);
+ input.dispatchEvent(new Event('input', { bubbles: true }));
+}
+const operation = (state = 'running', id = 'operation/shell') => ({ operation_id: id, state, sequence: state === 'succeeded' ? 2 : 1, cancellable: false, safe_error_code: null });
+const feedback = () => document.querySelector('[data-operation-phase]');
+async function pending() {
+ await fresh(() => {
+ c().desktop.pending = { plan_id: 'plan/daily', operation_id: 'operation/shell', idempotency_key: 'key/shell' };
+ c().handlers.observe_operation = () => operation();
+ });
+ await until(() => feedback()?.dataset.operationState === 'running', 'observed operation');
+}
+async function routing() {
+ await click('智能路由');
+ await until(() => all('.master-list .list-row').length, 'saved routes');
+ all('.master-list .list-row')[0].click();
+ await until(() => document.querySelector('.plan-identity-fields input'), 'route editor');
+}
+const scenarios = [
+ scenario('desktop.settings.persisted-scale', ['desktop-presentation'], 'Settings apply and persist all supported text scales through the shell', async () => {
+ await fresh(); await click('设置');
+ for (const [label, value] of [['150%', '1.5'], ['200%', '2'], ['100%', '1']]) {
+ await click(label);
+ assert(button(label).getAttribute('aria-pressed') === 'true', 'Scale choice did not become selected');
+ assert(document.querySelector('.hr-ui').dataset.textScale === value, 'Shell did not apply the selected scale');
+ assert(localStorage.getItem('hiroute.text-scale') === value, 'Selected scale was not persisted');
+ }
+ }),
+ scenario('desktop.operation.dismiss-observes', ['operation-feedback'], 'Closing feedback leaves the operation observable and never cancels it', async () => {
+ await pending();
+ const before = calls('observe_operation').length;
+ feedback().querySelector('button[aria-label="关闭"]').click();
+ await until(() => !feedback(), 'feedback closed');
+ await until(() => calls('observe_operation').length > before, 'observation continues after closing');
+ assert(!c().commands.some(({ command }) => /cancel|stop_observ/.test(command)), 'Closing feedback cancelled or stopped the operation');
+ }),
+ scenario('desktop.operation.identity-retry-converges', ['operation-feedback'], 'A mismatched observation stays neutral and retry converges on the accepted operation', async () => {
+ await pending();
+ const before = calls('observe_operation').length;
+ c().handlers.observe_operation = () => operation('succeeded', 'operation/unrelated');
+ await until(() => calls('observe_operation').length > before, 'first mismatched observation');
+ assert(!feedback().dataset.observationErrorCode, 'A transient mismatch skipped the recovery grace period');
+ await until(() => feedback()?.dataset.operationPhase === 'unverified', 'unconfirmed result becomes retryable', 12000);
+ assert(feedback().dataset.observationErrorCode === 'OPERATION_IDENTITY_MISMATCH', 'Mismatch was not diagnosed');
+ assert(feedback().querySelector('.oc-spinner') && !feedback().querySelector('.callout.bad'), 'Unknown result was presented as terminal failure');
+ c().handlers.observe_operation = () => operation('succeeded');
+ c().desktop.pending = null;
+ const reads = calls('desktop_snapshot').length;
+ await click('重新查询');
+ await until(() => feedback()?.dataset.operationPhase === 'succeeded', 'retry observes the accepted identity');
+ await until(() => calls('desktop_snapshot').length > reads, 'success refreshes actual state');
+ await until(() => !feedback(), 'success feedback dismisses itself', 6500);
+ }),
+ scenario('desktop.operation.repeated-submission', ['operation-feedback'], 'Repeated accepted and unverified Agent saves each resume operation observation', async () => {
+ for (const knownIdentity of [true, false]) {
+ await fresh(() => {
+ const agent = c().agents.agents.find(item => item.agent_id === 'agent_codex_default');
+ agent.configuration_state = 'not_configured';
+ agent.settings.current_selection = null;
+ agent.settings.state = 'not_configured';
+ c().agents.plans.plans = c().agents.plans.plans.filter(plan => plan.head.status === 'enabled').slice(0, 1);
+ c().handlers.preview_agent_settings = () => ({ preview: { applicable: true, blockers: [] }, mutation: { state: knownIdentity ? 'applied' : 'response_unknown', operation: knownIdentity ? operation() : null } });
+ });
+ await click('Agent');
+ await until(() => all('.native-list .list-row').some(item => item.textContent.includes('Codex')), 'Codex row');
+ all('.native-list .list-row').find(item => item.textContent.includes('Codex')).click();
+ await until(() => document.querySelector('[data-agent-facet="model"]'), 'model configuration');
+ document.querySelector('[data-agent-facet="model"]').click();
+ for (let attempt = 0; attempt < 2; attempt++) {
+ if (attempt && knownIdentity) document.querySelector('[data-agent-facet="model"]').click();
+ await until(() => document.querySelector('[role="dialog"] button[type="submit"]')?.disabled === false, 'save enabled');
+ const before = calls('observe_operation').length;
+ document.querySelector('[role="dialog"] button[type="submit"]').click();
+ await until(() => calls('preview_agent_settings').length === attempt + 1, 'save submitted');
+ await until(() => calls('observe_operation').length > before, `${knownIdentity ? 'accepted' : 'unverified'} save ${attempt + 1} is observed`, 4000);
+ }
+ }
+ }),
+ scenario('desktop.routing.qoder-budget-checkpoint', ['routing-editor', 'qoder'], 'An accepted publication that fails its Qoder budget checkpoint explains model reconnection and retains edits', async () => {
+ await fresh(() => {
+ c().handlers.preview_plan_editor = () => ({ state: 'applied', operation: operation() });
+ c().handlers.observe_operation = () => ({ ...operation('rolled_back'), sequence: 2, safe_error_code: 'QODER_MODEL_BUDGET_CONFLICT' });
+ });
+ await routing();
+ const contextMode = document.querySelector('.plan-context-mode');
+ assert(contextMode && visible(contextMode), 'Context window mode is not reachable');
+ contextMode.value = 'custom';
+ contextMode.dispatchEvent(new Event('change', { bubbles: true }));
+ await until(() => visible(document.querySelector('.plan-context-window-field')), 'custom context window');
+ const contextWindow = document.querySelector('.plan-context-window-field');
+ setInput(contextWindow, '32000');
+ await until(() => document.querySelector('[data-codex-capability-summary]')?.textContent.includes('32K'), 'model options for the edited context window');
+ await click('发布更改');
+ await until(() => feedback()?.dataset.operationPhase === 'failed', 'accepted publication checkpoint failure');
+ const guidance = feedback().querySelector('[data-error-code="QODER_MODEL_BUDGET_CONFLICT"]');
+ assert(guidance?.textContent.includes('停用 Qoder 的模型路由') && guidance.textContent.includes('再发布此计划并重新配置模型路由') && guidance.textContent.includes('任务协作无需停用'), 'Checkpoint failure lacks independent model recovery steps');
+ const publication = calls('preview_plan_editor').at(-1)?.payload.input;
+ assert(publication?.action === 'publish' && publication.editor.limits.context_window_tokens === 32000, 'The accepted request did not publish the edited budget');
+ assert(contextWindow.value === '32000' && !contextWindow.disabled && !button('发布更改').disabled, 'Checkpoint failure discarded or locked the local edit');
+ assert(calls('preview_agent_settings').length === 0 && calls('check_agent_live').length === 0, 'Checkpoint failure implicitly changed an Agent connection or called a model');
+ }),
+ scenario('desktop.routing.reactivation-models', ['routing-editor'], 'Returning to an existing route reloads saved model choices and scopes quality to active models', async () => {
+ await fresh(); await routing();
+ await until(() => document.querySelector('.quality-model-scope'), 'active model scope');
+ assert(document.querySelector('.quality-model-scope').textContent.includes('Qwen'), 'Active route models are absent');
+ assert(!document.querySelector('.quality-model-filter'), 'Quality asks users to type internal model IDs');
+ const before = calls('compute_management_snapshot').length;
+ const optionsBefore = calls('plan_editor_options').length;
+ await click('首页');
+ const revisedName = 'Saved renamed model';
+ c().management.sources.find(source => source.source_id === 'source/bailian/coding').models[0].display_name = revisedName;
+ c().handlers.plan_editor_options = payload => {
+ const options = c().fixtureResponse('plan_editor_options', payload);
+ return { ...options, candidates: options.candidates.map(candidate => candidate.binding_id === 'binding/bailian/qwen-coder' ? { ...candidate, display_name: revisedName } : candidate) };
+ };
+ await click('智能路由');
+ await until(() => calls('compute_management_snapshot').length > before && calls('plan_editor_options').length > optionsBefore, 'fresh saved choices after reactivation');
+ assert(document.querySelector('.plan-identity-fields input'), 'Returning lost the existing editor');
+ await until(() => document.querySelector('.quality-model-scope')?.textContent.includes(revisedName), 'latest saved model name is visible');
+ }),
+ scenario('desktop.models.documentation-retains-input', ['model-connections'], 'Model readiness stays bounded and a failed documentation link preserves input', async () => {
+ await fresh(); await click('模型');
+ await until(() => all('button').some(item => item.textContent.includes('GPT-6-Astra')), 'model row');
+ all('button').find(item => item.textContent.includes('GPT-6-Astra')).click();
+ await until(() => text().includes('接入就绪'), 'readiness status');
+ assert(text().includes('不代表上游推理或工具调用已验证'), 'Local readiness claims upstream inference verification');
+ await click('添加模型');
+ await until(() => all('button').some(item => item.textContent.includes('添加 API')), 'add API entry');
+ all('button').find(item => item.textContent.includes('添加 API')).click();
+ await until(() => document.querySelector('[role="dialog"] input[type="password"]'), 'API key input');
+ const key = document.querySelector('[role="dialog"] input[type="password"]');
+ setInput(key, 'synthetic-input-preserved'); await pause(40);
+ const link = all('a').find(item => item.textContent.includes('官方说明与获取 Key'));
+ assert(link?.target === '_blank' && link.rel.includes('noreferrer') && link.href.startsWith('https://'), 'Web documentation link is unavailable');
+ c().handlers.open_external_url = () => { throw new Error('BROWSER_UNAVAILABLE'); };
+ link.click(); await until(() => text().includes('当前表单内容已保留'), 'native browser failure feedback');
+ assert(calls('open_external_url').at(-1)?.payload.url === link.href, 'Native command did not receive the displayed documentation URL');
+ assert(key.value === 'synthetic-input-preserved', 'Opening documentation lost the API key input');
+ // Prevent an actual external navigation while observing the normal web default action.
+ const internals = window.__TAURI_INTERNALS__;
+ let preventedByProduct;
+ const observeClick = event => { preventedByProduct = event.defaultPrevented; event.preventDefault(); };
+ document.addEventListener('click', observeClick);
+ try { delete window.__TAURI_INTERNALS__; link.click(); }
+ finally { window.__TAURI_INTERNALS__ = internals; document.removeEventListener('click', observeClick); }
+ assert(preventedByProduct === false && calls('open_external_url').length === 1, 'Web preview does not retain ordinary anchor behavior');
+ }),
+ scenario('desktop.routing.classifier-protocol', ['routing-editor'], 'Classifier choice and protocol copy/save expose visible outcomes', async () => {
+ await fresh(); await routing();
+ const custom = all('.classifier-choice').find(item => item.textContent.includes('自定义分类服务'));
+ assert(custom, 'Custom classifier choice is missing'); custom.click(); await pause(40);
+ assert(custom.getAttribute('aria-pressed') === 'true' && visible(custom.querySelector('svg')), 'Custom choice is not visibly selected');
+ const local = all('.classifier-choice').find(item => item.textContent.includes('内置规则'));
+ local.click(); await pause(40);
+ assert(local.getAttribute('aria-pressed') === 'true' && custom.getAttribute('aria-pressed') === 'false', 'Built-in choice did not replace the custom selection');
+ custom.click(); await pause(40);
+ await click('查看接入协议');
+ await click('复制 curl');
+ await until(() => c().clipboard.length === 1, 'curl copied');
+ const curl = c().clipboard[0];
+ assert(curl.includes('https://classifier.example/v1/decisions'), 'Curl targets the wrong API');
+ for (const field of ['branches', 'latest_user', 'visible_conversation', 'history_partial', 'assessment_from']) assert(curl.includes(`"${field}"`), `Curl lacks ${field}`);
+ let finish;
+ c().handlers.save_classifier_openapi = () => new Promise(resolve => { finish = resolve; });
+ await click('保存 OpenAPI');
+ assert(button('保存 OpenAPI').disabled && text().includes('请选择保存位置'), 'Native save did not show a pending state');
+ finish('cancelled'); await until(() => text().includes('已取消保存'), 'cancelled save outcome');
+ c().handlers.save_classifier_openapi = () => 'saved';
+ await click('保存 OpenAPI'); await until(() => text().includes('已保存:hiroute-decision.openapi.json'), 'saved file outcome');
+ assert(calls('save_classifier_openapi').length === 2, 'Save did not use exactly one native command per click');
+ }),
+];
+export const productShellScenarioCatalog = scenarioCatalog(scenarios);
+export const runProductShellScenarios = (selection = { requiredIds: productShellRequired }) => runScenarios(scenarios, selection);
diff --git a/apps/desktop/tests/v3/browser/product-shell.html b/apps/desktop/tests/v3/browser/product-shell.html
new file mode 100644
index 00000000..89554172
--- /dev/null
+++ b/apps/desktop/tests/v3/browser/product-shell.html
@@ -0,0 +1,3 @@
+<!doctype html>
+<html lang="zh-CN"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>DesktopApp behavior fixture</title></head>
+<body><div id="root"></div><script type="module" src="./product-shell.tsx"></script></body></html>
diff --git a/apps/desktop/tests/v3/browser/product-shell.tsx b/apps/desktop/tests/v3/browser/product-shell.tsx
new file mode 100644
index 00000000..b0ebf429
--- /dev/null
+++ b/apps/desktop/tests/v3/browser/product-shell.tsx
@@ -0,0 +1,48 @@
+import React from 'react';
+import { createRoot } from 'react-dom/client';
+import { mockIPC, mockWindows } from '@tauri-apps/api/mocks';
+import { DesktopApp } from '../../../src/product/DesktopApp';
+import { mockProductInvoke, readyAgents, readyDesktop, readyManagement } from './product-fixtures';
+import '../../../src/occami/styles.css';
+
+// Only the IPC boundary is synthetic. Navigation, settings, forms and operation
+// observation all run through DesktopApp; tests never call its private callbacks.
+const root = createRoot(document.getElementById('root')!);
+let generation = 0;
+const control = {
+ desktop: structuredClone(readyDesktop),
+ agents: structuredClone(readyAgents),
+ management: structuredClone(readyManagement),
+ commands: [] as { command: string; payload: Record<string, unknown> }[],
+ clipboard: [] as string[],
+ handlers: {} as Record<string, (payload: Record<string, unknown>) => unknown>,
+ fixtureResponse: (command: string, payload: Record<string, unknown>) => mockProductInvoke(command, payload, 'ready'),
+ reset: () => {
+ control.desktop = structuredClone(readyDesktop);
+ control.agents = structuredClone(readyAgents);
+ control.management = structuredClone(readyManagement);
+ control.commands = [];
+ control.clipboard = [];
+ control.handlers = {};
+ localStorage.setItem('hiroute.language', 'zh');
+ localStorage.setItem('hiroute.text-scale', '1');
+ root.render(<DesktopApp key={++generation} />);
+ },
+};
+Object.assign(window, { productShell: control });
+Object.defineProperty(navigator, 'clipboard', { configurable: true, value: {
+ writeText: async (value: string) => { control.clipboard.push(value); },
+} });
+mockIPC((command, payload) => {
+ const args = (payload ?? {}) as Record<string, unknown>;
+ control.commands.push({ command, payload: args });
+ if (control.handlers[command]) return control.handlers[command](args);
+ if (command === 'startup_status') return { state: 'ready', recovery_available: false };
+ if (command === 'desktop_snapshot') return structuredClone(control.desktop);
+ if (command === 'agent_snapshot') return structuredClone(control.agents);
+ if (command === 'compute_management_snapshot') return structuredClone(control.management);
+ if (command === 'observe_operation' || command === 'web_confirmation_snapshot') return null;
+ return mockProductInvoke(command, args, 'ready');
+}, { shouldMockEvents: true });
+mockWindows('main');
+control.reset();
diff --git a/apps/desktop/tests/v3/browser/routing-worker-scenarios.mjs b/apps/desktop/tests/v3/browser/routing-worker-scenarios.mjs
index 1a229a73..b41e0d19 100644
--- a/apps/desktop/tests/v3/browser/routing-worker-scenarios.mjs
+++ b/apps/desktop/tests/v3/browser/routing-worker-scenarios.mjs
@@ -1,3 +1,6 @@
+import { scenario, scenarioCatalog, runScenarios } from './scenario-selection.mjs';
+import { routingWorkerRequired } from './scenario-requirements.mjs';
+
const tick = () => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));
const pause = milliseconds => new Promise(resolve => setTimeout(resolve, milliseconds));
const assert = (condition, message) => { if (!condition) throw new Error(message); };
@@ -11,7 +14,7 @@ const calls = name => trace().commands.filter(command => command === name).lengt
async function until(predicate, label) {
const deadline = Date.now() + 5000;
while (!predicate()) {
- if (Date.now() > deadline) throw new Error(`Timed out: ${label}`);
+ if (Date.now() > deadline) throw new Error(`Timed out: ${label}; plan requests: ${calls('preview_plan_editor')}; fixture feedback: ${[...document.querySelectorAll('.plan-editor [role="alert"]')].map(node => node.textContent.trim()).join(' | ').slice(0, 400)}`);
await pause(20);
}
await tick();
@@ -23,7 +26,7 @@ function setInput(input, value) {
}
const scenarios = [
- ['Codex capability summary separates candidate narrowing from fixed limits', async () => {
+ scenario('routing.capabilities.candidate-vs-fixed', ['routing-capabilities'], 'Codex capability summary separates candidate narrowing from fixed limits', async () => {
await until(() => document.querySelector('[data-codex-capability-state="available"]'), 'Codex capability summary');
const summary = document.querySelector('[data-codex-capability-summary]');
assert(summary.textContent.includes('上下文 64K') && summary.textContent.includes('输入 文本'), 'The shared Codex capability summary is incomplete');
@@ -41,8 +44,8 @@ const scenarios = [
const fixed = document.querySelector('[data-codex-fixed-limit="parallel_tool_calls_disabled"]');
assert(visible(fixed) && fixed?.textContent.includes('不由任何候选模型造成'), 'The fixed serial-tool limit is attributed to a candidate');
assert(!document.querySelector('[data-codex-capability-unavailable]'), 'Complete metadata was rendered as unavailable');
- }],
- ['configured delegation discovers only while its configuration is visible', async () => {
+ }),
+ scenario('worker.discovery.visible-only', ['worker-installation'], 'configured delegation discovers only while its configuration is visible', async () => {
await until(() => document.body.innerText.includes('Claude Code 本机安装'), 'initial worker installation');
await until(() => calls('worker_dependencies_discover') === 1, 'initial dependency discovery');
trace().commands.length = 0;
@@ -54,8 +57,8 @@ const scenarios = [
containingButton('允许委派任务给执行 Agent').click();
await until(() => document.body.innerText.includes('Claude Code 本机安装'), 'restored worker installation');
await until(() => calls('worker_dependencies_discover') === 1, 'discovery after explicit reopen');
- }],
- ['Codex CLI and Claude Code keep independent installation surfaces', async () => {
+ }),
+ scenario('worker.installation.harness-isolation', ['worker-installation'], 'Codex CLI and Claude Code keep independent installation surfaces', async () => {
trace().commands.length = 0;
containingButton('Codex CLI').click();
await until(() => document.body.innerText.includes('Codex CLI 本机安装'), 'Codex installation surface');
@@ -64,9 +67,9 @@ const scenarios = [
await until(() => document.body.innerText.includes('Claude Code 本机安装'), 'Claude installation surface');
await until(() => calls('worker_dependencies_discover') === 2, 'Claude discovery');
assert(document.querySelector('.v3-executor.selected')?.textContent.includes('Claude Code'), 'The selected executor did not return to Claude Code');
- }],
+ }),
// Selection uses one visible save click; native prepare/confirm stays an internal binding.
- ['a configured installation can be explicitly replaced through advanced paths', async () => {
+ scenario('worker.installation.replace', ['worker-replacement'], 'a configured installation can be explicitly replaced through advanced paths', async () => {
trace().commands.length = 0;
button('更换或高级设置').click();
await until(() => document.querySelector('#worker-claude_code-adapter'), 'manual adapter path');
@@ -82,9 +85,13 @@ const scenarios = [
'One explicit click did not prepare and commit exactly once');
assert(adapter.value === replacement, 'The committed adapter path did not remain selected');
assert(!document.querySelector('[role="alertdialog"]'), 'An obsolete second confirmation appeared');
- }],
- ['editing a replacement before saving commits only the latest path', async () => {
+ }),
+ scenario('worker.installation.latest-edit', ['worker-replacement'], 'editing a replacement before saving commits only the latest path', async () => {
trace().commands.length = 0;
+ if (!document.querySelector('#worker-claude_code-cli')) {
+ button('更换或高级设置').click();
+ await until(() => document.querySelector('#worker-claude_code-cli'), 'manual CLI path');
+ }
const cli = document.querySelector('#worker-claude_code-cli');
assert(cli, 'The manual CLI path is missing');
setInput(cli, '/opt/hiroute/claude-next');
@@ -99,8 +106,43 @@ const scenarios = [
'The latest path was not saved by one explicit click');
assert(cli.value === '/opt/hiroute/claude-final', 'An obsolete CLI path replaced the latest edit');
assert(!document.querySelector('[role="alertdialog"]'), 'An obsolete second confirmation appeared');
- }],
- ['an unobserved route save does not lock the editor or the route list', async () => {
+ }),
+ scenario('qoder.installation.single-cli', ['qoder', 'qoder-worker'], 'Qoder saves one CLI and switching execution Agents retains their independent installations', async () => {
+ if (!document.querySelector('#worker-claude_code-cli')) {
+ containingButton('Claude Code').click();
+ await until(() => button('更换或高级设置'), 'Claude installation before switching');
+ button('更换或高级设置').click(); await tick();
+ }
+ const previousClaude = document.querySelector('#worker-claude_code-cli').value;
+ trace().commands.length = 0; trace().requests.length = 0;
+ containingButton('Qoder CLI').click();
+ await until(() => button('一键检测'), 'Qoder detection action');
+ assert(calls('worker_dependencies_select_prepare') === 0, 'Choosing Qoder saved an installation implicitly');
+ button('一键检测').click();
+ await until(() => button('使用此安装'), 'single CLI recommendation');
+ button('高级设置').click(); await tick();
+ const cli = document.querySelector('#worker-qoder_cli-cli');
+ assert(cli && !document.querySelector('#worker-qoder_cli-adapter') && !document.querySelector('#worker-qoder_cli-node'), 'Qoder did not render exactly its one CLI input');
+ assert(!document.querySelector('.worker-dependencies').textContent.includes('Node.js'), 'Qoder advertised an unnecessary runtime');
+ assert(document.querySelector('[data-qoder-installation-guide] a').href === 'https://docs.qoder.com/cli/installation', 'Official installation guidance is missing');
+ setInput(cli, '/home/fixture/.local/bin/qodercli'); await tick();
+ assert(!button('使用此安装').disabled, 'A standalone Qoder CLI required adapter placeholders');
+ button('使用此安装').click();
+ await until(() => document.querySelector('.worker-dependencies .badge.good'), 'Qoder selection persisted');
+ const request = trace().requests.find(item => item.command === 'worker_dependencies_select_prepare').payload.input;
+ assert(request.harness === 'qoder_cli' && request.cli_path === '/home/fixture/.local/bin/qodercli', 'The selected CLI did not cross the public boundary');
+ assert(!('adapter_path' in request) && !('node_path' in request), 'Qoder request did not omit unsupported components');
+ assert(calls('worker_dependencies_select_prepare') === 1 && calls('worker_dependencies_select_confirm') === 1, 'One click did not commit exactly once');
+ containingButton('Claude Code').click();
+ await until(() => button('更换或高级设置'), 'existing Claude installation');
+ button('更换或高级设置').click(); await tick();
+ assert(document.querySelector('#worker-claude_code-cli')?.value === previousClaude, 'Qoder replaced the previously saved Claude installation');
+ containingButton('Qoder CLI').click();
+ await until(() => button('更换或高级设置'), 'saved Qoder installation');
+ button('更换或高级设置').click(); await tick();
+ assert(document.querySelector('#worker-qoder_cli-cli')?.value === request.cli_path, 'Switching away lost the Qoder installation');
+ }),
+ scenario('routing.save.unobserved-editable', ['route-save'], 'an unobserved route save does not lock the editor or the route list', async () => {
trace().commands.length = 0;
const name = document.querySelector('.plan-identity-fields input');
assert(name, 'The route editor is missing');
@@ -113,14 +155,35 @@ const scenarios = [
assert([...document.querySelectorAll('.master-list .list-row')].every(row => !row.disabled), 'The route list is blocked by the prior save');
setInput(name, 'Newer local edit');
await until(() => document.querySelector('.plan-identity-fields input')?.value === 'Newer local edit', 'newer input retained');
- }],
+ }),
+ scenario('routing.publish.qoder-budget-conflict', ['route-save', 'qoder'], 'a smaller Qoder model budget keeps route edits and explains model reconnection without disabling collaboration', async () => {
+ trace().commands.length = 0;
+ const contextMode = document.querySelector('.plan-context-mode');
+ assert(contextMode && visible(contextMode), 'Context window mode is not reachable');
+ contextMode.value = 'custom';
+ contextMode.dispatchEvent(new Event('change', { bubbles: true }));
+ await until(() => visible(document.querySelector('.plan-context-window-field')), 'custom context window');
+ const window = document.querySelector('.plan-context-window-field');
+ assert(window && visible(window), 'The user cannot edit the plan context window');
+ setInput(window, '32000');
+ await until(() => document.querySelector('[data-codex-capability-summary]')?.textContent.includes('32K'), 'model options for the edited context window');
+ await until(() => !button('发布更改')?.disabled, 'plan publication action');
+ trace().planPublicationError = 'QODER_MODEL_BUDGET_CONFLICT';
+ try {
+ button('发布更改').click();
+ await until(() => document.querySelector('.plan-editor [role="alert"]')?.textContent.includes('停用 Qoder 的模型路由'), 'Qoder budget recovery guidance');
+ const feedback = document.querySelector('.plan-editor [role="alert"]').textContent;
+ assert(feedback.includes('再发布此计划并重新配置模型路由') && feedback.includes('任务协作无需停用'), 'Budget recovery confuses model reconnection with task collaboration');
+ const publication = trace().requests.filter(item => item.command === 'preview_plan_editor').at(-1).payload.input;
+ assert(publication.action === 'publish' && publication.editor.limits.context_window_tokens === 32000, 'The attempted publication did not carry the edited budget');
+ assert(window.value === '32000' && !window.disabled && !button('发布更改').disabled, 'Rejected publication discarded or locked route edits');
+ assert(calls('preview_agent_settings') === 0 && calls('check_agent_live') === 0, 'Publication failure implicitly changed an Agent connection or called a model');
+ } finally { trace().planPublicationError = null; }
+ }),
];
-export async function runRoutingWorkerScenarios(start = 0, end = scenarios.length) {
- const results = [];
- for (const [name, run] of scenarios.slice(start, end)) {
- try { await run(); results.push({ name, state: 'green' }); }
- catch (error) { results.push({ name, state: 'red', error: error.message }); }
- }
- return { evidence: 'React components + mock IPC only; not native/Tauri and not the real daemon', tests: results.length, passed: results.filter(item => item.state === 'green').length, failed: results.filter(item => item.state === 'red').length, results };
+export const routingWorkerScenarioCatalog = scenarioCatalog(scenarios);
+
+export async function runRoutingWorkerScenarios(selection = { requiredIds: routingWorkerRequired }) {
+ return runScenarios(scenarios, selection);
}
diff --git a/apps/desktop/tests/v3/browser/scenario-requirements.mjs b/apps/desktop/tests/v3/browser/scenario-requirements.mjs
new file mode 100644
index 00000000..626cd2bb
--- /dev/null
+++ b/apps/desktop/tests/v3/browser/scenario-requirements.mjs
@@ -0,0 +1,55 @@
+// Reviewed capability gates. New discovered scenarios run in full mode automatically.
+// Retire a required ID only with an explicit replacement of its unique guarantee.
+export const agentTrustRequired = ['codex.restore.conflict-active',
+ 'codex.enable.draft-cancel',
+ 'claude.enable.shared-presets',
+ 'codex.enable.confirmed-command',
+ 'codex.routing.fixed-binding',
+ 'codex.routing.plan-only',
+ 'codex.routing.mixed-native-default',
+ 'agent.configuration.shared-interactions',
+ 'codex.recovery.token-controls',
+ 'codex.routing.preview-rejection',
+ 'agent.diagnostics.non-runnable',
+ 'agent.diagnostics.rescan',
+ 'agent.diagnostics.late-failure',
+ 'agent.recovery.non-runnable',
+ 'agent.configuration.independent-facets',
+ 'agent.configuration.prerequisite',
+ 'claude.collaboration.check-before-save',
+ 'claude.collaboration.retry-preserves-edit',
+ 'claude.collaboration.obsolete-blocker',
+ 'qoder.collaboration.enable-without-model',
+ 'qoder.collaboration.retry-and-restore',
+ 'qoder.routing.additional-plans',
+ 'qoder.routing.adjust-and-restore',
+ 'qoder.routing.resume-pending',
+ 'agent.diagnostics.configuration-state',
+ 'codex.routing.unproven-native-model'];
+
+export const routingWorkerRequired = ['routing.capabilities.candidate-vs-fixed',
+ 'worker.discovery.visible-only',
+ 'worker.installation.harness-isolation',
+ 'worker.installation.replace',
+ 'worker.installation.latest-edit',
+ 'qoder.installation.single-cli',
+ 'routing.save.unobserved-editable',
+ 'routing.publish.qoder-budget-conflict'];
+
+export const focusedRequirements = {
+ 'claude-collaboration': ['claude.collaboration.check-before-save', 'claude.collaboration.retry-preserves-edit', 'claude.collaboration.obsolete-blocker'],
+ 'worker-replacement': ['worker.installation.replace', 'worker.installation.latest-edit'],
+ 'qoder': ['qoder.collaboration.enable-without-model', 'qoder.collaboration.retry-and-restore', 'qoder.routing.additional-plans', 'qoder.routing.adjust-and-restore', 'agent.configuration.shared-interactions', 'qoder.routing.resume-pending', 'qoder.installation.single-cli', 'routing.publish.qoder-budget-conflict', 'desktop.routing.qoder-budget-checkpoint'],
+ 'route-save': ['routing.save.unobserved-editable', 'routing.publish.qoder-budget-conflict'],
+};
+
+export const productShellRequired = [
+ 'desktop.settings.persisted-scale',
+ 'desktop.operation.dismiss-observes',
+ 'desktop.operation.identity-retry-converges',
+ 'desktop.operation.repeated-submission',
+ 'desktop.models.documentation-retains-input',
+ 'desktop.routing.reactivation-models',
+ 'desktop.routing.qoder-budget-checkpoint',
+ 'desktop.routing.classifier-protocol',
+];
diff --git a/apps/desktop/tests/v3/browser/scenario-selection.mjs b/apps/desktop/tests/v3/browser/scenario-selection.mjs
new file mode 100644
index 00000000..033e79ca
--- /dev/null
+++ b/apps/desktop/tests/v3/browser/scenario-selection.mjs
@@ -0,0 +1,62 @@
+// Stable IDs select user capabilities; display names are report copy only.
+export function scenario(id, capabilities, name, run) {
+ return { id, capabilities, name, run };
+}
+
+export function scenarioCatalog(scenarios) {
+ return scenarios.map(({ id, capabilities, name }) => ({ id, capabilities, name }));
+}
+
+export function selectScenarios(catalog, selection = {}) {
+ if (!selection || typeof selection !== 'object' || Array.isArray(selection)) throw new Error('Scenario selection must be an options object');
+ const { ids, capability, requiredIds = [] } = selection;
+ if (!Array.isArray(requiredIds) || requiredIds.some(id => typeof id !== 'string' || !id)) throw new Error('Required scenario IDs must be a list of IDs');
+ if (capability !== undefined && (typeof capability !== 'string' || !capability)) throw new Error('Capability must be a nonempty string');
+ if (!Array.isArray(catalog) || catalog.length === 0) throw new Error('Scenario catalog is empty');
+ if (ids !== undefined && (!Array.isArray(ids) || ids.length === 0 || new Set(ids).size !== ids.length)) {
+ throw new Error('Scenario IDs must be a nonempty unique list');
+ }
+ const byId = new Map();
+ for (const item of catalog) {
+ if (!item || typeof item.id !== 'string' || !/^[a-z][a-z0-9.-]+$/.test(item.id) || byId.has(item.id)
+ || typeof item.name !== 'string' || !item.name.trim()
+ || !Array.isArray(item.capabilities) || item.capabilities.length === 0
+ || item.capabilities.some(value => typeof value !== 'string' || !value)) {
+ throw new Error(`Invalid or duplicate scenario: ${item?.id}`);
+ }
+ byId.set(item.id, item);
+ }
+ for (const id of [...(ids ?? []), ...requiredIds]) {
+ if (!byId.has(id)) throw new Error(`Required scenario is missing: ${id}`);
+ }
+ const selected = catalog.filter(item => (!ids || ids.includes(item.id))
+ && (!capability || item.capabilities.includes(capability)));
+ if (selected.length === 0) throw new Error('No scenarios selected');
+ for (const id of requiredIds) {
+ if (!selected.some(item => item.id === id)) throw new Error(`Required scenario was not selected: ${id}`);
+ }
+ return selected;
+}
+
+export function assertScenarioResults(selected, results) {
+ if (!Array.isArray(results) || results.length !== selected.length) throw new Error('Not all selected scenarios executed');
+ const expected = new Set(selected.map(item => item.id));
+ const seen = new Set();
+ for (const result of results) {
+ if (!expected.has(result.id) || seen.has(result.id) || !['green', 'red'].includes(result.state)) {
+ throw new Error(`Unexpected, duplicate or unexecuted scenario result: ${result.id}`);
+ }
+ seen.add(result.id);
+ }
+}
+
+export async function runScenarios(scenarios, selection) {
+ const selected = selectScenarios(scenarios, selection);
+ const results = [];
+ for (const { id, capabilities, name, run } of selected) {
+ try { await run(); results.push({ id, capabilities, name, state: 'green' }); }
+ catch (error) { results.push({ id, capabilities, name, state: 'red', error: error instanceof Error ? error.message : String(error) }); }
+ }
+ assertScenarioResults(selected, results);
+ return { evidence: 'React components + mock IPC only; not native/Tauri and not the real daemon', tests: results.length, passed: results.filter(item => item.state === 'green').length, failed: results.filter(item => item.state === 'red').length, results };
+}
diff --git a/apps/desktop/tests/v3/visual/agent-trust-active.mjs b/apps/desktop/tests/v3/visual/agent-trust-active.mjs
index 6778de2e..a945d940 100644
--- a/apps/desktop/tests/v3/visual/agent-trust-active.mjs
+++ b/apps/desktop/tests/v3/visual/agent-trust-active.mjs
@@ -1,10 +1,13 @@
import { mkdir, writeFile } from 'node:fs/promises';
import path from 'node:path';
+import { selectScenarios, assertScenarioResults } from '../browser/scenario-selection.mjs';
+import { agentTrustRequired, routingWorkerRequired, productShellRequired, focusedRequirements } from '../browser/scenario-requirements.mjs';
import { connectPage, evaluate, navigate, waitFor } from './cdp-client.mjs';
const port = Number(process.argv[2]);
const baseUrl = process.argv[3];
const outputRoot = path.resolve(process.argv[4]);
+const shellOnly = process.argv[5] === '--shell-only';
const routeSaveOnly = process.argv[5] === '--route-save-only';
const workerReplacementOnly = process.argv[5] === '--worker-replacement-only';
const claudeCollaborationOnly = process.argv[5] === '--claude-collaboration-only';
@@ -17,47 +20,66 @@ try {
const client = await connectPage(port);
try {
const checks = [];
- if (!routeSaveOnly && !workerReplacementOnly) {
+ if (!shellOnly && !routeSaveOnly && !workerReplacementOnly) {
await navigate(client, new URL('agent-trust.html', baseUrl).href, { width: 1280, height: 900 });
await waitFor(client, 'Boolean(window.agentTrust)', { timeout: 7000 });
- const names = await evaluate(client, "import('/agent-trust-scenarios.mjs').then(module => module.agentTrustScenarioNames)");
- if (!Array.isArray(names) || names.length === 0) throw new Error('Agent trust scenarios are missing');
- const batches = claudeCollaborationOnly
- ? names.flatMap((name, index) => name.startsWith('Claude collaboration') || name.startsWith('an unrelated Agent preview failure') ? [[index, index + 1]] : [])
- : Array.from({ length: Math.ceil(names.length / 5) }, (_, index) => [index * 5, Math.min((index + 1) * 5, names.length)]);
- if (claudeCollaborationOnly && batches.length !== 3) throw new Error('Required Claude collaboration scenarios are missing');
- const firstCheck = checks.length;
- for (const [start, end] of batches) {
- const batch = await evaluate(client, `import('/agent-trust-scenarios.mjs').then(module => module.runAgentTrustScenarios(${start}, ${end}))`);
- checks.push(...batch.results);
+ const catalog = await evaluate(client, "import('/agent-trust-scenarios.mjs').then(module => module.agentTrustScenarioCatalog)");
+ const selected = selectScenarios(catalog, claudeCollaborationOnly
+ ? { capability: 'claude-collaboration', requiredIds: focusedRequirements['claude-collaboration'] }
+ : { requiredIds: agentTrustRequired });
+ const results = [];
+ for (let offset = 0; offset < selected.length; offset += 5) {
+ const ids = selected.slice(offset, offset + 5).map(item => item.id);
+ const batch = await evaluate(client, `import('/agent-trust-scenarios.mjs').then(module => module.runAgentTrustScenarios(${JSON.stringify({ ids, requiredIds: ids })}))`);
+ results.push(...batch.results);
for (const item of batch.results) {
- process.stdout.write(`${item.state === 'green' ? 'green' : 'red'}: ${item.name}${item.error ? ` · ${item.error}` : ''}\n`);
+ process.stdout.write(`${item.state === 'green' ? 'green' : 'red'}: ${item.id} · ${item.name}${item.error ? ` · ${item.error}` : ''}\n`);
}
}
- if (checks.length - firstCheck !== (claudeCollaborationOnly ? 3 : names.length)) throw new Error('Agent trust scenarios were not all executed');
+ assertScenarioResults(selected, results);
+ checks.push(...results);
}
- if (!claudeCollaborationOnly) {
+ if (!shellOnly && !claudeCollaborationOnly) {
await navigate(client, new URL('?page=routing&scenario=ready', baseUrl).href, { width: 1280, height: 900 });
await waitFor(client, 'Boolean(window.__HIRouteFixtureTrace)', { timeout: 7000 });
- const routing = await evaluate(client, routeSaveOnly
- ? "import('/routing-worker-scenarios.mjs').then(module => module.runRoutingWorkerScenarios(5, 6))"
- : workerReplacementOnly
- ? "import('/routing-worker-scenarios.mjs').then(module => module.runRoutingWorkerScenarios(3, 5))"
- : "import('/routing-worker-scenarios.mjs').then(module => module.runRoutingWorkerScenarios())");
+ const catalog = await evaluate(client, "import('/routing-worker-scenarios.mjs').then(module => module.routingWorkerScenarioCatalog)");
+ const capability = routeSaveOnly ? 'route-save' : workerReplacementOnly ? 'worker-replacement' : undefined;
+ const selection = { capability, requiredIds: capability ? focusedRequirements[capability] : routingWorkerRequired };
+ const selected = selectScenarios(catalog, selection);
+ const routing = await evaluate(client, `import('/routing-worker-scenarios.mjs').then(module => module.runRoutingWorkerScenarios(${JSON.stringify(selection)}))`);
+ assertScenarioResults(selected, routing.results);
checks.push(...routing.results);
for (const item of routing.results) {
process.stdout.write(`${item.state === 'green' ? 'green' : 'red'}: ${item.name}${item.error ? ` · ${item.error}` : ''}\n`);
}
}
- if (!routeSaveOnly && !workerReplacementOnly && !claudeCollaborationOnly) {
+ if (!shellOnly && !routeSaveOnly && !workerReplacementOnly && !claudeCollaborationOnly) {
await navigate(client, new URL('?page=models&scenario=ready', baseUrl).href, { width: 1280, height: 900 });
await waitFor(client, 'Boolean(window.__HIRouteFixtureTrace)', { timeout: 7000 });
const fromModel = await evaluate(client, "import('/model-to-route-scenarios.mjs').then(module => module.runModelToRouteScenarios())");
+ if (fromModel.tests !== 1 || fromModel.results?.length !== 1 || !['green', 'red'].includes(fromModel.results[0].state)) {
+ throw new Error('Required model-to-route scenario did not execute');
+ }
checks.push(...fromModel.results);
for (const item of fromModel.results) {
process.stdout.write(`${item.state === 'green' ? 'green' : 'red'}: ${item.name}${item.error ? ` · ${item.error}` : ''}\n`);
}
}
+ if (shellOnly || (!routeSaveOnly && !workerReplacementOnly && !claudeCollaborationOnly)) {
+ await navigate(client, new URL('product-shell.html', baseUrl).href, { width: 1280, height: 900 });
+ await waitFor(client, 'Boolean(window.productShell)', { timeout: 7000 });
+ const catalog = await evaluate(client, "import('/product-shell-scenarios.mjs').then(module => module.productShellScenarioCatalog)");
+ const selected = selectScenarios(catalog, { requiredIds: productShellRequired });
+ const results = [];
+ for (const { id } of selected) {
+ const batch = await evaluate(client, `import('/product-shell-scenarios.mjs').then(module => module.runProductShellScenarios(${JSON.stringify({ ids: [id], requiredIds: [id] })}))`);
+ results.push(...batch.results);
+ for (const item of batch.results) process.stdout.write(`${item.state}: ${item.id} · ${item.name}${item.error ? ` · ${item.error}` : ''}\n`);
+ }
+ assertScenarioResults(selected, results);
+ checks.push(...results);
+ }
+ if (checks.length === 0) throw new Error('No scenarios executed');
const report = {
generatedAt: new Date().toISOString(),
evidence: 'React components + mock IPC only; not native/Tauri and not the real daemon',
diff --git a/apps/desktop/tests/v3/visual/agent-trust.mjs b/apps/desktop/tests/v3/visual/agent-trust.mjs
index a18a2e34..f06cf6dd 100644
--- a/apps/desktop/tests/v3/visual/agent-trust.mjs
+++ b/apps/desktop/tests/v3/visual/agent-trust.mjs
@@ -8,6 +8,8 @@ import { fileURLToPath } from 'node:url';
const here = path.dirname(fileURLToPath(import.meta.url));
const desktopRoot = path.resolve(here, '../../..');
const outputRoot = path.resolve(process.argv[2] ?? path.join(desktopRoot, 'test-results/v3-agent-trust'));
+const shellOnly = process.argv[3] === '--shell-only';
+if (process.argv[3] && !['--shell-only', '--route-save-only', '--worker-replacement-only', '--claude-collaboration-only'].includes(process.argv[3])) throw new Error(`Unknown scenario selection: ${process.argv[3]}`);
const routeSaveOnly = process.argv[3] === '--route-save-only';
const workerReplacementOnly = process.argv[3] === '--worker-replacement-only';
const claudeCollaborationOnly = process.argv[3] === '--claude-collaboration-only';
@@ -59,11 +61,18 @@ let vite;
let chrome;
try {
vite = spawn(path.join(desktopRoot, 'node_modules/.bin/vite'), ['tests/v3/browser', '--host', '127.0.0.1', '--port', String(httpPort), '--strictPort'], { cwd: desktopRoot, detached: true, stdio: ['ignore', 'pipe', 'pipe'] });
+ vite.stdout.resume();
+ vite.stderr.on('data', data => process.stderr.write(data));
await waitFor(`http://127.0.0.1:${httpPort}/`);
const chromeExecutable = process.env.CHROME_BIN || (process.platform === 'darwin' ? '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome' : 'google-chrome');
chrome = spawn(chromeExecutable, ['--headless=new', '--disable-gpu', `--remote-debugging-port=${cdpPort}`, '--remote-allow-origins=*', `--user-data-dir=${profile}`, '--window-size=1280,900', 'about:blank'], { detached: true, stdio: ['ignore', 'pipe', 'pipe'] });
- await waitFor(`http://127.0.0.1:${cdpPort}/json/version`);
- const runner = spawn(process.execPath, [path.join(here, 'agent-trust-active.mjs'), String(cdpPort), `http://127.0.0.1:${httpPort}/`, outputRoot, ...(routeSaveOnly ? ['--route-save-only'] : workerReplacementOnly ? ['--worker-replacement-only'] : claudeCollaborationOnly ? ['--claude-collaboration-only'] : [])], { cwd: desktopRoot, stdio: 'inherit' });
+ chrome.stdout.resume();
+ // Drain the diagnostic pipe: repeated platform warnings can otherwise block Chrome.
+ let chromeErrors = '';
+ chrome.stderr.on('data', data => { chromeErrors = (chromeErrors + data).slice(-8000); });
+ try { await waitFor(`http://127.0.0.1:${cdpPort}/json/version`); }
+ catch (error) { throw new Error(`${error.message}\n${chromeErrors}`); }
+ const runner = spawn(process.execPath, [path.join(here, 'agent-trust-active.mjs'), String(cdpPort), `http://127.0.0.1:${httpPort}/`, outputRoot, ...(shellOnly ? ['--shell-only'] : routeSaveOnly ? ['--route-save-only'] : workerReplacementOnly ? ['--worker-replacement-only'] : claudeCollaborationOnly ? ['--claude-collaboration-only'] : [])], { cwd: desktopRoot, stdio: 'inherit' });
const outcome = await waitForExit(runner);
if (outcome.code !== 0) process.exitCode = outcome.code ?? 1;
} finally {
diff --git a/apps/desktop/tests/worker-dependencies-state.test.mjs b/apps/desktop/tests/worker-dependencies-state.test.mjs
index 0dc93292..e389d959 100644
--- a/apps/desktop/tests/worker-dependencies-state.test.mjs
+++ b/apps/desktop/tests/worker-dependencies-state.test.mjs
@@ -2,6 +2,8 @@ import assert from 'node:assert/strict';
import test from 'node:test';
import {
recommendedWorkerDependencies,
+ workerDependencyComponents,
+ workerDependencySelectionComplete,
workerDependencySelectionMatches,
workerDependencySelectionState,
workerEnvelopeData,
@@ -35,6 +37,59 @@ test('detection recommends but never invents a persisted selection', () => {
assert.deepEqual(detected.selected, []);
});
+test('Qoder recommends and recognizes a saved native CLI without adapter or Node fields', () => {
+ const selected = { harness: 'qoder_cli', cli_path: '/bin/qodercli' };
+ const detected = view({
+ selection_revisions: [{ harness: 'qoder_cli', revision: 7 }],
+ candidates: [
+ ...view().candidates,
+ { harness: 'qoder_cli', component: 'cli', path: '/bin/qodercli', source: 'path', state: 'found' },
+ ],
+ });
+ const request = recommendedWorkerDependencies(detected, 'qoder_cli');
+ assert.deepEqual(request, { ...selected, expected_selection_revision: 7 });
+ assert.deepEqual(workerDependencyComponents('qoder_cli'), ['cli']);
+ assert.equal(workerDependencySelectionComplete(request), true);
+ assert.equal(workerDependencySelectionState(detected, 'qoder_cli'), 'found');
+ assert.deepEqual(detected.selected, []);
+ const saved = { ...detected, selected: [selected] };
+ assert.deepEqual(recommendedWorkerDependencies(saved, 'qoder_cli'), request);
+ assert.equal(workerDependencySelectionMatches(saved, request), true);
+ assert.equal(workerDependencySelectionState(saved, 'qoder_cli'), 'configured');
+});
+
+test('a missing selected Qoder CLI stays incomplete and does not fall back to a discovered installation', () => {
+ const selected = { harness: 'qoder_cli', cli_path: '/old/qoder' };
+ const detected = view({
+ selection_revisions: [{ harness: 'qoder_cli', revision: 7 }],
+ selected: [selected],
+ candidates: [
+ { harness: 'qoder_cli', component: 'cli', path: '/old/qoder', source: 'selected', state: 'missing' },
+ { harness: 'qoder_cli', component: 'cli', path: '/bin/qodercli', source: 'path', state: 'found' },
+ ],
+ });
+ assert.deepEqual(recommendedWorkerDependencies(detected, 'qoder_cli'), {
+ ...selected, expected_selection_revision: 7,
+ });
+ assert.equal(workerDependencySelectionState(detected, 'qoder_cli'), 'incomplete');
+ assert.equal(workerDependencySelectionMatches(detected, {
+ harness: 'qoder_cli', cli_path: '/bin/qodercli', expected_selection_revision: 7,
+ }), false);
+});
+
+test('a CLI alone remains incomplete for Codex and Claude adapter installations', () => {
+ for (const harness of ['codex_cli', 'claude_code']) {
+ const cliOnly = { harness, cli_path: `/bin/${harness}` };
+ const detected = view({
+ selection_revisions: [{ harness, revision: 0 }],
+ candidates: [{ harness, component: 'cli', path: cliOnly.cli_path, source: 'path', state: 'found' }],
+ });
+ assert.equal(workerDependencySelectionComplete(cliOnly), false);
+ assert.equal(workerDependencySelectionState(detected, harness), 'incomplete');
+ assert.equal(workerDependencySelectionState({ ...detected, selected: [cliOnly] }, harness), 'incomplete');
+ }
+});
+
test('an explicit selected path remains authoritative even when another candidate is found', () => {
const selected = {
harness: 'codex_cli',
diff --git a/apps/desktop/tsconfig.json b/apps/desktop/tsconfig.json
index 4f58b853..4c5ea7ae 100644
--- a/apps/desktop/tsconfig.json
+++ b/apps/desktop/tsconfig.json
@@ -1 +1 @@
-{"compilerOptions":{"target":"ES2022","lib":["ES2022","DOM"],"module":"ESNext","moduleResolution":"bundler","jsx":"react-jsx","strict":true,"noEmit":true,"skipLibCheck":true},"include":["src"]}
+{"compilerOptions":{"target":"ES2022","lib":["ES2022","DOM"],"module":"ESNext","moduleResolution":"bundler","jsx":"react-jsx","strict":true,"noEmit":true,"allowImportingTsExtensions":true,"skipLibCheck":true},"include":["src"]}
diff --git a/apps/website/src/lib/decision-docs.mjs b/apps/website/src/lib/decision-docs.mjs
index 76e4050d..58f81ab4 100644
--- a/apps/website/src/lib/decision-docs.mjs
+++ b/apps/website/src/lib/decision-docs.mjs
@@ -12,6 +12,7 @@ const sources = {
};
const route = (language, page) => `${language === 'en' ? '/en' : ''}/docs/${page}/`;
+const sourceLink = file => `https://github.com/higress-group/HiRoute/blob/main/${file}`;
const maps = {
mechanism: {
'README.md': '/en/docs/decision-extensions/', 'README.zh-CN.md': '/docs/decision-extensions/',
@@ -25,6 +26,13 @@ const maps = {
'decision.openapi.json': '/api/decision.openapi.json',
},
jev: {
+ 'jev_decider/settings.py': sourceLink('decision-extensions/extensions/jev-decider/jev_decider/settings.py'),
+ 'jev_decider/protocol.py': sourceLink('decision-extensions/extensions/jev-decider/jev_decider/protocol.py'),
+ 'jev_decider/decision.py': sourceLink('decision-extensions/extensions/jev-decider/jev_decider/decision.py'),
+ 'jev_decider/server.py': sourceLink('decision-extensions/extensions/jev-decider/jev_decider/server.py'),
+ 'tests/README.md': sourceLink('decision-extensions/extensions/jev-decider/tests/README.md'),
+ '../../../docs/code-map/decision-foundation.md': sourceLink('docs/code-map/decision-foundation.md'),
+ '../../../crates/gateway/README.md': sourceLink('crates/gateway/README.md'),
'README.md': '/en/docs/jev-decider/', 'README.zh-CN.md': '/docs/jev-decider/',
'../../README.md': '/en/docs/decision-extensions/', '../../README.zh-CN.md': '/docs/decision-extensions/',
'../../api/README.md': '/en/docs/decision-api/', '../../api/README.zh-CN.md': '/docs/decision-api/',
@@ -39,9 +47,10 @@ function rewriteTarget(target, page, language) {
|| target === '../../docs/smart-saving-model-classification.zh-CN.md') {
return route(language, 'model-routing');
}
- const mapped = maps[page][target];
+ const [file, fragment] = target.split('#', 2);
+ const mapped = maps[page][file];
if (!mapped) throw new Error(`unmapped relative decision-document link in ${page}: ${target}`);
- return mapped;
+ return mapped + (fragment === undefined ? '' : `#${fragment}`);
}
export async function renderDecisionDoc(page, language) {
diff --git a/apps/website/tests/decision-docs.test.mjs b/apps/website/tests/decision-docs.test.mjs
index e09eecf3..217ecdd2 100644
--- a/apps/website/tests/decision-docs.test.mjs
+++ b/apps/website/tests/decision-docs.test.mjs
@@ -19,7 +19,15 @@ test('canonical decision documents render into bilingual website routes', async
assert.match(zh, /href="#illustration-evidence-boundaries"/);
assert.match(zh, /id="illustration-evidence-boundaries"/);
assert.match(rendered.find(html => html.includes('Illustration evidence boundaries')), /id="illustration-evidence-boundaries"/);
- assert.doesNotMatch(rendered.join(''), /href="[^" ]+\.md"/);
+ assert.doesNotMatch(rendered.join(''), /href="(?!https:\/\/)[^" ]+\.md(?:#[^"]*)?"/);
+ for (const html of rendered.slice(4)) {
+ for (const file of ['settings', 'protocol', 'decision', 'server']) {
+ assert.ok(html.includes(`href="https://github.com/higress-group/HiRoute/blob/main/decision-extensions/extensions/jev-decider/jev_decider/${file}.py"`));
+ }
+ assert.ok(html.includes('https://github.com/higress-group/HiRoute/blob/main/decision-extensions/extensions/jev-decider/tests/README.md'));
+ }
+ assert.match(rendered[4], /href="\/en\/docs\/jev-decider\/#code-and-responsibility-map"/);
+ assert.ok(rendered[5].includes('https://github.com/higress-group/HiRoute/blob/main/docs/code-map/decision-foundation.md'));
});
test('prepared OpenAPI is byte-identical to the one repository contract', () => {
diff --git a/assets/agent-profiles/current/profile-seed.json b/assets/agent-profiles/current/profile-seed.json
index dda6b740..9c2b344f 100644
--- a/assets/agent-profiles/current/profile-seed.json
+++ b/assets/agent-profiles/current/profile-seed.json
@@ -1 +1 @@
-{"schema":"hiroute.agent-profiles-artifact/v1","tool_version":"hiroute-release-facts/1","profiles":[{"schema":"hiroute.agent-profile/v1","profile_id":"claude-messages-v1","integration_profile_ref":"builtin/claude-messages/v1","kind":"claude_code","ingress_protocol":"messages","config_precedence":["managed","process","launch","project","user"],"owned_config_fields":[{"field_id":"base_endpoint","path":"env.ANTHROPIC_BASE_URL","write_layer":"user"},{"field_id":"default_model","path":"env.ANTHROPIC_MODEL","write_layer":"user"},{"field_id":"default_opus_model","path":"env.ANTHROPIC_DEFAULT_OPUS_MODEL","write_layer":"user"},{"field_id":"default_sonnet_model","path":"env.ANTHROPIC_DEFAULT_SONNET_MODEL","write_layer":"user"},{"field_id":"default_haiku_model","path":"env.ANTHROPIC_DEFAULT_HAIKU_MODEL","write_layer":"user"},{"field_id":"small_fast_model","path":"env.ANTHROPIC_SMALL_FAST_MODEL","write_layer":"user"},{"field_id":"auth_helper","path":"apiKeyHelper","write_layer":"user"},{"field_id":"auth_environment","path":"hiroute.auth_environment","write_layer":"user"}],"dynamic_catalog":false,"static_catalog_fallback":false,"native_subagent_routing":false,"managed_launch":{"settings_argument":"--settings","environment_removals":["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_BASE_URL","ANTHROPIC_CUSTOM_HEADERS","ANTHROPIC_MODEL","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_FOUNDRY","CLAUDE_CODE_USE_VERTEX"],"caller_forbidden_options":["--anthropic-api-key","--anthropic-auth-token","--api-key","--api-key-helper","--auth-token","--base-url","--bedrock","--custom-headers","--foundry","--provider","--use-bedrock","--use-foundry","--use-vertex","--vertex"]}},{"schema":"hiroute.agent-profile/v1","profile_id":"codex-responses-v1","integration_profile_ref":"builtin/codex-responses/v1","kind":"codex","ingress_protocol":"responses","config_precedence":["process","launch","project","user","managed"],"owned_config_fields":[{"field_id":"provider","path":"model_provider","write_layer":"user"},{"field_id":"default_model","path":"model","write_layer":"user"},{"field_id":"base_endpoint","path":"model_providers.hiroute.base_url","write_layer":"user"},{"field_id":"wire_api","path":"model_providers.hiroute.wire_api","write_layer":"user"},{"field_id":"static_catalog","path":"model_catalog_json","write_layer":"user"}],"dynamic_catalog":true,"static_catalog_fallback":true,"native_subagent_routing":true,"spawn_guidance":{"tool_name":"spawn_agent","registration_id":"codex.builtin.spawn-agent.v1","begin_marker":"Available model overrides (optional; inherited parent model is preferred):","end_marker":"Spawn arguments:","expected_shape_digest":"sha256:e6fa92a60065816802f1048589e335a116799757bb16a27346b4c18756df8fde"}}]}
+{"schema":"hiroute.agent-profiles-artifact/v1","tool_version":"hiroute-release-facts/1","profiles":[{"schema":"hiroute.agent-profile/v1","profile_id":"claude-messages-v1","integration_profile_ref":"builtin/claude-messages/v1","kind":"claude_code","ingress_protocol":"messages","config_precedence":["managed","process","launch","project","user"],"owned_config_fields":[{"field_id":"base_endpoint","path":"env.ANTHROPIC_BASE_URL","write_layer":"user"},{"field_id":"default_model","path":"env.ANTHROPIC_MODEL","write_layer":"user"},{"field_id":"default_opus_model","path":"env.ANTHROPIC_DEFAULT_OPUS_MODEL","write_layer":"user"},{"field_id":"default_sonnet_model","path":"env.ANTHROPIC_DEFAULT_SONNET_MODEL","write_layer":"user"},{"field_id":"default_haiku_model","path":"env.ANTHROPIC_DEFAULT_HAIKU_MODEL","write_layer":"user"},{"field_id":"small_fast_model","path":"env.ANTHROPIC_SMALL_FAST_MODEL","write_layer":"user"},{"field_id":"auth_helper","path":"apiKeyHelper","write_layer":"user"},{"field_id":"auth_environment","path":"hiroute.auth_environment","write_layer":"user"}],"dynamic_catalog":false,"static_catalog_fallback":false,"native_subagent_routing":false,"managed_launch":{"settings_argument":"--settings","environment_removals":["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_BASE_URL","ANTHROPIC_CUSTOM_HEADERS","ANTHROPIC_MODEL","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_FOUNDRY","CLAUDE_CODE_USE_VERTEX"],"caller_forbidden_options":["--anthropic-api-key","--anthropic-auth-token","--api-key","--api-key-helper","--auth-token","--base-url","--bedrock","--custom-headers","--foundry","--provider","--use-bedrock","--use-foundry","--use-vertex","--vertex"]}},{"schema":"hiroute.agent-profile/v1","profile_id":"codex-responses-v1","integration_profile_ref":"builtin/codex-responses/v1","kind":"codex","ingress_protocol":"responses","config_precedence":["process","launch","project","user","managed"],"owned_config_fields":[{"field_id":"provider","path":"model_provider","write_layer":"user"},{"field_id":"default_model","path":"model","write_layer":"user"},{"field_id":"base_endpoint","path":"model_providers.hiroute.base_url","write_layer":"user"},{"field_id":"wire_api","path":"model_providers.hiroute.wire_api","write_layer":"user"},{"field_id":"static_catalog","path":"model_catalog_json","write_layer":"user"}],"dynamic_catalog":true,"static_catalog_fallback":true,"native_subagent_routing":true,"spawn_guidance":{"tool_name":"spawn_agent","registration_id":"codex.builtin.spawn-agent.v1","begin_marker":"Available model overrides (optional; inherited parent model is preferred):","end_marker":"Spawn arguments:","expected_shape_digest":"sha256:e6fa92a60065816802f1048589e335a116799757bb16a27346b4c18756df8fde"}},{"schema":"hiroute.agent-profile/v1","profile_id":"qoder-collaboration-v1","integration_profile_ref":"builtin/qoder-collaboration/v1","kind":"qoder","ingress_protocol":"responses","config_precedence":["process","local","project","user"],"owned_config_fields":[{"field_id":"additional_provider","path":"hiroute.additional_provider","write_layer":"user"}],"dynamic_catalog":false,"static_catalog_fallback":false,"native_subagent_routing":false}]}
diff --git a/assets/release-facts/current/bundle/agent-profiles.json b/assets/release-facts/current/bundle/agent-profiles.json
index c6aa6d12..56a58ecc 100644
--- a/assets/release-facts/current/bundle/agent-profiles.json
+++ b/assets/release-facts/current/bundle/agent-profiles.json
@@ -1 +1 @@
-{"schema":"hiroute.agent-profiles-artifact/v1","tool_version":"hiroute-release-facts/2","profiles":[{"schema":"hiroute.agent-profile/v1","profile_id":"claude-messages-v1","integration_profile_ref":"builtin/claude-messages/v1","kind":"claude_code","ingress_protocol":"messages","config_precedence":["managed","process","launch","project","user"],"owned_config_fields":[{"field_id":"base_endpoint","path":"env.ANTHROPIC_BASE_URL","write_layer":"user"},{"field_id":"default_model","path":"env.ANTHROPIC_MODEL","write_layer":"user"},{"field_id":"default_opus_model","path":"env.ANTHROPIC_DEFAULT_OPUS_MODEL","write_layer":"user"},{"field_id":"default_sonnet_model","path":"env.ANTHROPIC_DEFAULT_SONNET_MODEL","write_layer":"user"},{"field_id":"default_haiku_model","path":"env.ANTHROPIC_DEFAULT_HAIKU_MODEL","write_layer":"user"},{"field_id":"small_fast_model","path":"env.ANTHROPIC_SMALL_FAST_MODEL","write_layer":"user"},{"field_id":"auth_helper","path":"apiKeyHelper","write_layer":"user"},{"field_id":"auth_environment","path":"hiroute.auth_environment","write_layer":"user"}],"dynamic_catalog":false,"static_catalog_fallback":false,"native_subagent_routing":false,"managed_launch":{"settings_argument":"--settings","environment_removals":["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_BASE_URL","ANTHROPIC_CUSTOM_HEADERS","ANTHROPIC_MODEL","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_FOUNDRY","CLAUDE_CODE_USE_VERTEX"],"caller_forbidden_options":["--anthropic-api-key","--anthropic-auth-token","--api-key","--api-key-helper","--auth-token","--base-url","--bedrock","--custom-headers","--foundry","--provider","--use-bedrock","--use-foundry","--use-vertex","--vertex"]}},{"schema":"hiroute.agent-profile/v1","profile_id":"codex-responses-v1","integration_profile_ref":"builtin/codex-responses/v1","kind":"codex","ingress_protocol":"responses","config_precedence":["process","launch","project","user","managed"],"owned_config_fields":[{"field_id":"provider","path":"model_provider","write_layer":"user"},{"field_id":"default_model","path":"model","write_layer":"user"},{"field_id":"base_endpoint","path":"model_providers.hiroute.base_url","write_layer":"user"},{"field_id":"wire_api","path":"model_providers.hiroute.wire_api","write_layer":"user"},{"field_id":"static_catalog","path":"model_catalog_json","write_layer":"user"}],"dynamic_catalog":true,"static_catalog_fallback":true,"native_subagent_routing":true,"spawn_guidance":{"tool_name":"spawn_agent","registration_id":"codex.builtin.spawn-agent.v1","begin_marker":"Available model overrides (optional; inherited parent model is preferred):","end_marker":"Spawn arguments:","expected_shape_digest":"sha256:e6fa92a60065816802f1048589e335a116799757bb16a27346b4c18756df8fde"}}]}
+{"schema":"hiroute.agent-profiles-artifact/v1","tool_version":"hiroute-release-facts/2","profiles":[{"schema":"hiroute.agent-profile/v1","profile_id":"claude-messages-v1","integration_profile_ref":"builtin/claude-messages/v1","kind":"claude_code","ingress_protocol":"messages","config_precedence":["managed","process","launch","project","user"],"owned_config_fields":[{"field_id":"base_endpoint","path":"env.ANTHROPIC_BASE_URL","write_layer":"user"},{"field_id":"default_model","path":"env.ANTHROPIC_MODEL","write_layer":"user"},{"field_id":"default_opus_model","path":"env.ANTHROPIC_DEFAULT_OPUS_MODEL","write_layer":"user"},{"field_id":"default_sonnet_model","path":"env.ANTHROPIC_DEFAULT_SONNET_MODEL","write_layer":"user"},{"field_id":"default_haiku_model","path":"env.ANTHROPIC_DEFAULT_HAIKU_MODEL","write_layer":"user"},{"field_id":"small_fast_model","path":"env.ANTHROPIC_SMALL_FAST_MODEL","write_layer":"user"},{"field_id":"auth_helper","path":"apiKeyHelper","write_layer":"user"},{"field_id":"auth_environment","path":"hiroute.auth_environment","write_layer":"user"}],"dynamic_catalog":false,"static_catalog_fallback":false,"native_subagent_routing":false,"managed_launch":{"settings_argument":"--settings","environment_removals":["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_BASE_URL","ANTHROPIC_CUSTOM_HEADERS","ANTHROPIC_MODEL","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_FOUNDRY","CLAUDE_CODE_USE_VERTEX"],"caller_forbidden_options":["--anthropic-api-key","--anthropic-auth-token","--api-key","--api-key-helper","--auth-token","--base-url","--bedrock","--custom-headers","--foundry","--provider","--use-bedrock","--use-foundry","--use-vertex","--vertex"]}},{"schema":"hiroute.agent-profile/v1","profile_id":"codex-responses-v1","integration_profile_ref":"builtin/codex-responses/v1","kind":"codex","ingress_protocol":"responses","config_precedence":["process","launch","project","user","managed"],"owned_config_fields":[{"field_id":"provider","path":"model_provider","write_layer":"user"},{"field_id":"default_model","path":"model","write_layer":"user"},{"field_id":"base_endpoint","path":"model_providers.hiroute.base_url","write_layer":"user"},{"field_id":"wire_api","path":"model_providers.hiroute.wire_api","write_layer":"user"},{"field_id":"static_catalog","path":"model_catalog_json","write_layer":"user"}],"dynamic_catalog":true,"static_catalog_fallback":true,"native_subagent_routing":true,"spawn_guidance":{"tool_name":"spawn_agent","registration_id":"codex.builtin.spawn-agent.v1","begin_marker":"Available model overrides (optional; inherited parent model is preferred):","end_marker":"Spawn arguments:","expected_shape_digest":"sha256:e6fa92a60065816802f1048589e335a116799757bb16a27346b4c18756df8fde"}},{"schema":"hiroute.agent-profile/v1","profile_id":"qoder-collaboration-v1","integration_profile_ref":"builtin/qoder-collaboration/v1","kind":"qoder","ingress_protocol":"responses","config_precedence":["process","local","project","user"],"owned_config_fields":[{"field_id":"additional_provider","path":"hiroute.additional_provider","write_layer":"user"}],"dynamic_catalog":false,"static_catalog_fallback":false,"native_subagent_routing":false}]}
diff --git a/contracts/cli/agent-plan-catalog-query.v2.schema.json b/contracts/cli/agent-plan-catalog-query.v2.schema.json
index 683f1b39..3cddc4fb 100644
--- a/contracts/cli/agent-plan-catalog-query.v2.schema.json
+++ b/contracts/cli/agent-plan-catalog-query.v2.schema.json
@@ -440,7 +440,8 @@
"harness": {
"enum": [
"codex_cli",
- "claude_code"
+ "claude_code",
+ "qoder_cli"
]
},
"protocol": {
diff --git a/contracts/cli/contract-set.v1.json b/contracts/cli/contract-set.v1.json
index 8200cc0a..46d419f9 100644
--- a/contracts/cli/contract-set.v1.json
+++ b/contracts/cli/contract-set.v1.json
@@ -3,7 +3,7 @@
"files": {
"agent-check-request.v1.schema.json": "sha256:fbd9e9b19282a5ed8c3e30b5ae16538bc01318a70e4bb7c7a55e8e0472553feb",
"agent-launch-descriptor-request.v1.schema.json": "sha256:28f2f9d2d7f9a1618bea0f13383002429bc9e0ff56166cbee86958a245d0fd48",
- "agent-plan-catalog-query.v2.schema.json": "sha256:a7d4fc190b4e7ee8d12d0fe52f1cb020ae05777cd513d5f163449d7f12598f22",
+ "agent-plan-catalog-query.v2.schema.json": "sha256:2341c620bb43c9738ff1d639fa7057ecd301ee2799584ac35b1662137fc92754",
"coverage-manifest.v1.json": "sha256:76d8776f13d953fd0b1c0387ba877c30fba7ecf564d927d131cb7e76b3f5a822",
"delegation-cancel-request.v1.schema.json": "sha256:0822c53fc16acfcd618fbef66410939f33f634313389a6df4705f414a468b878",
"delegation-continue-request.v1.schema.json": "sha256:da2f81607f37d154a0fa698a107b37d4b0e9d5a03693dcbcc41e0b7e65db5b93",
@@ -19,10 +19,10 @@
"manifest.v1.json": "sha256:c602e9b661621403bc05405674f5522604be0e716a886673776199492f686f75",
"operation-cancel-request.v1.schema.json": "sha256:0071cbcf27de3bfb7f6644478fe2b73bb5387ebe33db93629ff5672959e8495f",
"operation-lookup.v1.schema.json": "sha256:0fbaaa15b0e75b4186979bdd856bed0485d55a4bd33a33f3caf3bd92e01a7850",
- "plan-content-change.v2.schema.json": "sha256:ebc3aa699171bdfab5b4d0e28f6dfd152f14580c46ecc14137a7ed1fda41b416",
- "plan-draft-change.v1.schema.json": "sha256:ce90a62a41e7fcaa63fd02b314e482631c30ee2428ac7078bf3b25b0e5d7f42b",
- "plan-editor.v2.schema.json": "sha256:649ae95a7a58f4efcd6de37753f908f11bf63b83a666ee416c7843f13b3785e7",
- "plan-lifecycle-change.v1.schema.json": "sha256:111f40b630574dd71d7a201adbf542e770dcc26e0e36f2152ff94828549f83f3",
+ "plan-content-change.v2.schema.json": "sha256:d74a6e9af374cf7d505afc1e9f1d15b47e2bc42f841030f347120407a1c33d39",
+ "plan-draft-change.v1.schema.json": "sha256:780afb152b88f0e17a3b1acce955d3b2329fbc385b56575c50b594a023485ca5",
+ "plan-editor.v2.schema.json": "sha256:9083d469b1fdb957dd176cdf48e4acd63e9a74938366d4890fb618e2c03726de",
+ "plan-lifecycle-change.v1.schema.json": "sha256:eb54a14f53f0e0a15463be1053b9b8f2f349b643ac9c9037cf879cfda26d05b5",
"planned-manifest.v1.json": "sha256:eac0c7583245a881de141f9b8d853a86efb3f9ef8fa9a3ffb3ed75d759467072",
"session-list-query.v1.schema.json": "sha256:1f71a89fc019b59c3499708c0760b694b8cb8532028b56d98702cd3b2721cd44",
"session-lookup.v1.schema.json": "sha256:0c9e0ea31bdde7f720a9a17e8dc175902a20b3fb92abc21ce4bdae9fc3d97587",
@@ -32,8 +32,8 @@
"work-plan-list-request.v1.schema.json": "sha256:d50adc8e139cbed719fcec6412c796a7cf4d4f280dd7a56c525619f72c26c58d",
"worker-cancel-request.v1.schema.json": "sha256:f731e6a6be762d409a53afe9697be105d0debb89fe5e28be96b15ae03b31dfdc",
"worker-continue-request.v1.schema.json": "sha256:cfe89487d3524061dd277a97b11291fcd0db4a0a0ca333118023628ab7d61b3b",
- "worker-dependencies-discover-request.v1.schema.json": "sha256:cde9509210a2a2605fc95ed19d9c4a3aa754241dd49e6522124f77236dac44e4",
- "worker-dependencies-select-request.v1.schema.json": "sha256:d6a0454d125ea368f6b205fe7f360b14963fdd6fc94080bc2e19daf2aef6b972",
+ "worker-dependencies-discover-request.v1.schema.json": "sha256:0f164b8dddc097c0f5e88e8fcfa38dba4e6702b018413b55673da7d9a0606a0a",
+ "worker-dependencies-select-request.v1.schema.json": "sha256:6e3e231fe506812128c73a18752699d7e5869fba80d92bdc187b003daa67f55c",
"worker-exec-request.v1.schema.json": "sha256:78bfea83b08e595ad4d4b5a5a20884ad9ebb34bb05e5ceed966f9e8e16f4d0fa",
"worker-list-request.v1.schema.json": "sha256:f1a2b5900b0412d8d561a5925a6f9489b495e74c41f386a3504175b2be3aff64",
"worker-plans-request.v1.schema.json": "sha256:a7f2d13869ab542223bf51eef4f0c1a05a4c8afef43f202165fd3025a2ab72c1",
diff --git a/contracts/cli/plan-content-change.v2.schema.json b/contracts/cli/plan-content-change.v2.schema.json
index cc3b0e7c..f680eede 100644
--- a/contracts/cli/plan-content-change.v2.schema.json
+++ b/contracts/cli/plan-content-change.v2.schema.json
@@ -440,7 +440,8 @@
"harness": {
"enum": [
"codex_cli",
- "claude_code"
+ "claude_code",
+ "qoder_cli"
]
},
"protocol": {
diff --git a/contracts/cli/plan-draft-change.v1.schema.json b/contracts/cli/plan-draft-change.v1.schema.json
index 90e476b6..4f638e0b 100644
--- a/contracts/cli/plan-draft-change.v1.schema.json
+++ b/contracts/cli/plan-draft-change.v1.schema.json
@@ -440,7 +440,8 @@
"harness": {
"enum": [
"codex_cli",
- "claude_code"
+ "claude_code",
+ "qoder_cli"
]
},
"protocol": {
diff --git a/contracts/cli/plan-editor.v2.schema.json b/contracts/cli/plan-editor.v2.schema.json
index 8d19a830..aa2b7799 100644
--- a/contracts/cli/plan-editor.v2.schema.json
+++ b/contracts/cli/plan-editor.v2.schema.json
@@ -440,7 +440,8 @@
"harness": {
"enum": [
"codex_cli",
- "claude_code"
+ "claude_code",
+ "qoder_cli"
]
},
"protocol": {
diff --git a/contracts/cli/plan-lifecycle-change.v1.schema.json b/contracts/cli/plan-lifecycle-change.v1.schema.json
index 34cea8fe..aed9d170 100644
--- a/contracts/cli/plan-lifecycle-change.v1.schema.json
+++ b/contracts/cli/plan-lifecycle-change.v1.schema.json
@@ -440,7 +440,8 @@
"harness": {
"enum": [
"codex_cli",
- "claude_code"
+ "claude_code",
+ "qoder_cli"
]
},
"protocol": {
diff --git a/contracts/cli/worker-dependencies-discover-request.v1.schema.json b/contracts/cli/worker-dependencies-discover-request.v1.schema.json
index 82491b69..7da5572f 100644
--- a/contracts/cli/worker-dependencies-discover-request.v1.schema.json
+++ b/contracts/cli/worker-dependencies-discover-request.v1.schema.json
@@ -6,7 +6,8 @@
"harness": {
"enum": [
"codex_cli",
- "claude_code"
+ "claude_code",
+ "qoder_cli"
]
}
},
diff --git a/contracts/cli/worker-dependencies-select-request.v1.schema.json b/contracts/cli/worker-dependencies-select-request.v1.schema.json
index 4f8efe17..f196d54f 100644
--- a/contracts/cli/worker-dependencies-select-request.v1.schema.json
+++ b/contracts/cli/worker-dependencies-select-request.v1.schema.json
@@ -2,6 +2,18 @@
"$id": "hiroute://contracts/cli/worker-dependencies-select-request.v1.schema.json",
"$schema": "https://json-schema.org/draft/2020-12/schema",
"additionalProperties": false,
+ "else": {
+ "required": [
+ "adapter_path"
+ ]
+ },
+ "if": {
+ "properties": {
+ "harness": {
+ "const": "qoder_cli"
+ }
+ }
+ },
"properties": {
"adapter_path": {
"maxLength": 4096,
@@ -21,7 +33,8 @@
"harness": {
"enum": [
"codex_cli",
- "claude_code"
+ "claude_code",
+ "qoder_cli"
]
},
"node_path": {
@@ -32,9 +45,14 @@
},
"required": [
"harness",
- "adapter_path",
"cli_path",
"expected_selection_revision"
],
+ "then": {
+ "properties": {
+ "adapter_path": false,
+ "node_path": false
+ }
+ },
"type": "object"
}
diff --git a/contracts/compatibility-support.v1.json b/contracts/compatibility-support.v1.json
index f572a700..8587bc1b 100644
--- a/contracts/compatibility-support.v1.json
+++ b/contracts/compatibility-support.v1.json
@@ -5,8 +5,10 @@
"hiroute.agent-access-grant-entry/v1",
"hiroute.agent-check-request/v1",
"hiroute.agent-check/v1",
+ "hiroute.agent-collaboration-check-failure/v1",
"hiroute.agent-collaboration-credential/v1",
"hiroute.agent-collaboration-grant/v1",
+ "hiroute.agent-collaboration-only-settings-status/v2",
"hiroute.agent-collaboration-settings-status/v2",
"hiroute.agent-config-change/v1",
"hiroute.agent-config-permission-control/v1",
@@ -268,6 +270,9 @@
"hiroute.protected-apply-grant/v2",
"hiroute.protected-input-result/v1",
"hiroute.protected-input/v1",
+ "hiroute.qoder-additional-model/v1",
+ "hiroute.qoder-borrowed-context-collaboration/v1",
+ "hiroute.qoder-native-restore/v1",
"hiroute.rating-snapshot/v2",
"hiroute.registered-compute-discovery-fact/v1",
"hiroute.release-facts-compiler-input/v2",
@@ -297,6 +302,7 @@
"hiroute.settings-codex-model-file/v1",
"hiroute.settings-login-item/v1",
"hiroute.settings-model-publication/v1",
+ "hiroute.settings-qoder-model-file/v1",
"hiroute.settings-service-completion/v2",
"hiroute.settings-service-proof/v2",
"hiroute.settings-skill-file/v1",
@@ -368,7 +374,7 @@
"contract": "hiroute.pre-fix-default-canonical-records/v1",
"mode": "frozen_fixture",
"owner": "local-storage",
- "reason": "Preserve the unmodified pre-MVP canonical Operation journal, alias-only model scope and six original step proofs as algorithm regression evidence. It is not a supported schema22 migration source or production recovery decoder; a schema23 store rejects its raw journal.",
+ "reason": "Preserve the unmodified pre-MVP canonical Operation journal, alias-only model scope and six original step proofs as algorithm regression evidence. It is not a supported schema22 migration source or production recovery decoder; the current stable store rejects its raw journal.",
"removal_condition": "Remove only with the historical canonical digest regression suite; never regenerate the frozen bytes from a current producer.",
"allowed_paths": [
"crates/local-storage/tests/canonical_compat.rs",
@@ -890,6 +896,20 @@
"tools/e2e-harness/tests/p0_gateway_request_authority.rs"
],
"field_compatibility_support": [
+ {
+ "contract": "hiroute.delegation-native-root/v1",
+ "field": "task-owned native home without borrowed-native-context.json",
+ "mode": "recovery_read_only",
+ "owner": "worker-native-context",
+ "reason": "Continue existing private-root Worker tasks with their original native history and owned cleanup. New tasks bind borrowed native context explicitly; a damaged or partially missing binding must never fall back to the legacy scanner.",
+ "removal_condition": "Retire only after all retained tasks and supported backups no longer contain private-root native sessions, together with the frozen recovery fixtures.",
+ "allowed_paths": [
+ "crates/daemon/src/delegation/profile/materials.rs",
+ "crates/daemon/src/delegation/profile/native_history.rs",
+ "crates/daemon/src/delegation/profile/materials_tests.rs",
+ "crates/daemon/src/delegation/profile/native_history_tests.rs"
+ ]
+ },
{
"contract": "hiroute.settings-service-completion/v2",
"field": "service-first restore checkpoint with an unstaged client model file",
@@ -964,6 +984,110 @@
"crates/cpa-bridge/src/runtime.rs",
"crates/cpa-bridge/src/runtime/tests/proxy_recovery.rs"
]
+ },
+ {
+ "contract": "hiroute.worker-dependency-selection-confirmation/v1",
+ "field": "schema23 selection/effect constraints and original Operation journal bytes",
+ "mode": "recovery_read_only",
+ "owner": "local-storage",
+ "reason": "Accept only marked stable schema23 through the existing complete three-store backup coordinator; schema24 expands harness constraints without reserializing selections, effects or Operation journals. Interrupted 23/24 sets require validated source backup, identities, key and migration phase.",
+ "removal_condition": "End schema23 upgrade support only by an explicit product decision that preserves a documented usable recovery path for supported stores and backups.",
+ "allowed_paths": [
+ "crates/local-storage/src/migrations/startup_format.rs",
+ "crates/local-storage/src/migrations/worker_dependencies_v24.rs"
+ ]
+ },
+ {
+ "contract": "hiroute.worker-dependency-selection-confirmation/v1",
+ "field": "frozen schema23 staged/activated/succeeded Worker journals",
+ "mode": "frozen_fixture",
+ "owner": "local-storage",
+ "reason": "Original six Codex/Claude journals exported from producer cdbb2cec by 5d8306cc establish raw-byte, fingerprint, idempotency and compensation compatibility after production startup; never regenerate from the current serializer.",
+ "removal_condition": "Retire only with declared schema23 recovery support and its replacement upgrade evidence.",
+ "allowed_paths": [
+ "crates/local-storage/src/migrations/fixtures/schema23-worker-operations.json",
+ "crates/local-storage/src/migrations/fixtures/README.md",
+ "crates/local-storage/src/migrations/worker_dependencies_v24_tests.rs",
+ "crates/local-storage/src/migrations/upgrade_batch_recovery_tests.rs"
+ ]
+ },
+ {
+ "contract": "hiroute.worker-settings/v1",
+ "field": "Qoder CLI 1.1.65 exact native-session history and compaction witnesses in acceptance fixtures",
+ "mode": "frozen_fixture",
+ "owner": "worker-product-acceptance",
+ "reason": "The opt-in Qoder acceptance fixture locates only the already-bound native session beneath its private canonical workspace (at most 200 characters) to verify history retention, exact missing-history refusal and native automatic compaction. The shared fixture classifier pins native summarization prompts; the auxiliary journey additionally pins compact_boundary/isCompactSummary records. Production never enumerates or derives a Qoder history filename or consumes these records.",
+ "removal_condition": "Replace when native exact-session history and structured purpose/compaction receipts can prove the same assertions; revise the pinned fixture when supporting a different native history or compaction layout.",
+ "allowed_paths": [
+ "crates/daemon/tests/support/qoder_native_context.py",
+ "crates/daemon/tests/support/qoder_compaction_product.py",
+ "crates/daemon/tests/support/native_context_fixture.py",
+ "tools/product-e2e/tests/QODER_DELEGATION.md",
+ "scripts/test-qoder-product.py"
+ ]
+ },
+ {
+ "contract": "hiroute.delegation-native-root/v1",
+ "field": "current runtime task/run record_json identity witness for a cancelled Qoder acceptance task",
+ "mode": "frozen_fixture",
+ "owner": "worker-product-acceptance",
+ "reason": "Cancellation does not grant successful-Continue eligibility. The opt-in fixture reads only its own runtime.db in read-only mode with exact workspace/task/run keys, verifies the task-owned context descriptor, Qoder harness, cancelled state, completed cleanup and matching native/ACP identity, then locates that exact native transcript. It never scans a daily database or changes the production Continue reader.",
+ "removal_condition": "Replace this test-only current-storage reader when a public exact-native-session identity projection can establish cancellation history retention independently of successful-Continue material; update the fixture if the task/run storage contract changes.",
+ "allowed_paths": [
+ "crates/daemon/tests/support/qoder_native_context.py",
+ "scripts/test-qoder-product.py",
+ "tools/product-e2e/tests/QODER_DELEGATION.md"
+ ]
+ },
+ {
+ "contract": "hiroute.qoder-additional-model/v1",
+ "field": "Qoder CLI 1.1.65 stream-json terminal result in persisted-model acceptance",
+ "mode": "frozen_fixture",
+ "owner": "agent-connections-product-acceptance",
+ "reason": "The opt-in persisted-model journey requires one native result with subtype=success, is_error=false, the independently issued source receipt and a nonempty session_id. This pinned test reader proves ordinary native startup consumed the saved route; it is not a production parser or model-subscription discovery contract.",
+ "removal_condition": "Replace or revise when a supported Qoder CLI changes its terminal result shape, preserving the independent upstream receipt and native identity assertions.",
+ "allowed_paths": [
+ "crates/daemon/tests/support/qoder_model_fixture.py",
+ "scripts/test-qoder-product.py",
+ "tools/product-e2e/tests/QODER_DELEGATION.md"
+ ]
+ },
+ {
+ "contract": "hiroute.operation-input/v1",
+ "field": "historical object member ordering in mutable operation_json.steps and operation_steps.step_json.step",
+ "mode": "recovery_read_only",
+ "owner": "local-storage Operation journal",
+ "reason": "journal_json_matches reads pre-canonical mutable journal copies emitted under either serde_json object-order feature graph. The same SQLite snapshot retains immutable Plan bytes, identities, generation, writer and step metadata guards; the narrow reader rejects duplicate members, unknown content changes, array reordering and changed numeric tokens. Current step-row writes use the existing canonical producer.",
+ "removal_condition": "Retire only after an explicitly approved migration covers every supported historical journal and backup, with replacement recovery evidence for the frozen original producer fixtures.",
+ "allowed_paths": [
+ "crates/local-storage/src/control/journal.rs",
+ "crates/local-storage/src/control/journal_order_tests.rs"
+ ]
+ },
+ {
+ "contract": "hiroute.agent-profile/v1",
+ "field": "Qoder collaboration-only ingress/config precedence/owned fields",
+ "mode": "recovery_read_only",
+ "owner": "agent-connections",
+ "reason": "Preserve the original model-less Qoder profile shape and identity for accepted collaboration Operations; current additional-model capability never upgrades a historical Skill transaction implicitly.",
+ "removal_condition": "Retire only when retained Operations and supported backups no longer contain collaboration-only Qoder profiles, together with their frozen byte-preservation test.",
+ "allowed_paths": [
+ "crates/domain/src/agents/profile.rs",
+ "crates/domain/src/agents/optional_model_tests.rs"
+ ]
+ },
+ {
+ "contract": "hiroute.agent-surface-check/v1",
+ "field": "marked schema23/schema24 native surface rows before Qoder model verification",
+ "mode": "recovery_read_only",
+ "owner": "local-storage",
+ "reason": "Schema25 extends only the closed surface constraint via the existing three-store migration coordinator; historical record JSON, revisions and timestamps are copied verbatim. Historical SQL-layout tests use opaque synthetic rows and do not claim native verification.",
+ "removal_condition": "End marked schema23/schema24 upgrade support only through an explicit product decision preserving a usable supported data recovery path.",
+ "allowed_paths": [
+ "crates/local-storage/src/migrations/startup_format.rs",
+ "crates/local-storage/src/migrations/agent_surface_checks_v25.rs",
+ "crates/local-storage/src/migrations/agent_surface_checks_v25_tests.rs"
+ ]
}
]
}
diff --git a/crates/application-api/src/agent_connection.rs b/crates/application-api/src/agent_connection.rs
index 87228703..adc906b7 100644
--- a/crates/application-api/src/agent_connection.rs
+++ b/crates/application-api/src/agent_connection.rs
@@ -116,3 +116,62 @@ pub struct AgentConnectionStatusV1 {
pub struct AgentLaunchDescriptorRequestV1 {
pub connection_id: String,
}
+
+/// Closed public reasons for an explicitly requested native collaboration check. Native output,
+/// paths and credentials are never part of this diagnostic contract.
+pub const AGENT_COLLABORATION_CHECK_FAILURE_SCHEMA_V1: &str =
+ "hiroute.agent-collaboration-check-failure/v1";
+
+#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
+#[serde(rename_all = "snake_case")]
+pub enum AgentCollaborationCheckFailureReasonV1 {
+ LoginRequired,
+ InstalledSkillMissing,
+ InstalledSkillChanged,
+ InstalledSkillInvalid,
+ NativeContextUnavailable,
+ NativeContextChanged,
+ DependencyUnavailable,
+ CheckTimedOut,
+ VerificationFailed,
+}
+
+#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
+#[serde(deny_unknown_fields)]
+pub struct AgentCollaborationCheckFailureV1 {
+ pub schema: String,
+ pub reason: AgentCollaborationCheckFailureReasonV1,
+}
+
+impl AgentCollaborationCheckFailureV1 {
+ pub fn new(reason: AgentCollaborationCheckFailureReasonV1) -> Self {
+ Self {
+ schema: AGENT_COLLABORATION_CHECK_FAILURE_SCHEMA_V1.into(),
+ reason,
+ }
+ }
+ pub fn valid(&self) -> bool {
+ self.schema == AGENT_COLLABORATION_CHECK_FAILURE_SCHEMA_V1
+ }
+}
+
+#[cfg(test)]
+mod collaboration_check_failure_tests {
+ use super::*;
+ use serde_json::json;
+
+ #[test]
+ fn collaboration_failure_details_reject_native_output_and_unknown_reasons() {
+ let value = json!({"schema":"hiroute.agent-collaboration-check-failure/v1", "reason":"login_required"});
+ let failure: AgentCollaborationCheckFailureV1 =
+ serde_json::from_value(value.clone()).unwrap();
+ assert!(failure.valid());
+ assert_eq!(serde_json::to_value(failure).unwrap(), value);
+ let mut leaked = value.clone();
+ leaked["native_output"] = "secret native output".into();
+ assert!(serde_json::from_value::<AgentCollaborationCheckFailureV1>(leaked).is_err());
+ let mut unknown = value;
+ unknown["reason"] = "/private/path/token".into();
+ assert!(serde_json::from_value::<AgentCollaborationCheckFailureV1>(unknown).is_err());
+ }
+}
diff --git a/crates/application-api/src/agent_settings.rs b/crates/application-api/src/agent_settings.rs
index 87756d9c..6a0040c0 100644
--- a/crates/application-api/src/agent_settings.rs
+++ b/crates/application-api/src/agent_settings.rs
@@ -115,6 +115,63 @@ pub enum AgentModelSettingsStateV2 {
NeedsAttention,
}
+/// Settings status follows the actual facets supported by an installation. The model variant
+/// serializes exactly as the existing V2 response, without an added envelope or discriminator.
+#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
+#[serde(untagged)]
+pub enum AgentSettingsStatusV2 {
+ Model(Box<AgentModelSettingsStatusV2>),
+ CollaborationOnly(AgentCollaborationOnlySettingsStatusV2),
+}
+
+#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
+#[serde(deny_unknown_fields)]
+pub struct AgentCollaborationOnlySettingsStatusV2 {
+ pub schema: String,
+ pub context_id: String,
+ pub collaboration: AgentCollaborationSettingsStatusV2,
+}
+
+impl AgentSettingsStatusV2 {
+ pub fn model(&self) -> Option<&AgentModelSettingsStatusV2> {
+ match self {
+ Self::Model(model) => Some(model.as_ref()),
+ Self::CollaborationOnly(_) => None,
+ }
+ }
+ pub fn collaboration(&self) -> Option<&AgentCollaborationSettingsStatusV2> {
+ match self {
+ Self::Model(model) => model.collaboration.as_ref(),
+ Self::CollaborationOnly(status) => Some(&status.collaboration),
+ }
+ }
+ pub fn context_id(&self) -> &str {
+ match self {
+ Self::Model(model) => &model.context_id,
+ Self::CollaborationOnly(status) => &status.context_id,
+ }
+ }
+ pub fn valid(&self) -> bool {
+ let context = self.context_id();
+ !context.is_empty()
+ && context.len() <= 256
+ && !context.contains(char::is_control)
+ && match self {
+ Self::Model(model) => {
+ model.schema == "hiroute.agent-model-settings-status/v2"
+ && model.collaboration.as_ref().is_none_or(|collaboration| {
+ collaboration.schema == "hiroute.agent-collaboration-settings-status/v2"
+ })
+ }
+ Self::CollaborationOnly(status) => {
+ status.schema == "hiroute.agent-collaboration-only-settings-status/v2"
+ && status.collaboration.schema
+ == "hiroute.agent-collaboration-settings-status/v2"
+ }
+ }
+ }
+}
+
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct AgentModelSettingsStatusV2 {
@@ -185,6 +242,9 @@ impl AgentModelSettingsStatusV2 {
AgentModelSurfaceV2::CodexCli | AgentModelSurfaceV2::CodexDesktop
),
AgentModelSelectionV2::ClaudeLauncher { surfaces, .. } => surfaces.contains(surface),
+ AgentModelSelectionV2::QoderAdditional { .. } => {
+ *surface == AgentModelSurfaceV2::QoderCli
+ }
};
let mut seen = std::collections::BTreeSet::new();
self.surface_results.iter().all(|result| {
@@ -319,6 +379,22 @@ mod tests {
assert!(!value.derive_model_verified(value.applied_revision));
}
+ #[test]
+ fn qoder_model_verification_cannot_inherit_another_clients_success() {
+ let mut value = status();
+ value.current_selection = Some(AgentModelSelectionV2::QoderAdditional {
+ allowed_plan_ids: [AgentPlanId::parse("plan/test").unwrap()].into(),
+ });
+ assert!(!value.derive_model_verified(value.applied_revision));
+ value.surface_results.truncate(1);
+ value.surface_results[0].surface = AgentModelSurfaceV2::QoderCli;
+ assert!(value.derive_model_verified(value.applied_revision));
+ value.surface_results[0].state = AgentModelCheckStateV2::Failed;
+ assert!(!value.derive_model_verified(value.applied_revision));
+ value.surface_results[0].state = AgentModelCheckStateV2::Passed;
+ assert!(!value.derive_model_verified(Some(GatewayPublicationRevision::new(8).unwrap())));
+ }
+
#[test]
fn pending_missing_or_duplicate_results_cannot_inherit_success() {
let mut value = status();
@@ -371,7 +447,8 @@ mod tests {
}
}
-/// Resume the original already-authorized Codex settings Operation; never creates a new intent.
+/// Resume an original already-authorized settings Operation for a supported native client;
+/// never creates a new intent or changes the original context.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct AgentSettingsRetryV1 {
@@ -379,3 +456,7 @@ pub struct AgentSettingsRetryV1 {
pub context_id: String,
pub operation_id: hiroute_domain::OperationId,
}
+
+#[cfg(test)]
+#[path = "agent_settings_status_tests.rs"]
+mod status_contract_tests;
diff --git a/crates/application-api/src/agent_settings_status_tests.rs b/crates/application-api/src/agent_settings_status_tests.rs
new file mode 100644
index 00000000..86281db0
--- /dev/null
+++ b/crates/application-api/src/agent_settings_status_tests.rs
@@ -0,0 +1,32 @@
+use super::*;
+
+#[test]
+fn model_status_union_keeps_existing_v2_bytes() {
+ let old = r#"{"schema":"hiroute.agent-model-settings-status/v2","context_id":"agent-context/codex","state":"not_configured","operation_id":null,"operation_state":null,"restore_point_ref":null,"applied_revision":null,"surface_results":[],"model_verified":false}"#;
+ let status: AgentSettingsStatusV2 = serde_json::from_str(old).unwrap();
+ assert!(status.valid());
+ assert!(status.model().is_some());
+ assert_eq!(serde_json::to_string(&status).unwrap(), old);
+}
+
+#[test]
+fn collaboration_only_status_has_no_model_shell_and_rejects_mixed_shape() {
+ let wire = r#"{"schema":"hiroute.agent-collaboration-only-settings-status/v2","context_id":"agent-context/qoder","collaboration":{"schema":"hiroute.agent-collaboration-settings-status/v2","state":"not_configured","operation_id":null,"operation_state":null,"restore_point_ref":null}}"#;
+ let status: AgentSettingsStatusV2 = serde_json::from_str(wire).unwrap();
+ assert!(status.valid());
+ assert!(status.model().is_none());
+ assert!(status.collaboration().is_some());
+ assert_eq!(serde_json::to_string(&status).unwrap(), wire);
+ let mut mixed: serde_json::Value = serde_json::from_str(wire).unwrap();
+ mixed["model_verified"] = false.into();
+ assert!(serde_json::from_value::<AgentSettingsStatusV2>(mixed).is_err());
+ let mut missing: serde_json::Value = serde_json::from_str(wire).unwrap();
+ missing.as_object_mut().unwrap().remove("collaboration");
+ assert!(serde_json::from_value::<AgentSettingsStatusV2>(missing).is_err());
+ let invalid: AgentSettingsStatusV2 = serde_json::from_str(&wire.replace(
+ "collaboration-only-settings-status/v2",
+ "model-settings-status/v2",
+ ))
+ .unwrap();
+ assert!(!invalid.valid());
+}
diff --git a/crates/application-api/src/generated/plan_authoring.rs b/crates/application-api/src/generated/plan_authoring.rs
index 3a4928b6..fe854e93 100644
--- a/crates/application-api/src/generated/plan_authoring.rs
+++ b/crates/application-api/src/generated/plan_authoring.rs
@@ -81,7 +81,7 @@ fn definitions() -> Value {
"schema":{"const":"hiroute.plan-editor/v2"},"display_name":{"type":"string","maxLength":128},"purpose":{"type":"string","maxLength":512},
"custom_alias":{"type":"string","maxLength":64},"mode":{"enum":["fixed_model","smart_saving","free_first"]},
"candidates":reference("candidates"),"smart":smart,"free":free,"delegation_enabled":{"type":"boolean"},"requirements":requirements,"limits":limits,
- "work":object(&["harness","protocol"],json!({"harness":{"enum":["codex_cli","claude_code"]},"protocol":{"enum":["responses","messages"]}}))
+ "work":object(&["harness","protocol"],json!({"harness":{"enum":["codex_cli","claude_code","qoder_cli"]},"protocol":{"enum":["responses","messages"]}}))
}),
);
let draft = object(
diff --git a/crates/application-api/src/generated/worker.rs b/crates/application-api/src/generated/worker.rs
index f822846f..decadaab 100644
--- a/crates/application-api/src/generated/worker.rs
+++ b/crates/application-api/src/generated/worker.rs
@@ -239,7 +239,7 @@ pub(super) fn dependencies_discover() -> Value {
"$id": "hiroute://contracts/cli/worker-dependencies-discover-request.v1.schema.json",
"type": "object",
"additionalProperties": false,
- "properties": {"harness": {"enum": ["codex_cli", "claude_code"]}}
+ "properties": {"harness": {"enum": ["codex_cli", "claude_code", "qoder_cli"]}}
})
}
@@ -249,13 +249,16 @@ pub(super) fn dependencies_select() -> Value {
"$id": "hiroute://contracts/cli/worker-dependencies-select-request.v1.schema.json",
"type": "object",
"additionalProperties": false,
- "required": ["harness", "adapter_path", "cli_path", "expected_selection_revision"],
+ "required": ["harness", "cli_path", "expected_selection_revision"],
"properties": {
- "harness": {"enum": ["codex_cli", "claude_code"]},
+ "harness": {"enum": ["codex_cli", "claude_code", "qoder_cli"]},
"adapter_path": {"type": "string", "minLength": 1, "maxLength": 4096},
"cli_path": {"type": "string", "minLength": 1, "maxLength": 4096},
"node_path": {"type": "string", "minLength": 1, "maxLength": 4096},
"expected_selection_revision": {"type": "integer", "minimum": 0, "maximum": u64::MAX}
- }
+ },
+ "if": {"properties": {"harness": {"const": "qoder_cli"}}},
+ "then": {"properties": {"adapter_path": false, "node_path": false}},
+ "else": {"required": ["adapter_path"]}
})
}
diff --git a/crates/application-api/src/protocol.rs b/crates/application-api/src/protocol.rs
index 36152c90..2cb91d28 100644
--- a/crates/application-api/src/protocol.rs
+++ b/crates/application-api/src/protocol.rs
@@ -564,6 +564,7 @@ pub enum ErrorCode {
ChangePreviewStale,
IdempotencyKeyReused,
AgentAuthPrecedenceConflict,
+ QoderModelBudgetConflict,
CapabilityDenied,
CapabilityUnavailable,
ResourceNotFound,
@@ -602,7 +603,9 @@ impl ErrorCode {
| Self::RevisionConflict
| Self::ChangePreviewStale
| Self::IdempotencyKeyReused => MachineStatus::Conflict,
- Self::NoSupportedAgent | Self::AgentAuthPrecedenceConflict => MachineStatus::Conflict,
+ Self::NoSupportedAgent
+ | Self::AgentAuthPrecedenceConflict
+ | Self::QoderModelBudgetConflict => MachineStatus::Conflict,
Self::CapabilityDenied => MachineStatus::Denied,
Self::ResourceNotFound => MachineStatus::NotFound,
Self::CapabilityUnavailable
@@ -632,6 +635,7 @@ impl ErrorCode {
Self::ChangePreviewStale => "application.error.change_preview_stale",
Self::IdempotencyKeyReused => "application.error.idempotency_key_reused",
Self::AgentAuthPrecedenceConflict => "agent.error.auth_precedence_conflict",
+ Self::QoderModelBudgetConflict => "agent.error.qoder_model_budget_conflict",
Self::CapabilityUnavailable => "control.error.capability_unavailable",
Self::CapabilityDenied => "control.error.capability_denied",
Self::ResourceNotFound => "application.error.resource_not_found",
diff --git a/crates/application-api/src/worker.rs b/crates/application-api/src/worker.rs
index 8cbec247..4c77c27b 100644
--- a/crates/application-api/src/worker.rs
+++ b/crates/application-api/src/worker.rs
@@ -79,7 +79,8 @@ impl WorkerDependenciesDiscoverRequestV1 {
#[serde(deny_unknown_fields)]
pub struct WorkerDependenciesSelectRequestV1 {
pub harness: WorkerHarnessV1,
- pub adapter_path: String,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub adapter_path: Option<String>,
pub cli_path: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub node_path: Option<String>,
@@ -88,12 +89,13 @@ pub struct WorkerDependenciesSelectRequestV1 {
impl WorkerDependenciesSelectRequestV1 {
pub fn valid(&self) -> bool {
- absolute_path(&self.adapter_path)
- && absolute_path(&self.cli_path)
- && self
- .node_path
- .as_ref()
- .is_none_or(|path| absolute_path(path))
+ hiroute_domain::delegation::WorkerLaunchFormV1::validate(
+ self.harness,
+ self.adapter_path.as_deref(),
+ &self.cli_path,
+ self.node_path.as_deref(),
+ )
+ .is_ok()
}
}
@@ -128,6 +130,7 @@ pub fn plan_worker_dependency_selection(
let harness = match request.harness {
WorkerHarnessV1::CodexCli => "codex_cli",
WorkerHarnessV1::ClaudeCode => "claude_code",
+ WorkerHarnessV1::QoderCli => "qoder_cli",
};
let spec = ChangeSpecV1 {
schema_version: CHANGE_SPEC_SCHEMA_V1,
@@ -209,7 +212,8 @@ pub struct WorkerDependencySelectionRevisionV1 {
#[serde(deny_unknown_fields)]
pub struct WorkerDependencySelectionV1 {
pub harness: WorkerHarnessV1,
- pub adapter_path: String,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub adapter_path: Option<String>,
pub cli_path: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub node_path: Option<String>,
@@ -251,16 +255,17 @@ impl WorkerDependenciesViewV1 {
.collect::<BTreeSet<_>>();
self.schema == WORKER_DEPENDENCIES_VIEW_SCHEMA_V1
&& !self.selection_revisions.is_empty()
- && self.selection_revisions.len() <= 2
+ && self.selection_revisions.len() <= 3
&& revisions.len() == self.selection_revisions.len()
&& selections.len() == self.selected.len()
&& self.selected.iter().all(|selection| {
- absolute_path(&selection.adapter_path)
- && absolute_path(&selection.cli_path)
- && selection
- .node_path
- .as_ref()
- .is_none_or(|path| absolute_path(path))
+ hiroute_domain::delegation::WorkerLaunchFormV1::validate(
+ selection.harness,
+ selection.adapter_path.as_deref(),
+ &selection.cli_path,
+ selection.node_path.as_deref(),
+ )
+ .is_ok()
})
&& self.candidates.len() <= 256
&& self.candidates.iter().all(|candidate| {
@@ -371,9 +376,10 @@ pub struct WorkerExecutorAvailabilityListV1 {
impl WorkerExecutorAvailabilityListV1 {
pub fn valid(&self) -> bool {
self.schema == WORKER_EXECUTOR_AVAILABILITY_SCHEMA_V1
- && self.executors.len() == 2
+ && self.executors.len() == 3
&& self.executors[0].harness == WorkerHarnessV1::CodexCli
&& self.executors[1].harness == WorkerHarnessV1::ClaudeCode
+ && self.executors[2].harness == WorkerHarnessV1::QoderCli
&& self
.executors
.iter()
@@ -900,7 +906,7 @@ mod tests {
fn dependency_selection_plan_binds_only_the_normalized_tuple_and_target_revision() {
let request = WorkerDependenciesSelectRequestV1 {
harness: WorkerHarnessV1::CodexCli,
- adapter_path: "/opt/acp/codex-acp.js".into(),
+ adapter_path: Some("/opt/acp/codex-acp.js".into()),
cli_path: "/opt/bin/codex".into(),
node_path: Some("/opt/bin/node".into()),
expected_selection_revision: 7,
@@ -936,14 +942,14 @@ mod tests {
fn dependency_selection_plan_rejects_relative_or_control_character_paths() {
let request = WorkerDependenciesSelectRequestV1 {
harness: WorkerHarnessV1::CodexCli,
- adapter_path: "relative/adapter".into(),
+ adapter_path: Some("relative/adapter".into()),
cli_path: "/opt/bin/codex".into(),
node_path: Some("/opt/bin/node".into()),
expected_selection_revision: 0,
};
assert!(plan_worker_dependency_selection(&request).is_none());
let invalid = WorkerDependenciesSelectRequestV1 {
- adapter_path: "/opt/acp/codex\nacp".into(),
+ adapter_path: Some("/opt/acp/codex\nacp".into()),
..request
};
assert!(plan_worker_dependency_selection(&invalid).is_none());
@@ -1143,7 +1149,7 @@ mod tests {
}
#[test]
- fn executor_availability_is_exactly_two_capability_scoped_harnesses() {
+ fn executor_availability_is_exactly_three_capability_scoped_harnesses() {
let ready = WorkerExecutorCapabilityAvailabilityV1 {
state: WorkerExecutorAvailabilityStateV1::Ready,
reason: None,
@@ -1170,10 +1176,17 @@ mod tests {
executors: vec![
executor(WorkerHarnessV1::CodexCli),
executor(WorkerHarnessV1::ClaudeCode),
+ executor(WorkerHarnessV1::QoderCli),
],
};
assert!(response.valid());
+ let mut incomplete = response.clone();
+ incomplete.executors.pop();
+ assert!(!incomplete.valid());
+ let mut duplicate = response.clone();
+ duplicate.executors[2].harness = WorkerHarnessV1::CodexCli;
+ assert!(!duplicate.valid());
let mut reordered = response.clone();
reordered.executors.swap(0, 1);
assert!(!reordered.valid());
@@ -1183,3 +1196,7 @@ mod tests {
assert!(!overstated.valid());
}
}
+
+#[cfg(test)]
+#[path = "worker_selection_tests.rs"]
+mod selection_tests;
diff --git a/crates/application-api/src/worker_selection_tests.rs b/crates/application-api/src/worker_selection_tests.rs
new file mode 100644
index 00000000..aa00dcd7
--- /dev/null
+++ b/crates/application-api/src/worker_selection_tests.rs
@@ -0,0 +1,160 @@
+//! Product contract: preserve saved adapter selections while accepting one native ACP CLI.
+use super::*;
+use hiroute_domain::{StoredOperationInputV1, TransactionPlanV1};
+
+fn generated_schema(path: &str) -> serde_json::Value {
+ let file = crate::generated_contract_files()
+ .into_iter()
+ .find(|file| file.relative_path == path)
+ .unwrap();
+ serde_json::from_str(&file.contents).unwrap()
+}
+
+#[test]
+fn saved_adapter_selections_preserve_json_and_confirmation_identity() {
+ let schema = generated_schema("worker-dependencies-select-request.v1.schema.json");
+ // Adapter-based clients keep their required adapter in the published conditional schema.
+ assert_eq!(
+ schema["else"]["required"],
+ serde_json::json!(["adapter_path"])
+ );
+ // Frozen V1 payloads and independently calculated canonical SHA-256 values. The expected
+ // side deliberately does not serialize the current producer or call its digest algorithm.
+ let cases = [
+ (
+ r#"{"harness":"codex_cli","adapter_path":"/opt/acp/adapter.js","cli_path":"/opt/bin/client","expected_selection_revision":7}"#,
+ r#"{"harness":"codex_cli","adapter_path":"/opt/acp/adapter.js","cli_path":"/opt/bin/client"}"#,
+ "sha256:01e16fae616552635d9b77cb2dbe3272cc05e8a548fc3e95f71d671d053c3f69",
+ "worker-dependency-selection:5b5b9a089fa008bfc2a91d1833610695992b5e2a6d079442c98c79172dbbd4d1",
+ ),
+ (
+ r#"{"harness":"codex_cli","adapter_path":"/opt/acp/adapter.js","cli_path":"/opt/bin/client","node_path":"/opt/bin/node","expected_selection_revision":7}"#,
+ r#"{"harness":"codex_cli","adapter_path":"/opt/acp/adapter.js","cli_path":"/opt/bin/client","node_path":"/opt/bin/node"}"#,
+ "sha256:796b38a26770d894814caaef51c7f8ae4180830a78623bac9cf9954b0abb568b",
+ "worker-dependency-selection:f7cffc9d7ed25312cc899bf79fcf3a871b902202509c2dd771debf574c5d03b1",
+ ),
+ (
+ r#"{"harness":"claude_code","adapter_path":"/opt/acp/adapter.js","cli_path":"/opt/bin/client","expected_selection_revision":7}"#,
+ r#"{"harness":"claude_code","adapter_path":"/opt/acp/adapter.js","cli_path":"/opt/bin/client"}"#,
+ "sha256:6ccc36de24affb1e4fc380d05003bb4e033e627c0db7d1b56226e4e1409cbd91",
+ "worker-dependency-selection:c2db1091d6add9a405689945edf59485ee171b6b3164069a4ace6730b90cba49",
+ ),
+ (
+ r#"{"harness":"claude_code","adapter_path":"/opt/acp/adapter.js","cli_path":"/opt/bin/client","node_path":"/opt/bin/node","expected_selection_revision":7}"#,
+ r#"{"harness":"claude_code","adapter_path":"/opt/acp/adapter.js","cli_path":"/opt/bin/client","node_path":"/opt/bin/node"}"#,
+ "sha256:e48f651bab522d28ad7d62964cafed5e6ad9ea81348158ed0a84ae0dbdb12e34",
+ "worker-dependency-selection:52cc6ea2e04b2ca05bbd1e18f058076187d023b0201fcc968d3eae42bbac358c",
+ ),
+ ];
+ for (request_json, selection_json, accepted, idempotency) in cases {
+ let request: WorkerDependenciesSelectRequestV1 =
+ serde_json::from_str(request_json).unwrap();
+ assert_ne!(
+ schema["if"]["properties"]["harness"]["const"],
+ serde_json::to_value(request.harness).unwrap()
+ );
+ assert_eq!(serde_json::to_string(&request).unwrap(), request_json);
+ let plan = plan_worker_dependency_selection(&request).unwrap();
+ assert_eq!(
+ serde_json::to_string(&plan.change.after_selection).unwrap(),
+ selection_json
+ );
+ assert_eq!(plan.accept_digest.as_str(), accepted);
+ assert_eq!(plan.idempotency_key, idempotency);
+ let transaction =
+ TransactionPlanV1::from_worker_dependency_selection_planner(plan.spec, plan.change)
+ .unwrap();
+ let stored = StoredOperationInputV1::freeze(&transaction).unwrap();
+ assert_eq!(
+ StoredOperationInputV1::freeze(&stored.build().unwrap()).unwrap(),
+ stored
+ );
+ }
+}
+
+#[test]
+fn native_acp_requires_only_cli_and_rejects_cross_form_fields() {
+ let json =
+ r#"{"harness":"qoder_cli","cli_path":"/opt/bin/qodercli","expected_selection_revision":0}"#;
+ let request: WorkerDependenciesSelectRequestV1 = serde_json::from_str(json).unwrap();
+ let schema = generated_schema("worker-dependencies-select-request.v1.schema.json");
+ assert_eq!(
+ schema["required"],
+ serde_json::json!(["harness", "cli_path", "expected_selection_revision"])
+ );
+ assert_eq!(
+ schema["if"]["properties"]["harness"]["const"],
+ serde_json::to_value(request.harness).unwrap()
+ );
+ assert_eq!(
+ schema["then"]["properties"],
+ serde_json::json!({"adapter_path":false,"node_path":false})
+ );
+ assert_eq!(serde_json::to_string(&request).unwrap(), json);
+ let plan = plan_worker_dependency_selection(&request).unwrap();
+ assert!(matches!(
+ plan.change.after_selection.validated_launch().unwrap(),
+ hiroute_domain::delegation::WorkerLaunchFormV1::NativeAcp {
+ cli: "/opt/bin/qodercli"
+ }
+ ));
+ for (adapter, node) in [
+ (Some("/opt/adapter".into()), None),
+ (None, Some("/opt/node".into())),
+ ] {
+ let invalid = WorkerDependenciesSelectRequestV1 {
+ adapter_path: adapter,
+ node_path: node,
+ ..request.clone()
+ };
+ assert!(plan_worker_dependency_selection(&invalid).is_none());
+ }
+ for harness in [WorkerHarnessV1::CodexCli, WorkerHarnessV1::ClaudeCode] {
+ assert!(
+ plan_worker_dependency_selection(&WorkerDependenciesSelectRequestV1 {
+ harness,
+ ..request.clone()
+ })
+ .is_none()
+ );
+ }
+ let invalid = WorkerDependencySelectionRecordV1 {
+ harness: WorkerHarnessV1::QoderCli,
+ adapter_path: Some("/opt/adapter".into()),
+ cli_path: "/opt/qoder".into(),
+ node_path: None,
+ };
+ let mut forged = plan.change;
+ forged.after_selection = invalid;
+ let mut spec = plan.spec;
+ spec.desired_state = serde_json::to_value(&forged.after_selection).unwrap();
+ assert!(TransactionPlanV1::from_worker_dependency_selection_planner(spec, forged).is_err());
+}
+
+#[test]
+fn published_worker_harnesses_match_typed_discovery_selection_and_plan_bindings() {
+ let discover = generated_schema("worker-dependencies-discover-request.v1.schema.json");
+ let select = generated_schema("worker-dependencies-select-request.v1.schema.json");
+ let editor = generated_schema("plan-editor.v2.schema.json");
+ let expected = serde_json::json!(["codex_cli", "claude_code", "qoder_cli"]);
+ for declared in [
+ &discover["properties"]["harness"]["enum"],
+ &select["properties"]["harness"]["enum"],
+ &editor["$defs"]["editor"]["properties"]["work"]["properties"]["harness"]["enum"],
+ ] {
+ assert_eq!(declared, &expected);
+ }
+ for harness in expected.as_array().unwrap() {
+ let discovery: WorkerDependenciesDiscoverRequestV1 =
+ serde_json::from_value(serde_json::json!({"harness":harness})).unwrap();
+ assert!(discovery.valid());
+ assert_eq!(
+ serde_json::to_value(discovery).unwrap()["harness"],
+ *harness
+ );
+ let work: hiroute_domain::WorkerPlanV1 =
+ serde_json::from_value(serde_json::json!({"harness":harness,"protocol":"responses"}))
+ .unwrap();
+ assert_eq!(serde_json::to_value(work).unwrap()["harness"], *harness);
+ }
+}
diff --git a/crates/application/src/agent_connection/collaboration_check.rs b/crates/application/src/agent_connection/collaboration_check.rs
new file mode 100644
index 00000000..1599d70f
--- /dev/null
+++ b/crates/application/src/agent_connection/collaboration_check.rs
@@ -0,0 +1,108 @@
+//! Public failure projection after the existing protected Check admission.
+use crate::control::CollaborationCheckError;
+use hiroute_application_api::{
+ AGENT_COLLABORATION_CHECK_FAILURE_SCHEMA_V1, AgentCollaborationCheckFailureReasonV1 as Reason,
+ AgentCollaborationCheckFailureV1, ErrorCode, ErrorV1, MachineEnvelopeV2,
+};
+use serde_json::Value;
+
+pub(crate) fn failed(
+ error: CollaborationCheckError,
+ request_id: String,
+) -> MachineEnvelopeV2<Value> {
+ match error {
+ CollaborationCheckError::Control(error) => {
+ crate::failed(crate::map_control_error(error), request_id)
+ }
+ CollaborationCheckError::Failed(reason) => {
+ let code = match reason {
+ Reason::LoginRequired
+ | Reason::InstalledSkillMissing
+ | Reason::InstalledSkillChanged
+ | Reason::InstalledSkillInvalid
+ | Reason::NativeContextUnavailable
+ | Reason::NativeContextChanged
+ | Reason::DependencyUnavailable => ErrorCode::ActionRequired,
+ Reason::CheckTimedOut | Reason::VerificationFailed => {
+ ErrorCode::ObservationUnavailable
+ }
+ };
+ let mut error = ErrorV1::new(code);
+ error.details_schema = AGENT_COLLABORATION_CHECK_FAILURE_SCHEMA_V1.into();
+ MachineEnvelopeV2::failed_with_data(
+ error,
+ serde_json::to_value(AgentCollaborationCheckFailureV1::new(reason))
+ .expect("closed collaboration failure is serializable"),
+ Some(request_id),
+ )
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::control::ControlReadError;
+ use serde_json::json;
+
+ #[test]
+ fn native_check_failures_expose_only_closed_actionable_details() {
+ for (reason, wire, code) in [
+ (
+ Reason::LoginRequired,
+ "login_required",
+ ErrorCode::ActionRequired,
+ ),
+ (
+ Reason::InstalledSkillMissing,
+ "installed_skill_missing",
+ ErrorCode::ActionRequired,
+ ),
+ (
+ Reason::InstalledSkillChanged,
+ "installed_skill_changed",
+ ErrorCode::ActionRequired,
+ ),
+ (
+ Reason::CheckTimedOut,
+ "check_timed_out",
+ ErrorCode::ObservationUnavailable,
+ ),
+ (
+ Reason::VerificationFailed,
+ "verification_failed",
+ ErrorCode::ObservationUnavailable,
+ ),
+ ] {
+ let result = failed(
+ CollaborationCheckError::Failed(reason),
+ "request/check".into(),
+ );
+ assert_eq!(result.error.as_ref().unwrap().code, code);
+ assert_eq!(
+ result.error.as_ref().unwrap().details_schema,
+ "hiroute.agent-collaboration-check-failure/v1"
+ );
+ assert_eq!(
+ result.data,
+ Some(json!({
+ "schema":"hiroute.agent-collaboration-check-failure/v1", "reason":wire,
+ }))
+ );
+ }
+ }
+
+ #[test]
+ fn ordinary_control_failures_keep_the_previous_envelope() {
+ for error in [
+ ControlReadError::NotFound,
+ ControlReadError::Unavailable,
+ ControlReadError::Denied,
+ ] {
+ assert_eq!(
+ failed(error.into(), "request/check".into()),
+ crate::failed(crate::map_control_error(error), "request/check".into())
+ );
+ }
+ }
+}
diff --git a/crates/application/src/agent_connection/control.rs b/crates/application/src/agent_connection/control.rs
index 06a67d18..fa591624 100644
--- a/crates/application/src/agent_connection/control.rs
+++ b/crates/application/src/agent_connection/control.rs
@@ -56,12 +56,17 @@ pub(crate) fn check(
let target = request.target.as_ref().ok_or(ControlReadError::Corrupt)?;
if agent.context_id.as_deref() != Some(target.context_id.as_str())
|| match request.agent_id.as_str() {
- "agent_codex_default" => {
- target.surface == hiroute_application_api::AgentModelSurfaceV2::ClaudeCli
- }
+ "agent_codex_default" => !matches!(
+ target.surface,
+ hiroute_application_api::AgentModelSurfaceV2::CodexCli
+ | hiroute_application_api::AgentModelSurfaceV2::CodexDesktop
+ ),
"agent_claude_default" => {
target.surface != hiroute_application_api::AgentModelSurfaceV2::ClaudeCli
}
+ "agent_qoder_default" => {
+ target.surface != hiroute_application_api::AgentModelSurfaceV2::QoderCli
+ }
_ => true,
}
{
diff --git a/crates/application/src/agent_connection/mod.rs b/crates/application/src/agent_connection/mod.rs
index f2aa3f35..f03010c4 100644
--- a/crates/application/src/agent_connection/mod.rs
+++ b/crates/application/src/agent_connection/mod.rs
@@ -1,10 +1,12 @@
//! Typed AgentConnection Preview and Apply-plan sealing.
mod claude_model_journal;
+pub(crate) mod collaboration_check;
pub(crate) mod control;
mod login_item;
mod model_journal;
mod planner;
+mod qoder_model_journal;
mod restore;
mod revocation;
mod settings;
@@ -16,6 +18,7 @@ pub use claude_model_journal::*;
pub use login_item::*;
pub use model_journal::*;
pub use planner::*;
+pub use qoder_model_journal::*;
pub use restore::*;
pub use revocation::*;
pub use settings::*;
diff --git a/crates/application/src/agent_connection/planner.rs b/crates/application/src/agent_connection/planner.rs
index ceea62e6..d412e1b6 100644
--- a/crates/application/src/agent_connection/planner.rs
+++ b/crates/application/src/agent_connection/planner.rs
@@ -219,15 +219,18 @@ impl AgentConnectionPlanner {
.require_action(hiroute_domain::AgentAction::ConfigureModel)
.map_err(AgentConnectionPlanningError::UnprovenCapabilities)?;
let profile = &facts.installation.profile;
+ let protocol = profile
+ .model_connection()
+ .map_err(|_| AgentConnectionPlanningError::InvalidGrant)?
+ .ok_or(AgentConnectionPlanningError::InvalidGrant)?
+ .ingress_protocol;
let allowed_agent_plan_ids = match spec.allowed_scope {
AgentPlanAllowedScopeV1::Selected => spec.allowed_agent_plan_ids.clone(),
AgentPlanAllowedScopeV1::AllPublished if spec.allowed_agent_plan_ids.is_empty() => {
facts
.plans
.iter()
- .filter(|plan| {
- plan.active && plan.supported_ingress.contains(&profile.client_protocol())
- })
+ .filter(|plan| plan.active && plan.supported_ingress.contains(&protocol))
.map(|plan| plan.agent_plan_id.clone())
.collect()
}
@@ -236,7 +239,7 @@ impl AgentConnectionPlanner {
}
};
let grant = AgentPlanGrantV1::derive_with_scope(
- profile.client_protocol(),
+ protocol,
spec.allowed_scope,
spec.default_agent_plan_id.clone(),
allowed_agent_plan_ids,
@@ -267,8 +270,7 @@ impl AgentConnectionPlanner {
))
})
.collect::<Result<BTreeMap<_, _>, AgentConnectionPlanningError>>()?;
- let model_grant =
- hiroute_domain::AgentModelGrantV2::seal(profile.client_protocol(), routes)?;
+ let model_grant = hiroute_domain::AgentModelGrantV2::seal(protocol, routes)?;
let (catalog, overlay, catalog_delivery) = if spec.native_subagent_routing {
if !profile.native_subagent_routing {
@@ -277,8 +279,7 @@ impl AgentConnectionPlanner {
let delivery = profile
.catalog_delivery(spec.dynamic_catalog_available)
.ok_or(AgentConnectionPlanningError::CatalogUnavailable)?;
- let catalog =
- AgentPlanCatalogV1::from_grant(&grant, profile.client_protocol(), &facts.plans)?;
+ let catalog = AgentPlanCatalogV1::from_grant(&grant, protocol, &facts.plans)?;
let overlay = RoutingInstructionOverlayV1::render(&catalog)?;
(Some(catalog), Some(overlay), Some(delivery))
} else {
@@ -286,13 +287,9 @@ impl AgentConnectionPlanner {
};
let desired_config = match facts.activation_mode {
- AgentActivationModeV1::ManagedConfiguration => desired_config(
- profile.client_protocol(),
- &facts,
- &grant,
- catalog.as_ref(),
- catalog_delivery,
- )?,
+ AgentActivationModeV1::ManagedConfiguration => {
+ desired_config(protocol, &facts, &grant, catalog.as_ref(), catalog_delivery)?
+ }
AgentActivationModeV1::ManagedLaunch => BTreeMap::new(),
};
let writable = facts.installation.writable_values(&desired_config)?;
@@ -324,7 +321,7 @@ impl AgentConnectionPlanner {
agent_id: spec.agent_id.clone(),
profile_id: profile.profile_id.clone(),
integration_profile_ref: profile.integration_profile_ref.clone(),
- protocol: profile.client_protocol(),
+ protocol,
activation_mode: facts.activation_mode,
grant: grant.clone(),
native_subagent_routing: spec.native_subagent_routing,
@@ -365,7 +362,7 @@ impl AgentConnectionPlanner {
"guidance_result_digest": guidance_result_digest,
"config_change_digest": config_change.digest,
"integration_profile_ref": profile.integration_profile_ref,
- "protocol": profile.client_protocol(),
+ "protocol": protocol,
"activation_mode": facts.activation_mode,
"grant_digest": grant.digest,
"model_grant_digest": model_grant.digest,
diff --git a/crates/application/src/agent_connection/qoder_model_journal.rs b/crates/application/src/agent_connection/qoder_model_journal.rs
new file mode 100644
index 00000000..2fb63a72
--- /dev/null
+++ b/crates/application/src/agent_connection/qoder_model_journal.rs
@@ -0,0 +1,187 @@
+//! Non-secret additive Qoder model effects, bound to one settings Operation.
+use hiroute_domain::{
+ AgentConnectionControlIntentV1, AgentConnectionEffectRoleV1, AgentConnectionTransactionKindV1,
+ AgentFacetIntent, AgentIngressProtocolV1, AgentModelGrantV2, AgentModelRouteV2,
+ AgentModelSelectionV2, AgentOperationRead, AgentSettingsSpecV2, CanonicalDigest,
+ ExternalEffectIntentV1, OperationId, OperationValidationError, PortError, PortErrorCode,
+ PortResult, QoderAdditionalModelV1,
+};
+use serde::{Deserialize, Serialize};
+
+const SCHEMA: &str = "hiroute.settings-qoder-model-file/v1";
+
+#[derive(Clone, Debug, Deserialize, Serialize)]
+#[serde(tag = "action", rename_all = "snake_case", deny_unknown_fields)]
+pub enum QoderModelFileAction {
+ Configure {
+ previous_operation: Option<OperationId>,
+ provider_id: String,
+ endpoint: String,
+ models: Vec<QoderAdditionalModelV1>,
+ },
+ Restore {
+ original_operation: OperationId,
+ },
+}
+
+#[derive(Clone, Debug, Deserialize, Serialize)]
+#[serde(deny_unknown_fields)]
+pub struct QoderModelFilePayload {
+ schema: String,
+ pub context_id: String,
+ pub expected_content: CanonicalDigest,
+ pub change: QoderModelFileAction,
+}
+
+/// A stable, context-owned namespace. It never adopts an existing unowned provider.
+pub fn qoder_model_provider_id(context_id: &str) -> String {
+ let digest = CanonicalDigest::of_bytes(context_id.as_bytes());
+ format!("hiroute-main-{}", &digest.as_str()[7..])
+}
+
+pub fn settings_qoder_model_file_intent(
+ control: &AgentConnectionControlIntentV1,
+ context_id: &str,
+ expected_content: CanonicalDigest,
+ before_fingerprint: Option<CanonicalDigest>,
+ change: QoderModelFileAction,
+) -> Result<ExternalEffectIntentV1, OperationValidationError> {
+ if control.transaction() != AgentConnectionTransactionKindV1::Settings {
+ return Err(OperationValidationError::UnregisteredEffectPlan);
+ }
+ let payload = QoderModelFilePayload {
+ schema: SCHEMA.into(),
+ context_id: context_id.into(),
+ expected_content,
+ change,
+ };
+ let intent = ExternalEffectIntentV1::from_agent_connection_planner(
+ control,
+ AgentConnectionEffectRoleV1::ManagedConfiguration,
+ before_fingerprint,
+ &payload,
+ 0o600,
+ )?;
+ decode_settings_qoder_model_file(&intent)
+ .map_err(|_| OperationValidationError::UnregisteredEffectPlan)?;
+ Ok(intent)
+}
+
+pub fn decode_settings_qoder_model_file(
+ intent: &ExternalEffectIntentV1,
+) -> PortResult<QoderModelFilePayload> {
+ ExternalEffectIntentV1::from_registered_adapter(
+ intent.effect_id(),
+ intent.kind(),
+ intent.target(),
+ intent.before_fingerprint().cloned(),
+ intent.desired().clone(),
+ intent.desired_mode(),
+ intent.sensitive(),
+ )
+ .map_err(|_| invalid())?;
+ let value = intent.desired();
+ if intent.effect_id() != "agent-connection-managed-configuration"
+ || intent.desired_mode() != 0o600
+ || value["transaction"] != "settings"
+ || value["subject"]["agent_id"] != "agent_qoder_default"
+ || value["subject"]["profile_id"] != "qoder-collaboration-v1"
+ || value["subject"]["integration_profile_ref"] != "builtin/qoder-collaboration/v1"
+ {
+ return Err(invalid());
+ }
+ let payload: QoderModelFilePayload =
+ serde_json::from_value(value["payload"].clone()).map_err(|_| invalid())?;
+ if payload.schema != SCHEMA || !super::settings::identity(&payload.context_id) {
+ return Err(invalid());
+ }
+ match &payload.change {
+ QoderModelFileAction::Configure {
+ provider_id,
+ endpoint,
+ models,
+ ..
+ } => {
+ if provider_id != &qoder_model_provider_id(&payload.context_id)
+ || !local_endpoint(endpoint)
+ || models.is_empty()
+ || models.len() > 256
+ || models.iter().any(|model| model.validate().is_err())
+ || models.windows(2).any(|pair| pair[0].alias >= pair[1].alias)
+ {
+ return Err(invalid());
+ }
+ }
+ QoderModelFileAction::Restore { .. } => {}
+ }
+ Ok(payload)
+}
+
+pub fn settings_qoder_model_file_for_operation(
+ operation: &(impl AgentOperationRead + ?Sized),
+ intent: &ExternalEffectIntentV1,
+) -> PortResult<QoderModelFilePayload> {
+ let payload = decode_settings_qoder_model_file(intent)?;
+ let spec: AgentSettingsSpecV2 =
+ serde_json::from_value(operation.agent_input().spec.desired_state.clone())
+ .map_err(|_| invalid())?;
+ if operation.agent_input().spec.command_id != "agents.settings.apply"
+ || spec.context_id != payload.context_id
+ || !operation.agent_input().external.contains(intent)
+ || spec.restore_native_model.is_some()
+ {
+ return Err(invalid());
+ }
+ let state = &operation.agent_input().control["payload"]["state"];
+ if state["accept_digest"]
+ != serde_json::to_value(operation.accepted_digest()).map_err(|_| invalid())?
+ {
+ return Err(invalid());
+ }
+ match (&spec.model, &payload.change) {
+ (
+ AgentFacetIntent::Configure {
+ settings: AgentModelSelectionV2::QoderAdditional { allowed_plan_ids },
+ },
+ QoderModelFileAction::Configure {
+ previous_operation,
+ models,
+ ..
+ },
+ ) => {
+ let grant: AgentModelGrantV2 =
+ serde_json::from_value(state["model_grant"].clone()).map_err(|_| invalid())?;
+ let [mutation] = operation.agent_input().grants else {
+ return Err(invalid());
+ };
+ let scope = mutation.desired_scope().ok_or_else(invalid)?;
+ if scope.model_grant() != &grant || grant.protocol != AgentIngressProtocolV1::Responses
+ || previous_operation.as_ref() == Some(operation.operation_id())
+ || models.len() != grant.routes.len() || models.len() != allowed_plan_ids.len()
+ || !models.iter().all(|model| matches!(grant.routes.get(&model.alias), Some(AgentModelRouteV2::Plan { plan_id, alias, .. }) if allowed_plan_ids.contains(plan_id) && alias.as_str() == model.alias))
+ { return Err(invalid()); }
+ }
+ (
+ AgentFacetIntent::Restore { restore_point_ref },
+ QoderModelFileAction::Restore { original_operation },
+ ) if original_operation != operation.operation_id()
+ && *restore_point_ref == super::codex_model_restore_point_ref(original_operation) => {}
+ _ => return Err(invalid()),
+ }
+ Ok(payload)
+}
+
+fn local_endpoint(value: &str) -> bool {
+ value
+ .strip_prefix("http://127.0.0.1:")
+ .or_else(|| value.strip_prefix("http://[::1]:"))
+ .and_then(|rest| rest.strip_suffix(hiroute_domain::QODER_MODEL_BASE_PATH))
+ .is_some_and(|port| {
+ !port.is_empty()
+ && port.bytes().all(|b| b.is_ascii_digit())
+ && port.parse::<u16>().is_ok_and(|p| p != 0)
+ })
+}
+fn invalid() -> PortError {
+ PortError::new(PortErrorCode::InvalidData, "qoder.settings.intent")
+}
diff --git a/crates/application/src/agent_connection/settings.rs b/crates/application/src/agent_connection/settings.rs
index 12470fb4..2aa07097 100644
--- a/crates/application/src/agent_connection/settings.rs
+++ b/crates/application/src/agent_connection/settings.rs
@@ -12,12 +12,21 @@ use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet};
pub struct AgentSettingsFacts {
- pub codex_context_override: bool,
- pub claude_context_override: bool,
- pub claude_plan_capability_unavailable: bool,
pub context_id: String,
pub dependency_digest: CanonicalDigest,
pub capabilities: AgentCapabilitySet,
+ /// No model facts or configuration target are needed by collaboration-only installations.
+ pub model: Option<SettingsModelFacts>,
+ pub collaboration_file_conflict: bool,
+ pub restore_points: BTreeMap<String, AgentSettingsFacet>,
+}
+
+pub struct SettingsModelFacts {
+ /// A closed native field conflict; only Qoder model changes consume this fact.
+ pub qoder_model_conflict: Option<SettingsBlockReason>,
+ pub codex_context_override: bool,
+ pub claude_context_override: bool,
+ pub claude_plan_capability_unavailable: bool,
pub ingress: AgentIngressProtocolV1,
pub available_surfaces: BTreeSet<hiroute_domain::AgentModelSurfaceV2>,
pub model_publication: Option<GatewayPublicationV1>,
@@ -56,10 +65,6 @@ pub struct AgentSettingsFacts {
/// Model that an unmodified restore would leave in the native configuration.
pub restored_native_model: Option<String>,
pub native_claude_presets: Option<hiroute_domain::AgentClaudePresetValuesV2>,
- /// Preview-time ownership check for an existing collaboration Skill file.
- pub collaboration_file_conflict: bool,
- /// Only restoration points owned by this context, projected from the protected store.
- pub restore_points: BTreeMap<String, AgentSettingsFacet>,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
@@ -113,6 +118,8 @@ pub struct AgentSettingsBlock {
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum SettingsBlockReason {
+ QoderDefaultInUse,
+ QoderModelFileConflict,
CodexContextOverride,
ClaudeContextOverride,
ClaudePlanCapabilityUnavailable,
@@ -149,6 +156,13 @@ pub fn preview_agent_settings(
{
return Err(SettingsPlanningError::InvalidContext);
}
+ if facts.model.is_none()
+ && (!matches!(spec.model, AgentFacetIntent::Keep)
+ || !matches!(spec.access_token, AgentAccessTokenIntentV1::Keep)
+ || spec.restore_native_model.is_some())
+ {
+ return Err(SettingsPlanningError::InvalidSelection);
+ }
if spec.restore_native_model.is_some()
&& !matches!(&spec.model, AgentFacetIntent::Restore { .. })
{
@@ -159,34 +173,63 @@ pub fn preview_agent_settings(
{
return Err(SettingsPlanningError::InvalidSelection);
}
- spec.protected_native_model_ids = if facts.require_native_model_routes {
- facts.required_native_model_ids.clone().unwrap_or_default()
- } else {
- Vec::new()
- };
- if let AgentFacetIntent::Configure {
- settings: AgentModelSelectionV2::CodexDefault { fixed_models, .. },
- } = &mut spec.model
- {
- for preserved in &facts.preserved_codex_models {
- if !fixed_models
- .iter()
- .any(|selected| selected.client_model_id == preserved.client_model_id)
- {
- fixed_models.push(preserved.clone());
+ spec.protected_native_model_ids.clear();
+ if let Some(model) = &facts.model {
+ spec.protected_native_model_ids = if model.require_native_model_routes {
+ model.required_native_model_ids.clone().unwrap_or_default()
+ } else {
+ Vec::new()
+ };
+ if let AgentFacetIntent::Configure {
+ settings: AgentModelSelectionV2::CodexDefault { fixed_models, .. },
+ } = &mut spec.model
+ {
+ for preserved in &model.preserved_codex_models {
+ if !fixed_models
+ .iter()
+ .any(|selected| selected.client_model_id == preserved.client_model_id)
+ {
+ fixed_models.push(preserved.clone());
+ }
}
+ fixed_models.sort_by(|left, right| left.client_model_id.cmp(&right.client_model_id));
}
- fixed_models.sort_by(|left, right| left.client_model_id.cmp(&right.client_model_id));
}
let mut changed_facets = BTreeSet::new();
let mut blockers = Vec::new();
+ if let Some(reason) = facts
+ .model
+ .as_ref()
+ .and_then(|model| model.qoder_model_conflict)
+ {
+ if !matches!(
+ reason,
+ SettingsBlockReason::QoderDefaultInUse | SettingsBlockReason::QoderModelFileConflict
+ ) {
+ return Err(SettingsPlanningError::InvalidSelection);
+ }
+ blockers.push(AgentSettingsBlock {
+ facet: AgentSettingsFacet::Model,
+ reason,
+ capabilities: Vec::new(),
+ model_ids: Vec::new(),
+ });
+ }
let mut model_grant = None;
let mut collaboration_trigger_mode = None;
match &spec.model {
AgentFacetIntent::Keep => {}
AgentFacetIntent::Configure { settings } => {
+ let model = facts
+ .model
+ .as_ref()
+ .ok_or(SettingsPlanningError::InvalidSelection)?;
changed_facets.insert(AgentSettingsFacet::Model);
- if matches!(settings, AgentModelSelectionV2::CodexDefault { .. }) {
+ if matches!(
+ settings,
+ AgentModelSelectionV2::CodexDefault { .. }
+ | AgentModelSelectionV2::QoderAdditional { .. }
+ ) {
// A short-lived isolated HTTP challenge diagnoses a native client; it is not
// authorization to write a safely observed Codex configuration. Actual client
// calls have independent per-surface verification results.
@@ -216,17 +259,24 @@ pub fn preview_agent_settings(
&mut blockers,
);
}
+ if matches!(settings, AgentModelSelectionV2::QoderAdditional { .. })
+ && !model
+ .available_surfaces
+ .contains(&hiroute_domain::AgentModelSurfaceV2::QoderCli)
+ {
+ return Err(SettingsPlanningError::InvalidSelection);
+ }
settings
.validate()
.map_err(|_| SettingsPlanningError::InvalidSelection)?;
if let AgentModelSelectionV2::ClaudeLauncher { surfaces, .. } = settings
- && !surfaces.is_subset(&facts.available_surfaces)
+ && !surfaces.is_subset(&model.available_surfaces)
{
return Err(SettingsPlanningError::InvalidSelection);
}
if matches!(settings, AgentModelSelectionV2::CodexDefault { .. })
&& !settings.allowed_plan_ids().is_empty()
- && facts.codex_context_override
+ && model.codex_context_override
{
blockers.push(AgentSettingsBlock {
facet: AgentSettingsFacet::Model,
@@ -235,13 +285,13 @@ pub fn preview_agent_settings(
model_ids: Vec::new(),
});
}
- let grant = derive_model_grant(settings, facts);
+ let grant = derive_model_grant(settings, model);
match grant {
Ok(grant) => {
// Every Codex selection publishes one exact client catalog, including
// HiRoute-only fixed routes without a Plan.
if matches!(settings, AgentModelSelectionV2::CodexDefault { .. })
- && facts.model_catalog.is_none()
+ && model.model_catalog.is_none()
{
blockers.push(AgentSettingsBlock {
facet: AgentSettingsFacet::Model,
@@ -254,11 +304,11 @@ pub fn preview_agent_settings(
model_ids: Vec::new(),
});
}
- if let Some(required) = &facts.required_native_model_ids {
+ if let Some(required) = &model.required_native_model_ids {
let missing = required
.iter()
.filter(|name| {
- !facts.preserved_codex_models.iter().any(|preserved| {
+ !model.preserved_codex_models.iter().any(|preserved| {
preserved.client_model_id == name.as_str()
&& settings
.fixed_models()
@@ -268,7 +318,7 @@ pub fn preview_agent_settings(
})
.cloned()
.collect::<Vec<_>>();
- if facts.require_native_model_routes
+ if model.require_native_model_routes
&& (required.is_empty() || !missing.is_empty())
{
blockers.push(AgentSettingsBlock {
@@ -278,8 +328,8 @@ pub fn preview_agent_settings(
model_ids: missing,
});
}
- if facts.native_default_must_be_original
- && facts
+ if model.native_default_must_be_original
+ && model
.native_default_model
.as_ref()
.is_some_and(|default| !required.contains(default))
@@ -288,7 +338,7 @@ pub fn preview_agent_settings(
facet: AgentSettingsFacet::Model,
reason: SettingsBlockReason::NativeDefaultInvalid,
capabilities: Vec::new(),
- model_ids: facts.native_default_model.iter().cloned().collect(),
+ model_ids: model.native_default_model.iter().cloned().collect(),
});
}
}
@@ -303,6 +353,10 @@ pub fn preview_agent_settings(
}
}
AgentFacetIntent::Restore { restore_point_ref } => {
+ let model = facts
+ .model
+ .as_ref()
+ .ok_or(SettingsPlanningError::InvalidSelection)?;
changed_facets.insert(AgentSettingsFacet::Model);
restore(
facts,
@@ -311,12 +365,17 @@ pub fn preview_agent_settings(
restore_point_ref,
&mut blockers,
);
- if facts.ingress == AgentIngressProtocolV1::Responses && !facts.restore_inherits_root {
+ if model.ingress == AgentIngressProtocolV1::Responses
+ && !model.restore_inherits_root
+ && !model
+ .available_surfaces
+ .contains(&hiroute_domain::AgentModelSurfaceV2::QoderCli)
+ {
let chosen = spec
.restore_native_model
.as_ref()
- .or(facts.restored_native_model.as_ref());
- let valid = facts
+ .or(model.restored_native_model.as_ref());
+ let valid = model
.restore_native_model_ids
.as_ref()
.is_some_and(|models| {
@@ -327,7 +386,7 @@ pub fn preview_agent_settings(
facet: AgentSettingsFacet::Model,
reason: SettingsBlockReason::RestoreNativeModelInvalid,
capabilities: Vec::new(),
- model_ids: facts.restored_native_model.iter().cloned().collect(),
+ model_ids: model.restored_native_model.iter().cloned().collect(),
});
}
} else if spec.restore_native_model.is_some() {
@@ -404,7 +463,15 @@ pub fn preview_agent_settings(
.collect::<Vec<_>>();
let context_windows = match model_grant
.as_ref()
- .map(|grant| plan_context_windows(grant, facts.model_publication.as_ref()))
+ .map(|grant| {
+ plan_context_windows(
+ grant,
+ facts
+ .model
+ .as_ref()
+ .and_then(|model| model.model_publication.as_ref()),
+ )
+ })
.transpose()
{
Ok(windows) => windows.unwrap_or_default(),
@@ -425,7 +492,11 @@ pub fn preview_agent_settings(
}
) && !context_windows.is_empty()
{
- if facts.claude_plan_capability_unavailable {
+ let model = facts
+ .model
+ .as_ref()
+ .ok_or(SettingsPlanningError::InvalidSelection)?;
+ if model.claude_plan_capability_unavailable {
blockers.push(AgentSettingsBlock {
facet: AgentSettingsFacet::Model,
reason: SettingsBlockReason::ClaudePlanCapabilityUnavailable,
@@ -438,10 +509,10 @@ pub fn preview_agent_settings(
.copied()
.min()
.and_then(hiroute_domain::claude_context_window);
- if facts.claude_context_override || window.is_none() {
+ if model.claude_context_override || window.is_none() {
blockers.push(AgentSettingsBlock {
facet: AgentSettingsFacet::Model,
- reason: if facts.claude_context_override {
+ reason: if model.claude_context_override {
SettingsBlockReason::ClaudeContextOverride
} else {
SettingsBlockReason::ClaudeContextWindowUnsupported
@@ -477,13 +548,17 @@ pub fn preview_agent_settings(
model_grant,
collaboration_trigger_mode,
blockers,
- unproven_native_model_ids: facts.unproven_native_model_ids.clone(),
+ unproven_native_model_ids: facts
+ .model
+ .as_ref()
+ .map(|model| model.unproven_native_model_ids.clone())
+ .unwrap_or_default(),
})
}
fn derive_model_grant(
settings: &AgentModelSelectionV2,
- facts: &AgentSettingsFacts,
+ facts: &SettingsModelFacts,
) -> Result<AgentModelGrantV2, SettingsPlanningError> {
let invalid = || SettingsPlanningError::InvalidSelection;
let ordinary_fixed = settings
@@ -522,7 +597,7 @@ fn derive_model_grant(
fn validate_model_default(
settings: &AgentModelSelectionV2,
- facts: &AgentSettingsFacts,
+ facts: &SettingsModelFacts,
grant: &AgentModelGrantV2,
) -> Result<(), SettingsPlanningError> {
let invalid = || SettingsPlanningError::InvalidSelection;
@@ -536,6 +611,7 @@ fn validate_model_default(
.then_some(name.as_str())
}),
},
+ AgentModelSelectionV2::QoderAdditional { .. } => return Ok(()),
AgentModelSelectionV2::ClaudeLauncher { .. } => {
claude_presets = grant
.claude_preset_values(
diff --git a/crates/application/src/agent_connection/settings/collaboration_only_tests.rs b/crates/application/src/agent_connection/settings/collaboration_only_tests.rs
new file mode 100644
index 00000000..755544d3
--- /dev/null
+++ b/crates/application/src/agent_connection/settings/collaboration_only_tests.rs
@@ -0,0 +1,146 @@
+//! The collaboration capability has its own confirmation and effects, with no model shell.
+use super::*;
+use crate::agent_connection::{
+ AgentSettingsPlanningInput, CollaborationSkillTemplate, SettingsSkillFileFacts,
+};
+use hiroute_application_api::AgentSettingsApplyV2;
+use hiroute_domain::{AgentConnectionTransactionSubjectV1, RevisionSetV1};
+
+fn collaboration_spec() -> AgentSettingsSpecV2 {
+ serde_json::from_value(json!({
+ "schema_version":{"major":2,"minor":0},"context_id":"agent-context/test",
+ "collaboration":{"intent":"configure","settings":{"trigger_mode":"explicit"}}
+ }))
+ .unwrap()
+}
+
+fn input(facts: AgentSettingsFacts) -> AgentSettingsPlanningInput {
+ AgentSettingsPlanningInput {
+ collaboration_state: json!({"trigger_mode":"explicit"}),
+ facts,
+ expected_revisions: RevisionSetV1 {
+ target: 0,
+ dependencies: BTreeMap::new(),
+ },
+ subject: AgentConnectionTransactionSubjectV1::from_registered_profile(
+ "agent_qoder_default",
+ "default",
+ "builtin/qoder-collaboration/v1",
+ )
+ .unwrap(),
+ model_file: None,
+ skill_file: SettingsSkillFileFacts {
+ root_ref: "skill-root/qoder".into(),
+ target: "/selected/qoder/skills/hiroute-collaboration/SKILL.md".into(),
+ before: None,
+ observed_file: None,
+ before_fingerprint: None,
+ template: CollaborationSkillTemplate::bundled("fixture/v1", "# Collaboration\n")
+ .unwrap(),
+ },
+ }
+}
+
+fn confirm(spec: AgentSettingsSpecV2, facts: &AgentSettingsFacts) -> ConfirmedAgentSettings {
+ let preview = preview_agent_settings(spec.clone(), facts).unwrap();
+ confirm_agent_settings(
+ AgentSettingsApplyV2 {
+ expected_revisions: RevisionSetV1 {
+ target: 0,
+ dependencies: BTreeMap::new(),
+ },
+ spec,
+ accept_digest: preview.accept_digest,
+ dependency_digest: preview.dependency_digest,
+ idempotency_key: "collaboration-only-confirmation".into(),
+ login_item: None,
+ },
+ facts,
+ )
+ .unwrap()
+}
+
+#[test]
+fn collaboration_only_confirmation_seals_only_the_skill_effect_without_model_facts() {
+ let mut fresh = facts();
+ fresh.model = None;
+ let confirmed = confirm(collaboration_spec(), &fresh);
+ assert!(confirmed.preview().model_grant.is_none());
+ assert!(confirmed.preview().context_windows.is_empty());
+ let plan = input(fresh).seal_settings(&confirmed).unwrap();
+ assert_eq!(plan.external().len(), 1);
+ assert!(plan.agent_access_grants().is_empty());
+ assert!(plan.secrets().is_empty());
+ assert!(plan.runtime().is_empty());
+ assert_eq!(plan.spec().desired_state["model"]["intent"], "keep");
+ assert!(plan.control()["payload"]["state"]["model_grant"].is_null());
+}
+
+#[test]
+fn collaboration_only_preview_rejects_every_model_mutation() {
+ let mut fresh = facts();
+ fresh.model = None;
+ let baseline = collaboration_spec();
+ for model in [
+ json!({"intent":"restore","restore_point_ref":"restore/model"}),
+ json!({"intent":"configure","settings":{
+ "mode":"codex_default","native_model_mode":"hiroute_only", "fixed_models":[],
+ "allowed_plan_ids":[], "default_selection":{"kind":"preserve_native"}
+ }}),
+ ] {
+ let mut wire = serde_json::to_value(&baseline).unwrap();
+ wire["model"] = model;
+ let spec = serde_json::from_value(wire).unwrap();
+ assert_eq!(
+ preview_agent_settings(spec, &fresh).unwrap_err(),
+ SettingsPlanningError::InvalidSelection
+ );
+ }
+ for access_token in [
+ hiroute_domain::AgentAccessTokenIntentV1::Regenerate,
+ hiroute_domain::AgentAccessTokenIntentV1::Set {
+ input_slot: "token/input".into(),
+ },
+ ] {
+ let mut spec = baseline.clone();
+ spec.access_token = access_token;
+ assert_eq!(
+ preview_agent_settings(spec, &fresh).unwrap_err(),
+ SettingsPlanningError::InvalidSelection
+ );
+ }
+}
+
+#[test]
+fn sealing_rechecks_model_support_even_for_a_previously_confirmed_restore() {
+ let mut fresh = facts();
+ let proof = CapabilityEvidence {
+ capability: AgentCapability::EffectiveConfiguration,
+ state: CapabilityState::Proven,
+ adapter_contract: "fixture/restore".into(),
+ observed_at_unix_ms: 1,
+ dependency_digest: fresh.dependency_digest.clone(),
+ reason: None,
+ };
+ fresh.capabilities = AgentCapabilitySet::new([
+ proof.clone(),
+ CapabilityEvidence {
+ capability: AgentCapability::AtomicManagedReplace,
+ ..proof
+ },
+ ])
+ .unwrap();
+ fresh
+ .restore_points
+ .insert("restore/model".into(), AgentSettingsFacet::Model);
+ let mut spec = collaboration_spec();
+ spec.collaboration = AgentFacetIntent::Keep;
+ spec.model = AgentFacetIntent::Restore {
+ restore_point_ref: "restore/model".into(),
+ };
+ let confirmed = confirm(spec, &fresh);
+ // Even if a buggy facts provider retained a digest, the absent model facet cannot be
+ // converted into model file/grant effects or a default configuration target.
+ fresh.model = None;
+ assert!(input(fresh).seal_settings(&confirmed).is_err());
+}
diff --git a/crates/application/src/agent_connection/settings/tests.rs b/crates/application/src/agent_connection/settings/tests.rs
index 8fa0c744..7cdddc04 100644
--- a/crates/application/src/agent_connection/settings/tests.rs
+++ b/crates/application/src/agent_connection/settings/tests.rs
@@ -24,39 +24,49 @@ fn facts() -> AgentSettingsFacts {
)
.unwrap();
AgentSettingsFacts {
- codex_context_override: false,
- claude_context_override: false,
- claude_plan_capability_unavailable: false,
context_id: "agent-context/test".into(),
dependency_digest,
capabilities,
- ingress: hiroute_domain::AgentIngressProtocolV1::Messages,
- available_surfaces: [
- hiroute_domain::AgentModelSurfaceV2::CodexCli,
- hiroute_domain::AgentModelSurfaceV2::CodexDesktop,
- hiroute_domain::AgentModelSurfaceV2::ClaudeCli,
- ]
- .into(),
- model_publication: None,
- model_catalog: None,
- login_item_required: false,
- login_item_removal_required: false,
- fixed_candidate_facts: Vec::new(),
- preserved_codex_models: Vec::new(),
- preserved_codex_bindings: BTreeMap::new(),
- required_native_model_ids: None,
- unproven_native_model_ids: Vec::new(),
- require_native_model_routes: false,
- native_default_must_be_original: false,
- native_default_model: None,
- restore_native_model_ids: None,
- restore_inherits_root: false,
- restored_native_model: None,
- native_claude_presets: None,
collaboration_file_conflict: false,
restore_points: BTreeMap::new(),
+ model: Some(SettingsModelFacts {
+ qoder_model_conflict: None,
+ codex_context_override: false,
+ claude_context_override: false,
+ claude_plan_capability_unavailable: false,
+ ingress: hiroute_domain::AgentIngressProtocolV1::Messages,
+ available_surfaces: [
+ hiroute_domain::AgentModelSurfaceV2::CodexCli,
+ hiroute_domain::AgentModelSurfaceV2::CodexDesktop,
+ hiroute_domain::AgentModelSurfaceV2::ClaudeCli,
+ ]
+ .into(),
+ model_publication: None,
+ model_catalog: None,
+ login_item_required: false,
+ login_item_removal_required: false,
+ fixed_candidate_facts: Vec::new(),
+ preserved_codex_models: Vec::new(),
+ preserved_codex_bindings: BTreeMap::new(),
+ required_native_model_ids: None,
+ unproven_native_model_ids: Vec::new(),
+ require_native_model_routes: false,
+ native_default_must_be_original: false,
+ native_default_model: None,
+ restore_native_model_ids: None,
+ restore_inherits_root: false,
+ restored_native_model: None,
+ native_claude_presets: None,
+ }),
}
}
+fn model(facts: &mut AgentSettingsFacts) -> &mut SettingsModelFacts {
+ facts
+ .model
+ .as_mut()
+ .expect("this fixture supports model settings")
+}
+
#[test]
fn claude_default_coverage_resolves_all_three_presets_without_changing_selection() {
use hiroute_domain::{
@@ -88,22 +98,31 @@ fn claude_default_coverage_resolves_all_three_presets_without_changing_selection
},
};
let mut current = facts();
- current.native_claude_presets = Some(AgentClaudePresetValuesV2 {
+ model(&mut current).native_claude_presets = Some(AgentClaudePresetValuesV2 {
opus: Some("native-opus".into()),
sonnet: None,
haiku: Some("native-haiku".into()),
});
for default in ["opus", "sonnet", "haiku", "hiroute-shared", "default"] {
- current.native_default_model = Some(default.into());
- assert_eq!(validate_model_default(&selection, &current, &grant), Ok(()));
- assert_eq!(current.native_default_model.as_deref(), Some(default));
+ model(&mut current).native_default_model = Some(default.into());
+ assert_eq!(
+ validate_model_default(&selection, current.model.as_ref().unwrap(), &grant),
+ Ok(())
+ );
+ assert_eq!(
+ model(&mut current).native_default_model.as_deref(),
+ Some(default)
+ );
}
- current.native_default_model = None;
- assert_eq!(validate_model_default(&selection, &current, &grant), Ok(()));
+ model(&mut current).native_default_model = None;
+ assert_eq!(
+ validate_model_default(&selection, current.model.as_ref().unwrap(), &grant),
+ Ok(())
+ );
for default in [Some("uncovered-native"), Some("opus[1m]")] {
- current.native_default_model = default.map(str::to_owned);
+ model(&mut current).native_default_model = default.map(str::to_owned);
assert_eq!(
- validate_model_default(&selection, &current, &grant),
+ validate_model_default(&selection, current.model.as_ref().unwrap(), &grant),
Err(SettingsPlanningError::InvalidSelection)
);
}
@@ -115,17 +134,20 @@ fn claude_default_coverage_resolves_all_three_presets_without_changing_selection
preset_mappings.sonnet = AgentClaudePresetSelectionV2::PreserveNative;
}
for default in ["opus", "sonnet"] {
- current.native_default_model = Some(default.into());
+ model(&mut current).native_default_model = Some(default.into());
assert_eq!(
- validate_model_default(&selection, &current, &grant),
+ validate_model_default(&selection, current.model.as_ref().unwrap(), &grant),
Err(SettingsPlanningError::InvalidSelection)
);
}
- current.native_default_model = Some("haiku".into());
- assert_eq!(validate_model_default(&selection, &current, &grant), Ok(()));
- current.native_claude_presets = None;
+ model(&mut current).native_default_model = Some("haiku".into());
+ assert_eq!(
+ validate_model_default(&selection, current.model.as_ref().unwrap(), &grant),
+ Ok(())
+ );
+ model(&mut current).native_claude_presets = None;
assert_eq!(
- validate_model_default(&selection, &current, &grant),
+ validate_model_default(&selection, current.model.as_ref().unwrap(), &grant),
Err(SettingsPlanningError::InvalidSelection)
);
}
@@ -225,12 +247,13 @@ fn agent_settings_restore_reference_cannot_cross_context_or_facet() {
#[test]
fn codex_restore_requires_an_original_catalog_model_for_a_stale_alias() {
let mut facts = facts();
- facts.ingress = AgentIngressProtocolV1::Responses;
+ model(&mut facts).ingress = AgentIngressProtocolV1::Responses;
facts
.restore_points
.insert("restore/owned".into(), AgentSettingsFacet::Model);
- facts.restore_native_model_ids = Some(vec!["gpt-5.6-sol".into(), "gpt-5.6-luna".into()]);
- facts.restored_native_model = Some("hiroute-fanyi".into());
+ model(&mut facts).restore_native_model_ids =
+ Some(vec!["gpt-5.6-sol".into(), "gpt-5.6-luna".into()]);
+ model(&mut facts).restored_native_model = Some("hiroute-fanyi".into());
let mut spec: AgentSettingsSpecV2 = serde_json::from_value(json!({
"schema_version": {"major": 2, "minor": 0},
"context_id": "agent-context/test",
@@ -435,36 +458,39 @@ fn codex_plan_selections_preview_only_with_catalog_facts() {
)
.unwrap();
AgentSettingsFacts {
- codex_context_override: false,
- claude_context_override: false,
- claude_plan_capability_unavailable: false,
context_id: "agent-context/test".into(),
dependency_digest,
capabilities,
- ingress: AgentIngressProtocolV1::Responses,
- available_surfaces: [
- hiroute_domain::AgentModelSurfaceV2::CodexCli,
- hiroute_domain::AgentModelSurfaceV2::CodexDesktop,
- ]
- .into(),
- model_publication: Some(publication.clone()),
- model_catalog,
- login_item_required: false,
- login_item_removal_required: false,
- fixed_candidate_facts: Vec::new(),
- preserved_codex_models: Vec::new(),
- preserved_codex_bindings: BTreeMap::new(),
- required_native_model_ids: None,
- unproven_native_model_ids: Vec::new(),
- require_native_model_routes: false,
- native_default_must_be_original: false,
- native_default_model: None,
- restore_native_model_ids: None,
- restore_inherits_root: false,
- restored_native_model: None,
- native_claude_presets: None,
collaboration_file_conflict: false,
restore_points: BTreeMap::new(),
+ model: Some(SettingsModelFacts {
+ qoder_model_conflict: None,
+ codex_context_override: false,
+ claude_context_override: false,
+ claude_plan_capability_unavailable: false,
+ ingress: AgentIngressProtocolV1::Responses,
+ available_surfaces: [
+ hiroute_domain::AgentModelSurfaceV2::CodexCli,
+ hiroute_domain::AgentModelSurfaceV2::CodexDesktop,
+ ]
+ .into(),
+ model_publication: Some(publication.clone()),
+ model_catalog,
+ login_item_required: false,
+ login_item_removal_required: false,
+ fixed_candidate_facts: Vec::new(),
+ preserved_codex_models: Vec::new(),
+ preserved_codex_bindings: BTreeMap::new(),
+ required_native_model_ids: None,
+ unproven_native_model_ids: Vec::new(),
+ require_native_model_routes: false,
+ native_default_must_be_original: false,
+ native_default_model: None,
+ restore_native_model_ids: None,
+ restore_inherits_root: false,
+ restored_native_model: None,
+ native_claude_presets: None,
+ }),
}
};
let catalog_block = |reason: hiroute_domain::CapabilityBlockReason| AgentSettingsBlock {
@@ -529,13 +555,13 @@ fn codex_plan_selections_preview_only_with_catalog_facts() {
producer_context_digest: CanonicalDigest::of_bytes(b"codex-context"),
producer_dependency_digest: CanonicalDigest::of_bytes(b"catalog-dependencies"),
}));
- no_detected_surface.available_surfaces.clear();
+ model(&mut no_detected_surface).available_surfaces.clear();
let without_client =
preview_agent_settings(spec(plan_selection.clone()), &no_detected_surface).unwrap();
assert!(without_client.blockers.is_empty());
assert!(without_client.model_grant.is_some());
- no_detected_surface.codex_context_override = true;
+ model(&mut no_detected_surface).codex_context_override = true;
let conflict =
preview_agent_settings(spec(plan_selection.clone()), &no_detected_surface).unwrap();
assert!(
@@ -559,7 +585,7 @@ fn codex_plan_selections_preview_only_with_catalog_facts() {
let mut preserve_plan_alias = plan_selection.clone();
preserve_plan_alias["native_model_mode"] = json!("preserve_available");
preserve_plan_alias["default_selection"] = json!({"kind": "preserve_native"});
- proven_facts.native_default_model = Some(plan.model_alias.as_str().into());
+ model(&mut proven_facts).native_default_model = Some(plan.model_alias.as_str().into());
let matched_alias =
preview_agent_settings(spec(preserve_plan_alias.clone()), &proven_facts).unwrap();
assert!(matched_alias.blockers.is_empty());
@@ -570,14 +596,14 @@ fn codex_plan_selections_preview_only_with_catalog_facts() {
.permits_name(plan.model_alias.as_str()),
"an explicitly allowed plan covers the same current Codex default alias"
);
- proven_facts.native_default_model = Some("hiroute-unpublished".into());
+ model(&mut proven_facts).native_default_model = Some("hiroute-unpublished".into());
let unmatched_alias = preview_agent_settings(spec(preserve_plan_alias), &proven_facts).unwrap();
assert_eq!(
unmatched_alias.blockers[0].reason,
SettingsBlockReason::ModelPlanUnavailable,
"an unrelated default name still cannot be published"
);
- proven_facts.native_default_model = None;
+ model(&mut proven_facts).native_default_model = None;
let candidates = crate::compiler::test_fixtures::compilation_facts().candidates;
let candidate = candidates
.iter()
@@ -598,15 +624,15 @@ fn codex_plan_selections_preview_only_with_catalog_facts() {
}),
},
};
- proven_facts.fixed_candidate_facts = vec![candidate, replacement_candidate.clone()];
- proven_facts.preserved_codex_models = vec![preserved.clone()];
- proven_facts.native_default_model = Some(preserved.client_model_id.clone());
- proven_facts.required_native_model_ids = Some(vec![
+ model(&mut proven_facts).fixed_candidate_facts = vec![candidate, replacement_candidate.clone()];
+ model(&mut proven_facts).preserved_codex_models = vec![preserved.clone()];
+ model(&mut proven_facts).native_default_model = Some(preserved.client_model_id.clone());
+ model(&mut proven_facts).required_native_model_ids = Some(vec![
preserved.client_model_id.clone(),
"native-unselected".into(),
]);
- proven_facts.require_native_model_routes = true;
- proven_facts.native_default_must_be_original = true;
+ model(&mut proven_facts).require_native_model_routes = true;
+ model(&mut proven_facts).native_default_must_be_original = true;
let mut preserve_selection = plan_selection.clone();
preserve_selection["native_model_mode"] = json!("preserve_available");
let incomplete =
@@ -615,15 +641,16 @@ fn codex_plan_selections_preview_only_with_catalog_facts() {
block.reason == SettingsBlockReason::NativeModelCoverageUnavailable
&& block.model_ids == ["native-unselected"]
}));
- proven_facts.required_native_model_ids = Some(vec![preserved.client_model_id.clone()]);
- proven_facts.native_default_model = Some(plan.model_alias.as_str().into());
+ model(&mut proven_facts).required_native_model_ids =
+ Some(vec![preserved.client_model_id.clone()]);
+ model(&mut proven_facts).native_default_model = Some(plan.model_alias.as_str().into());
let stale_default =
preview_agent_settings(spec(preserve_selection.clone()), &proven_facts).unwrap();
assert!(stale_default.blockers.iter().any(|block| {
block.reason == SettingsBlockReason::NativeDefaultInvalid
&& block.model_ids == [plan.model_alias.as_str()]
}));
- proven_facts.native_default_model = Some(preserved.client_model_id.clone());
+ model(&mut proven_facts).native_default_model = Some(preserved.client_model_id.clone());
let mut replacing = preserve_selection.clone();
let mut replaced = preserved.clone();
replaced.candidate.binding_id = replacement_candidate.binding.binding_id.clone();
@@ -641,7 +668,8 @@ fn codex_plan_selections_preview_only_with_catalog_facts() {
};
assert_eq!(fixed_models, std::slice::from_ref(&replaced));
- proven_facts.unproven_native_model_ids = vec!["cache-name-without-account-proof".into()];
+ model(&mut proven_facts).unproven_native_model_ids =
+ vec!["cache-name-without-account-proof".into()];
let proven = preview_agent_settings(spec(preserve_selection.clone()), &proven_facts).unwrap();
assert!(proven.blockers.is_empty());
assert_eq!(
@@ -665,10 +693,10 @@ fn codex_plan_selections_preview_only_with_catalog_facts() {
else {
panic!("fixed route")
};
- proven_facts
+ model(&mut proven_facts)
.preserved_codex_bindings
.insert(preserved.client_model_id.clone(), binding.as_ref().clone());
- proven_facts.fixed_candidate_facts.clear();
+ model(&mut proven_facts).fixed_candidate_facts.clear();
let later = preview_agent_settings(spec(preserve_selection.clone()), &proven_facts).unwrap();
assert!(later.blockers.is_empty());
assert_eq!(
@@ -681,7 +709,7 @@ fn codex_plan_selections_preview_only_with_catalog_facts() {
);
let mut changed_binding = preserve_selection;
changed_binding["fixed_models"] = serde_json::to_value([replaced]).unwrap();
- proven_facts.fixed_candidate_facts = vec![replacement_candidate];
+ model(&mut proven_facts).fixed_candidate_facts = vec![replacement_candidate];
let rejected = preview_agent_settings(spec(changed_binding), &proven_facts).unwrap();
assert!(!rejected.blockers.is_empty());
assert!(
@@ -692,10 +720,10 @@ fn codex_plan_selections_preview_only_with_catalog_facts() {
);
// Plan-only settings without protected native bindings remain a full-state edit.
- proven_facts.preserved_codex_models.clear();
- proven_facts.preserved_codex_bindings.clear();
- proven_facts.required_native_model_ids = None;
- proven_facts.require_native_model_routes = false;
+ model(&mut proven_facts).preserved_codex_models.clear();
+ model(&mut proven_facts).preserved_codex_bindings.clear();
+ model(&mut proven_facts).required_native_model_ids = None;
+ model(&mut proven_facts).require_native_model_routes = false;
let removed = preview_agent_settings(spec(plan_selection), &proven_facts).unwrap();
let AgentFacetIntent::Configure {
settings: AgentModelSelectionV2::CodexDefault { fixed_models, .. },
@@ -1027,8 +1055,8 @@ fn claude_settings_share_the_smallest_published_window_and_block_overrides() {
"opus":{"kind":"plan","plan_id":ids[0]},"sonnet":{"kind":"plan","plan_id":ids[1]},"haiku":{"kind":"preserve_native"}}}}
})).unwrap();
let mut facts = facts();
- facts.model_publication = Some(publication);
- facts.native_claude_presets = Some(hiroute_domain::AgentClaudePresetValuesV2 {
+ model(&mut facts).model_publication = Some(publication);
+ model(&mut facts).native_claude_presets = Some(hiroute_domain::AgentClaudePresetValuesV2 {
opus: None,
sonnet: None,
haiku: None,
@@ -1043,7 +1071,7 @@ fn claude_settings_share_the_smallest_published_window_and_block_overrides() {
.collect::<BTreeSet<_>>(),
[100_000, 120_000].into()
);
- facts.claude_context_override = true;
+ model(&mut facts).claude_context_override = true;
let blocked = preview_agent_settings(spec.clone(), &facts).unwrap();
assert!(
blocked
@@ -1051,8 +1079,8 @@ fn claude_settings_share_the_smallest_published_window_and_block_overrides() {
.iter()
.any(|block| block.reason == SettingsBlockReason::ClaudeContextOverride)
);
- facts.claude_context_override = false;
- facts.claude_plan_capability_unavailable = true;
+ model(&mut facts).claude_context_override = false;
+ model(&mut facts).claude_plan_capability_unavailable = true;
let blocked = preview_agent_settings(spec, &facts).unwrap();
assert!(
blocked
@@ -1065,8 +1093,8 @@ fn claude_settings_share_the_smallest_published_window_and_block_overrides() {
#[test]
fn standalone_profile_restore_inherits_root_without_catalog_or_native_override() {
let mut facts = facts();
- facts.ingress = AgentIngressProtocolV1::Responses;
- facts.restore_inherits_root = true;
+ model(&mut facts).ingress = AgentIngressProtocolV1::Responses;
+ model(&mut facts).restore_inherits_root = true;
facts.capabilities = AgentCapabilitySet::new(
[
AgentCapability::EffectiveConfiguration,
@@ -1103,3 +1131,6 @@ fn standalone_profile_restore_inherits_root_without_catalog_or_native_override()
Err(SettingsPlanningError::InvalidSelection)
));
}
+
+#[path = "collaboration_only_tests.rs"]
+mod collaboration_only_tests;
diff --git a/crates/application/src/agent_connection/settings_input.rs b/crates/application/src/agent_connection/settings_input.rs
index 7f411cea..97dc04ae 100644
--- a/crates/application/src/agent_connection/settings_input.rs
+++ b/crates/application/src/agent_connection/settings_input.rs
@@ -3,7 +3,7 @@ use super::*;
use hiroute_domain::{
AgentAccessGrantMaterialActionV1, AgentAccessGrantMutationV1, AgentAccessGrantRefV1,
AgentAccessGrantScopeV1, AgentAccessTokenIntentV1, AgentConnectionTransactionSubjectV1,
- AgentFacetIntent, AgentIngressProtocolV1, CanonicalDigest, OperationId,
+ AgentFacetIntent, AgentIngressProtocolV1, AgentModelSelectionV2, CanonicalDigest, OperationId,
OperationValidationError, RevisionSetV1, SupportedAgentInstallationV1, TransactionPlanV1,
WorkspaceId, settings_model_publication_intent,
};
@@ -15,7 +15,7 @@ pub struct AgentSettingsPlanningInput {
pub facts: AgentSettingsFacts,
pub expected_revisions: RevisionSetV1,
pub subject: AgentConnectionTransactionSubjectV1,
- pub model_file: SettingsModelFileFacts,
+ pub model_file: Option<SettingsModelFileFacts>,
pub skill_file: SettingsSkillFileFacts,
}
@@ -43,6 +43,11 @@ pub enum SettingsModelTargetFacts {
endpoint: String,
},
Claude(SettingsClaudeModelFacts),
+ Qoder {
+ provider_id: String,
+ endpoint: String,
+ models: Vec<hiroute_domain::QoderAdditionalModelV1>,
+ },
}
pub struct SettingsClaudeModelFacts {
@@ -76,9 +81,17 @@ impl AgentSettingsPlanningInput {
{
return Err(invalid());
}
- let file = &self.model_file;
+ if self.facts.model.is_none()
+ && (!matches!(preview.spec.model, AgentFacetIntent::Keep)
+ || !matches!(preview.spec.access_token, AgentAccessTokenIntentV1::Keep)
+ || preview.model_grant.is_some())
+ {
+ return Err(invalid());
+ }
let (model_mutations, model_action, restore_grant) = match &preview.spec.model {
AgentFacetIntent::Configure { settings } => {
+ let file = self.model_file.as_ref().ok_or_else(invalid)?;
+ let model = self.facts.model.as_ref().ok_or_else(invalid)?;
let grant = preview.model_grant.as_ref().ok_or_else(invalid)?;
let scope = AgentAccessGrantScopeV1::new(
format!("agent-connection/{}", self.facts.context_id),
@@ -95,21 +108,32 @@ impl AgentSettingsPlanningInput {
model: grant
.codex_default_override(settings)
.map_err(|_| invalid())?,
- model_catalog: self
- .facts
+ model_catalog: model
.model_catalog
.as_ref()
.map(|catalog| catalog.content_digest.clone()),
}),
+ SettingsModelTargetFacts::Qoder {
+ provider_id,
+ endpoint,
+ models,
+ } => {
+ if !matches!(settings, AgentModelSelectionV2::QoderAdditional { .. }) {
+ return Err(invalid());
+ }
+ SettingsModelAction::Qoder(super::QoderModelFileAction::Configure {
+ previous_operation: file.active_configuration.clone(),
+ provider_id: provider_id.clone(),
+ endpoint: endpoint.clone(),
+ models: models.clone(),
+ })
+ }
SettingsModelTargetFacts::Claude(claude) => {
let mut snapshot = claude_model_snapshot(
settings,
grant,
claude,
- self.facts
- .native_claude_presets
- .as_ref()
- .ok_or_else(invalid)?,
+ model.native_claude_presets.as_ref().ok_or_else(invalid)?,
)?;
snapshot.context_window_tokens = preview.claude_context_window;
SettingsModelAction::Claude(ClaudeModelFileAction::Configure {
@@ -155,6 +179,8 @@ impl AgentSettingsPlanningInput {
)
}
AgentFacetIntent::Restore { restore_point_ref } => {
+ let file = self.model_file.as_ref().ok_or_else(invalid)?;
+ self.facts.model.as_ref().ok_or_else(invalid)?;
let (operation, reference) = file.restore.as_ref().ok_or_else(invalid)?;
if *restore_point_ref != codex_model_restore_point_ref(operation)
|| reference.generation() != file.expected_grant_generation
@@ -168,6 +194,11 @@ impl AgentSettingsPlanningInput {
native_model: preview.spec.restore_native_model.clone(),
})
}
+ SettingsModelTargetFacts::Qoder { .. } => {
+ SettingsModelAction::Qoder(super::QoderModelFileAction::Restore {
+ original_operation: operation.clone(),
+ })
+ }
SettingsModelTargetFacts::Claude(_) => {
SettingsModelAction::Claude(ClaudeModelFileAction::Restore {
original_operation: operation.clone(),
@@ -210,7 +241,12 @@ impl AgentSettingsPlanningInput {
model_mutations,
|control| {
let mut external = Vec::new();
- if self.facts.login_item_removal_required {
+ if self
+ .facts
+ .model
+ .as_ref()
+ .is_some_and(|model| model.login_item_removal_required)
+ {
// The last managed connection's restore releases the login item this
// feature created in an older version. New connections never create one.
let declaration = confirmed.login_item().ok_or_else(invalid)?;
@@ -221,9 +257,11 @@ impl AgentSettingsPlanningInput {
)?);
}
if let Some(action) = model_action {
+ let file = self.model_file.as_ref().ok_or_else(invalid)?;
+ let model = self.facts.model.as_ref().ok_or_else(invalid)?;
match action {
SettingsModelAction::Codex(change) => {
- if let Some(catalog) = self.facts.model_catalog.as_ref() {
+ if let Some(catalog) = model.model_catalog.as_ref() {
// The immutable catalog artifact is staged before the managed
// configuration so the rendered pointer always has a target.
external.push(settings_codex_catalog_intent(
@@ -246,6 +284,15 @@ impl AgentSettingsPlanningInput {
change,
)?);
}
+ SettingsModelAction::Qoder(change) => {
+ external.push(super::settings_qoder_model_file_intent(
+ control,
+ &self.facts.context_id,
+ file.expected_content.clone(),
+ file.before_fingerprint.clone(),
+ change,
+ )?);
+ }
SettingsModelAction::Claude(change) => {
external.push(settings_claude_model_file_intent(
control,
@@ -356,6 +403,7 @@ impl AgentSettingsPlanningInput {
}
enum SettingsModelAction {
+ Qoder(super::QoderModelFileAction),
Codex(CodexModelFileAction),
Claude(ClaudeModelFileAction),
}
@@ -405,7 +453,7 @@ fn claude_model_snapshot(
if installation.agent_id != "agent_claude_default"
|| profile.profile_id != "claude-messages-v1"
|| profile.integration_profile_ref != "builtin/claude-messages/v1"
- || profile.client_protocol() != AgentIngressProtocolV1::Messages
+ || profile.client_protocol() != Some(AgentIngressProtocolV1::Messages)
|| !Path::new(&facts.trusted_hiroute_executable).is_absolute()
{
return Err(invalid());
diff --git a/crates/application/src/agent_connection/tests.rs b/crates/application/src/agent_connection/tests.rs
index 20099175..77c75ff0 100644
--- a/crates/application/src/agent_connection/tests.rs
+++ b/crates/application/src/agent_connection/tests.rs
@@ -48,6 +48,9 @@ fn agent_connection_current_proof_allows_unlisted_version_without_version_allowl
fn installation(kind: AgentKindV1) -> SupportedAgentInstallationV1 {
let version = match kind {
+ AgentKindV1::Qoder => {
+ panic!("model-connection fixture does not support collaboration-only Qoder")
+ }
AgentKindV1::Codex => CODEX_VERIFIED_VERSION_V1,
AgentKindV1::ClaudeCode => CLAUDE_CODE_VERIFIED_VERSION_V1,
};
@@ -82,6 +85,9 @@ fn installation(kind: AgentKindV1) -> SupportedAgentInstallationV1 {
fn profile(kind: AgentKindV1) -> AgentProfileV1 {
let precedence = kind.config_precedence().to_vec();
match kind {
+ AgentKindV1::Qoder => {
+ panic!("model-connection fixture does not support collaboration-only Qoder")
+ }
AgentKindV1::Codex => {
let tool = codex_spawn_agent_tool_v1();
AgentProfileV1 {
@@ -90,7 +96,7 @@ fn profile(kind: AgentKindV1) -> AgentProfileV1 {
integration_profile_ref: "builtin/codex-responses/v1".to_owned(),
kind,
legacy_exact_versions: BTreeSet::from([CODEX_VERIFIED_VERSION_V1.to_owned()]),
- ingress_protocol: AgentIngressProtocolV1::Responses,
+ ingress_protocol: Some(AgentIngressProtocolV1::Responses),
config_precedence: precedence,
owned_config_fields: vec![
field("provider", "model_provider"),
@@ -120,7 +126,7 @@ fn profile(kind: AgentKindV1) -> AgentProfileV1 {
integration_profile_ref: "builtin/claude-messages/v1".to_owned(),
kind,
legacy_exact_versions: BTreeSet::from([CLAUDE_CODE_VERIFIED_VERSION_V1.to_owned()]),
- ingress_protocol: AgentIngressProtocolV1::Messages,
+ ingress_protocol: Some(AgentIngressProtocolV1::Messages),
config_precedence: precedence,
owned_config_fields: vec![
field("base_endpoint", "env.ANTHROPIC_BASE_URL"),
@@ -246,6 +252,9 @@ fn facts(kind: AgentKindV1) -> AgentConnectionPlanningFactsV1 {
fn spec(kind: AgentKindV1, native: bool, dynamic: bool) -> AgentConnectSpecV1 {
let profile = match kind {
+ AgentKindV1::Qoder => {
+ panic!("model-connection fixture does not support collaboration-only Qoder")
+ }
AgentKindV1::Codex => profile(AgentKindV1::Codex),
AgentKindV1::ClaudeCode => profile(AgentKindV1::ClaudeCode),
};
@@ -254,6 +263,9 @@ fn spec(kind: AgentKindV1, native: bool, dynamic: bool) -> AgentConnectSpecV1 {
agent_id: format!("agent/{}", kind.as_str()),
profile_id: profile.profile_id,
installed_version: match kind {
+ AgentKindV1::Qoder => {
+ panic!("model-connection fixture does not support collaboration-only Qoder")
+ }
AgentKindV1::Codex => CODEX_VERIFIED_VERSION_V1,
AgentKindV1::ClaudeCode => CLAUDE_CODE_VERIFIED_VERSION_V1,
}
@@ -735,3 +747,21 @@ fn client_version_changes_do_not_invalidate_configuration_snapshot() {
}
}
}
+
+#[test]
+fn model_connection_planner_rejects_collaboration_only_profile_before_grants() {
+ let spec = spec(AgentKindV1::Codex, false, false);
+ let mut facts = facts(AgentKindV1::Codex);
+ let profile = &mut facts.installation.profile;
+ profile.kind = AgentKindV1::Qoder;
+ profile.ingress_protocol = None;
+ profile.config_precedence.clear();
+ profile.owned_config_fields.clear();
+ profile.dynamic_catalog = false;
+ profile.static_catalog_fallback = false;
+ profile.native_subagent_routing = false;
+ profile.spawn_guidance = None;
+ profile.managed_launch = None;
+ profile.validate().unwrap();
+ assert!(AgentConnectionPlanner::preview_connect(spec, facts).is_err());
+}
diff --git a/crates/application/src/control/collaboration_check.rs b/crates/application/src/control/collaboration_check.rs
new file mode 100644
index 00000000..826aec01
--- /dev/null
+++ b/crates/application/src/control/collaboration_check.rs
@@ -0,0 +1,15 @@
+//! Only native collaboration checks carry action-specific failure details.
+use super::ControlReadError;
+use hiroute_application_api::AgentCollaborationCheckFailureReasonV1;
+
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub enum CollaborationCheckError {
+ Control(ControlReadError),
+ Failed(AgentCollaborationCheckFailureReasonV1),
+}
+
+impl From<ControlReadError> for CollaborationCheckError {
+ fn from(error: ControlReadError) -> Self {
+ Self::Control(error)
+ }
+}
diff --git a/crates/application/src/control/mod.rs b/crates/application/src/control/mod.rs
index 0be9b53d..7e53c996 100644
--- a/crates/application/src/control/mod.rs
+++ b/crates/application/src/control/mod.rs
@@ -28,6 +28,8 @@ use std::collections::{BTreeMap, BTreeSet};
use serde::{Deserialize, Serialize};
use serde_json::Value;
+mod collaboration_check;
+pub use collaboration_check::CollaborationCheckError;
mod status;
pub use status::system_status;
@@ -325,8 +327,8 @@ pub trait AgentConnectionControlPort: Send + Sync {
fn check_native_authentication(&self, _agent_id: &str) -> Result<(), ControlReadError> {
Err(ControlReadError::Unavailable)
}
- fn check_collaboration(&self, _agent_id: &str) -> Result<(), ControlReadError> {
- Err(ControlReadError::Unavailable)
+ fn check_collaboration(&self, _agent_id: &str) -> Result<(), CollaborationCheckError> {
+ Err(ControlReadError::Unavailable.into())
}
fn validate_live_check_target(
&self,
@@ -353,7 +355,7 @@ pub trait AgentConnectionControlPort: Send + Sync {
fn settings_status(
&self,
_request: &hiroute_application_api::AgentSettingsStatusRequestV2,
- ) -> Result<hiroute_application_api::AgentModelSettingsStatusV2, ControlReadError> {
+ ) -> Result<hiroute_application_api::AgentSettingsStatusV2, ControlReadError> {
Err(ControlReadError::Unavailable)
}
diff --git a/crates/application/src/control_plane/agent_settings.rs b/crates/application/src/control_plane/agent_settings.rs
index d7e54c60..ae04b0f5 100644
--- a/crates/application/src/control_plane/agent_settings.rs
+++ b/crates/application/src/control_plane/agent_settings.rs
@@ -21,7 +21,10 @@ pub(crate) fn preview(
Ok(payload) => payload,
Err(_) => return failed(ErrorCode::InvalidArguments, request.request_id),
};
- if request.operation_id == "PreviewAgentConnectionRestore" && !payload.spec.is_restore_only() {
+ // Restore owns a distinct confirmation and idempotency scope. Keep the descriptor
+ // consistent with the journal kind the strict settings reader derives from this spec.
+ let restore = request.operation_id == "PreviewAgentConnectionRestore";
+ if restore != payload.spec.is_restore_only() {
return failed(ErrorCode::InvalidArguments, request.request_id);
}
let Some(port) = service
@@ -44,8 +47,8 @@ pub(crate) fn preview(
result["expected_revisions"] = json!(input.expected_revisions);
result["applicable"] = json!(preview.blockers.is_empty());
result["resident_service"] = json!({
- "login_item_required": input.facts.login_item_required,
- "login_item_removal_required": input.facts.login_item_removal_required,
+ "login_item_required": input.facts.model.as_ref().is_some_and(|model| model.login_item_required),
+ "login_item_removal_required": input.facts.model.as_ref().is_some_and(|model| model.login_item_removal_required),
});
if matches!(
&preview.spec.collaboration,
@@ -61,13 +64,16 @@ pub(crate) fn preview(
trigger_mode: settings.trigger_mode,
});
}
- result["model_effect"] = match (&preview.spec.model, &input.model_file.target) {
+ result["model_effect"] = match (
+ &preview.spec.model,
+ input.model_file.as_ref().map(|file| &file.target),
+ ) {
(
hiroute_application_api::AgentFacetIntent::Configure { settings },
- SettingsModelTargetFacts::Codex {
+ Some(SettingsModelTargetFacts::Codex {
provider_id,
endpoint,
- },
+ }),
) => json!({
"action":"configure", "agent_class":"codex", "provider_id":provider_id, "endpoint":endpoint,
"selection":settings,
@@ -75,16 +81,28 @@ pub(crate) fn preview(
}),
(
hiroute_application_api::AgentFacetIntent::Configure { settings },
- SettingsModelTargetFacts::Claude(claude),
+ Some(SettingsModelTargetFacts::Claude(claude)),
) => json!({
"action":"configure", "agent_class":"claude", "endpoint":claude.gateway_base_url,
"selection":settings,
"authentication":"connection_scoped_local_grant",
}),
- (hiroute_application_api::AgentFacetIntent::Restore { restore_point_ref }, _) => {
+ (
+ hiroute_application_api::AgentFacetIntent::Configure { settings },
+ Some(SettingsModelTargetFacts::Qoder {
+ provider_id,
+ endpoint,
+ ..
+ }),
+ ) => json!({
+ "action":"configure", "agent_class":"qoder", "provider_id":provider_id, "endpoint":endpoint,
+ "selection":settings, "authentication":"connection_scoped_local_grant",
+ }),
+ (hiroute_application_api::AgentFacetIntent::Restore { restore_point_ref }, Some(_)) => {
json!({"action":"restore","restore_point_ref":restore_point_ref})
}
(hiroute_application_api::AgentFacetIntent::Keep, _) => json!({"action":"keep"}),
+ (_, None) => return failed(ErrorCode::InvalidArguments, request.request_id),
};
if !preview.context_windows.is_empty() {
result["model_effect"]["context_windows"] = json!(preview.context_windows);
@@ -128,7 +146,7 @@ pub(crate) fn apply(
Err(_) => return failed(ErrorCode::InvalidArguments, request.request_id),
};
let restore = request.operation_id == "ApplyAgentConnectionRestore";
- if restore && !payload.spec.is_restore_only() {
+ if restore != payload.spec.is_restore_only() {
return failed(ErrorCode::InvalidArguments, request.request_id);
}
let operation_kind = if restore {
@@ -156,12 +174,22 @@ pub(crate) fn apply(
Ok(input) => input,
Err(error) => return failed(map_control_error(error), request.request_id),
};
- if !input.facts.login_item_removal_required && payload.login_item.is_some() {
+ if !input
+ .facts
+ .model
+ .as_ref()
+ .is_some_and(|model| model.login_item_removal_required)
+ && payload.login_item.is_some()
+ {
// New saves do not own startup state; an unsolicited host declaration must not be
// silently accepted after an older Desktop has changed the system login item.
return failed(ErrorCode::InvalidArguments, request.request_id);
}
- if input.facts.login_item_removal_required
+ if input
+ .facts
+ .model
+ .as_ref()
+ .is_some_and(|model| model.login_item_removal_required)
&& !payload
.login_item
.as_ref()
diff --git a/crates/application/src/delegation/tasks.rs b/crates/application/src/delegation/tasks.rs
index afce036d..35f90f78 100644
--- a/crates/application/src/delegation/tasks.rs
+++ b/crates/application/src/delegation/tasks.rs
@@ -809,6 +809,7 @@ mod tests {
executors: vec![
unavailable(hiroute_domain::delegation::WorkerHarnessV1::CodexCli),
unavailable(hiroute_domain::delegation::WorkerHarnessV1::ClaudeCode),
+ unavailable(hiroute_domain::delegation::WorkerHarnessV1::QoderCli),
],
})
}
@@ -869,7 +870,15 @@ mod tests {
let value = response.data.unwrap();
assert!(value.get("plans").is_none());
assert!(value.get("agent_id").is_none());
- assert_eq!(value["executors"].as_array().unwrap().len(), 2);
+ assert_eq!(
+ value["executors"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|executor| executor["harness"].as_str().unwrap())
+ .collect::<Vec<_>>(),
+ ["codex_cli", "claude_code", "qoder_cli"]
+ );
let rejected = invoke_worker(
&tasks,
diff --git a/crates/application/src/lib.rs b/crates/application/src/lib.rs
index 83c8a2f3..e6bf9854 100644
--- a/crates/application/src/lib.rs
+++ b/crates/application/src/lib.rs
@@ -474,7 +474,7 @@ impl ApplicationService {
"agent_id":check.agent_id, "skill_loading":"proven",
"trusted_cli_execution":"proven", "model_call":false,
}), request.request_id),
- Err(error) => failed(map_control_error(error), request.request_id),
+ Err(error) => agent_connection::collaboration_check::failed(error, request.request_id),
};
}
if disposition == agent_connection::control::CheckDisposition::NativeAuthenticationRequested {
diff --git a/crates/application/src/operations/mod.rs b/crates/application/src/operations/mod.rs
index e349f79c..f6b70799 100644
--- a/crates/application/src/operations/mod.rs
+++ b/crates/application/src/operations/mod.rs
@@ -956,6 +956,12 @@ pub enum TransactionError {
impl TransactionError {
pub fn error_code(&self) -> ErrorCode {
match self {
+ Self::Port(error) | Self::Preparation(ChangePreparationError::Port(error))
+ if error.code == hiroute_domain::PortErrorCode::Conflict
+ && error.context == "qoder.model.budget.shrink" =>
+ {
+ ErrorCode::QoderModelBudgetConflict
+ }
Self::PlanContent(code) => *code,
Self::FeatureNotEnabled
| Self::Preparation(ChangePreparationError::FeatureNotEnabled) => {
@@ -991,6 +997,12 @@ impl TransactionError {
fn safe_code(&self) -> &'static str {
match self {
+ Self::Port(error) | Self::Preparation(ChangePreparationError::Port(error))
+ if error.code == hiroute_domain::PortErrorCode::Conflict
+ && error.context == "qoder.model.budget.shrink" =>
+ {
+ "QODER_MODEL_BUDGET_CONFLICT"
+ }
Self::ChangePreviewStale
| Self::Preparation(ChangePreparationError::SecretFingerprintMismatch)
| Self::Preparation(ChangePreparationError::ExternalEffectChanged) => {
diff --git a/crates/application/src/operations/prepared.rs b/crates/application/src/operations/prepared.rs
index 48699b1c..c83c81a5 100644
--- a/crates/application/src/operations/prepared.rs
+++ b/crates/application/src/operations/prepared.rs
@@ -271,10 +271,12 @@ where
} else if plan.spec().command_id == hiroute_domain::COMPUTE_SUBSCRIPTION_CHECK_COMMAND_ID_V2
{
operation_kind == APPLY_SUBSCRIPTION_CHECK_OPERATION_V2
+ } else if settings_restore_plan(plan.spec()) {
+ // The internal settings command is shared, but restore-only plans must never
+ // reach the journal through Change authority, including internal callers.
+ operation_kind == "ApplyAgentConnectionRestore"
} else {
(registered_apply_operation_kind(&request.spec.command_id)? == operation_kind)
- || (operation_kind == "ApplyAgentConnectionRestore"
- && settings_restore_plan(plan.spec()))
|| (operation_kind == APPLY_COMPUTE_SAVE_OPERATION_V2
&& plan.spec().command_id == "compute.connection.apply")
};
diff --git a/crates/application/src/operations/tests/mod.rs b/crates/application/src/operations/tests/mod.rs
index ccaab242..facdf822 100644
--- a/crates/application/src/operations/tests/mod.rs
+++ b/crates/application/src/operations/tests/mod.rs
@@ -40,6 +40,7 @@ struct MemoryState {
operation_reads: usize,
secret_reads: usize,
external_reads: usize,
+ external_fingerprints: HashMap<String, CanonicalDigest>,
protected_reads: usize,
staged_pool: Option<CredentialPoolMutationV1>,
compute_pool: Option<hiroute_domain::CredentialPoolV1>,
@@ -589,9 +590,10 @@ impl RuntimeStatePort for MemoryPorts {
}
impl ExternalEffectPort for MemoryPorts {
- fn current_external_fingerprint(&self, _target: &str) -> PortResult<Option<CanonicalDigest>> {
- self.state.borrow_mut().external_reads += 1;
- Ok(None)
+ fn current_external_fingerprint(&self, target: &str) -> PortResult<Option<CanonicalDigest>> {
+ let mut state = self.state.borrow_mut();
+ state.external_reads += 1;
+ Ok(state.external_fingerprints.get(target).cloned())
}
fn apply_external(
@@ -1011,3 +1013,28 @@ fn terminal_reconciliation_turns_missing_owned_effect_into_attention() {
mod classifier_secret_tests;
#[path = "compute_tests.rs"]
mod compute_tests;
+
+#[test]
+fn qoder_budget_conflict_has_the_same_public_and_terminal_error_code() {
+ for error in [
+ TransactionError::Port(PortError::new(
+ PortErrorCode::Conflict,
+ "qoder.model.budget.shrink",
+ )),
+ TransactionError::Preparation(ChangePreparationError::Port(PortError::new(
+ PortErrorCode::Conflict,
+ "qoder.model.budget.shrink",
+ ))),
+ ] {
+ assert_eq!(error.error_code(), ErrorCode::QoderModelBudgetConflict);
+ assert_eq!(error.safe_code(), "QODER_MODEL_BUDGET_CONFLICT");
+ }
+ for error in [
+ PortError::new(PortErrorCode::Conflict, "another.conflict"),
+ PortError::new(PortErrorCode::Unavailable, "qoder.model.budget.shrink"),
+ ] {
+ let error = TransactionError::Port(error);
+ assert_eq!(error.error_code(), ErrorCode::DaemonUnavailable);
+ assert_eq!(error.safe_code(), "ADAPTER_FAILURE");
+ }
+}
diff --git a/crates/application/src/operations/tests/settings_tail.rs b/crates/application/src/operations/tests/settings_tail.rs
index 83d0d689..b359adb0 100644
--- a/crates/application/src/operations/tests/settings_tail.rs
+++ b/crates/application/src/operations/tests/settings_tail.rs
@@ -261,6 +261,83 @@ fn coordinator<'a>(
TransactionCoordinator::new(ports, ports, ports, ports, ports, admission)
}
+#[test]
+fn restore_only_settings_require_restore_authority_before_journal_admission() {
+ let ports = MemoryPorts::default();
+ let runtime = TransactionRuntime::default();
+ let coordinator = open(&ports, &runtime);
+ let plan = settings_plan_for_action(false, true);
+ // Unlike the execution-tail fixtures, admission observes the previewed publication.
+ // Model-file absence is intentional, but the publication must exist at its source digest.
+ let publication = plan
+ .external()
+ .iter()
+ .find(|intent| is_settings_publication(intent))
+ .unwrap();
+ ports.state.borrow_mut().external_fingerprints.insert(
+ publication.target().to_owned(),
+ CanonicalDigest::of_bytes(b"publication-source"),
+ );
+ let digest = CanonicalDigest::of_bytes(b"restore-authority");
+ let request = ApplyRequestV1 {
+ schema_version: CHANGE_SPEC_SCHEMA_V1,
+ spec: plan.spec().clone(),
+ accept_digest: digest.clone(),
+ expected_revisions: ports.current_revisions(&WorkspaceId::default()).unwrap(),
+ idempotency_key: "restore-authority".to_owned(),
+ apply_capability: Some("restore-capability".to_owned()),
+ };
+ // Even a valid Change capability cannot admit a restore-only plan under the Change kind.
+ ports.grant_for(
+ "restore-capability",
+ &digest,
+ &request.expected_revisions,
+ "ApplyAgentConnectionChange",
+ );
+ let before = ports.counters();
+ let wrong =
+ crate::PreparedTransactionV1::for_setup(request.clone(), digest.clone(), plan.clone())
+ .unwrap()
+ .with_revalidation(|| Ok(()));
+ assert!(matches!(
+ coordinator.accept_prepared(&WorkspaceId::default(), &principal(), wrong),
+ Err(TransactionError::InvalidArguments)
+ ));
+ assert_eq!(ports.counters(), before);
+ assert!(ports.state.borrow().operations.is_empty());
+ assert!(ports.state.borrow().writer.is_none());
+ assert!(
+ ports.state.borrow().grants[CanonicalDigest::of_bytes(b"restore-capability").as_str()]
+ .consumed
+ .is_none()
+ );
+
+ ports.grant_for(
+ "restore-capability",
+ &digest,
+ &request.expected_revisions,
+ "ApplyAgentConnectionRestore",
+ );
+ for replay in [false, true] {
+ let prepared = crate::PreparedTransactionV1::for_agent_settings_restore(
+ request.clone(),
+ digest.clone(),
+ plan.clone(),
+ )
+ .unwrap()
+ .with_revalidation(|| Ok(()));
+ let accepted = coordinator
+ .accept_prepared(&WorkspaceId::default(), &principal(), prepared)
+ .unwrap();
+ assert_eq!(accepted.existing, replay);
+ assert_eq!(
+ accepted.operation().idempotency.operation_kind,
+ "ApplyAgentConnectionRestore"
+ );
+ }
+ assert_eq!(ports.state.borrow().operations.len(), 1);
+}
+
fn stored(ports: &MemoryPorts, operation_id: &OperationId) -> OperationV1 {
ports
.state
diff --git a/crates/cli/src/worker/input.rs b/crates/cli/src/worker/input.rs
index d39b0fb3..34f7f7de 100644
--- a/crates/cli/src/worker/input.rs
+++ b/crates/cli/src/worker/input.rs
@@ -24,6 +24,7 @@ pub(super) fn parse_dependencies_discover(
let parsed = match next(options, &mut index)?.as_str() {
"codex_cli" => WorkerHarnessV1::CodexCli,
"claude_code" => WorkerHarnessV1::ClaudeCode,
+ "qoder_cli" => WorkerHarnessV1::QoderCli,
_ => return Err(ErrorCode::InvalidArguments),
};
harness = unique(harness, parsed)?;
diff --git a/crates/cli/src/worker/render.rs b/crates/cli/src/worker/render.rs
index e8653619..767c94a3 100644
--- a/crates/cli/src/worker/render.rs
+++ b/crates/cli/src/worker/render.rs
@@ -371,12 +371,20 @@ pub(super) fn render_erased(
for selected in dependencies.selected {
if output == OutputMode::Quiet {
lines.push(worker_harness_wire_name(selected.harness).to_owned());
+ } else if selected.harness == WorkerHarnessV1::QoderCli {
+ lines.push(format!(
+ "selected\t{:?}\t{}",
+ selected.harness, selected.cli_path
+ ));
} else {
+ let Some(adapter_path) = selected.adapter_path.as_deref() else {
+ return invalid_response();
+ };
lines.push(format!(
"selected\t{:?}\t{}\t{}\t{}",
selected.harness,
selected.cli_path,
- selected.adapter_path,
+ adapter_path,
selected.node_path.as_deref().unwrap_or("-")
));
}
@@ -702,6 +710,7 @@ fn worker_harness_wire_name(harness: WorkerHarnessV1) -> &'static str {
match harness {
WorkerHarnessV1::CodexCli => "codex_cli",
WorkerHarnessV1::ClaudeCode => "claude_code",
+ WorkerHarnessV1::QoderCli => "qoder_cli",
}
}
@@ -773,16 +782,17 @@ mod tests {
);
}
- #[test]
- fn dependency_quiet_output_contains_only_stable_selected_harness_names() {
+ fn dependency_view() -> WorkerDependenciesViewV1 {
let root = std::env::current_dir().unwrap();
let selection = |harness, name: &str| WorkerDependencySelectionV1 {
harness,
- adapter_path: root.join(format!("{name}-adapter")).display().to_string(),
+ adapter_path: (harness != WorkerHarnessV1::QoderCli)
+ .then(|| root.join(format!("{name}-adapter")).display().to_string()),
cli_path: root.join(format!("{name}-cli")).display().to_string(),
- node_path: None,
+ node_path: (harness == WorkerHarnessV1::CodexCli)
+ .then(|| root.join("node").display().to_string()),
};
- let view = WorkerDependenciesViewV1 {
+ WorkerDependenciesViewV1 {
schema: "hiroute.worker-dependencies-view/v1".into(),
selection_revisions: vec![
WorkerDependencySelectionRevisionV1 {
@@ -793,22 +803,57 @@ mod tests {
harness: WorkerHarnessV1::ClaudeCode,
revision: 2,
},
+ WorkerDependencySelectionRevisionV1 {
+ harness: WorkerHarnessV1::QoderCli,
+ revision: 3,
+ },
],
candidates: Vec::new(),
selected: vec![
selection(WorkerHarnessV1::CodexCli, "codex"),
selection(WorkerHarnessV1::ClaudeCode, "claude"),
+ selection(WorkerHarnessV1::QoderCli, "qoder"),
],
install_hints: Vec::new(),
- };
+ }
+ }
+
+ #[test]
+ fn dependency_quiet_output_contains_only_stable_selected_harness_names() {
let rendered = render_transport(
- Ok::<_, ClientFailure>(MachineEnvelopeV2::succeeded(view, None)),
+ Ok::<_, ClientFailure>(MachineEnvelopeV2::succeeded(dependency_view(), None)),
OutputMode::Quiet,
"worker.dependencies.discover",
None,
);
assert_eq!(rendered.exit_code, 0);
- assert_eq!(rendered.stdout, "codex_cli\nclaude_code\n");
+ assert_eq!(rendered.stdout, "codex_cli\nclaude_code\nqoder_cli\n");
+ assert!(rendered.stderr.is_empty());
+ }
+
+ #[test]
+ fn dependency_text_preserves_adapter_columns_only_for_adapter_harnesses() {
+ let view = dependency_view();
+ let codex = &view.selected[0];
+ let claude = &view.selected[1];
+ let qoder = &view.selected[2];
+ let expected = format!(
+ "selected\tCodexCli\t{}\t{}\t{}\nselected\tClaudeCode\t{}\t{}\t-\nselected\tQoderCli\t{}\n",
+ codex.cli_path,
+ codex.adapter_path.as_deref().unwrap(),
+ codex.node_path.as_deref().unwrap(),
+ claude.cli_path,
+ claude.adapter_path.as_deref().unwrap(),
+ qoder.cli_path,
+ );
+ let rendered = render_transport(
+ Ok::<_, ClientFailure>(MachineEnvelopeV2::succeeded(view, None)),
+ OutputMode::Text,
+ "worker.dependencies.discover",
+ None,
+ );
+ assert_eq!(rendered.exit_code, 0);
+ assert_eq!(rendered.stdout, expected);
assert!(rendered.stderr.is_empty());
}
}
diff --git a/crates/cli/tests/worker_dependencies.rs b/crates/cli/tests/worker_dependencies.rs
index 596403dc..22c0d862 100644
--- a/crates/cli/tests/worker_dependencies.rs
+++ b/crates/cli/tests/worker_dependencies.rs
@@ -18,6 +18,10 @@ fn write_dependency(path: &Path, executable: bool) {
}
fn run_cli(runtime_root: &Path, arguments: &[&str], stdin: Option<&[u8]>) -> Value {
+ serde_json::from_str(&run_cli_output(runtime_root, arguments, stdin)).unwrap()
+}
+
+fn run_cli_output(runtime_root: &Path, arguments: &[&str], stdin: Option<&[u8]>) -> String {
let mut command = Command::new(env!("CARGO_BIN_EXE_hiroute"));
command
.args(arguments)
@@ -46,52 +50,59 @@ fn run_cli(runtime_root: &Path, arguments: &[&str], stdin: Option<&[u8]>) -> Val
"{}",
String::from_utf8_lossy(&output.stderr)
);
- serde_json::from_slice(&output.stdout).unwrap()
+ String::from_utf8(output.stdout).unwrap()
}
-fn candidate_path(discovery: &Value, component: &str) -> String {
+fn candidate_path(discovery: &Value, harness: &str, component: &str) -> String {
discovery["data"]["candidates"]
.as_array()
.unwrap()
.iter()
.find(|candidate| {
- candidate["harness"] == "codex_cli"
+ candidate["harness"] == harness
&& candidate["component"] == component
&& candidate["state"] == "found"
})
.and_then(|candidate| candidate["path"].as_str())
- .unwrap_or_else(|| panic!("missing found {component} candidate: {discovery}"))
+ .unwrap_or_else(|| panic!("missing found {harness} {component} candidate: {discovery}"))
.to_owned()
}
+fn isolated_dependency_environment(test_name: &str, dependencies: &[(&str, bool)]) -> bool {
+ if std::env::var(CHILD).as_deref() == Ok(test_name) {
+ return true;
+ }
+ let home = tempfile::tempdir().unwrap();
+ std::fs::set_permissions(home.path(), std::fs::Permissions::from_mode(0o700)).unwrap();
+ let bin = home.path().join("bin");
+ std::fs::create_dir(&bin).unwrap();
+ for (name, executable) in dependencies {
+ write_dependency(&bin.join(name), *executable);
+ }
+ let status = Command::new(std::env::current_exe().unwrap())
+ .args(["--exact", test_name, "--nocapture"])
+ .env(CHILD, test_name)
+ .env("HOME", home.path())
+ .env("PATH", &bin)
+ .env_remove("CODEX_HOME")
+ .env_remove("CLAUDE_CONFIG_DIR")
+ .env_remove("QODER_CONFIG_DIR")
+ .env_remove("NPM_CONFIG_PREFIX")
+ .env_remove("npm_config_prefix")
+ .env_remove("NPM_CONFIG_CACHE")
+ .env_remove("npm_config_cache")
+ .status()
+ .unwrap();
+ assert!(status.success());
+ false
+}
+
#[test]
fn public_cli_discover_select_and_same_request_replay_are_self_contained() {
- if std::env::var_os(CHILD).is_none() {
- let home = tempfile::tempdir().unwrap();
- std::fs::set_permissions(home.path(), std::fs::Permissions::from_mode(0o700)).unwrap();
- let bin = home.path().join("bin");
- std::fs::create_dir(&bin).unwrap();
- write_dependency(&bin.join("codex"), true);
- write_dependency(&bin.join("codex-acp"), false);
- write_dependency(&bin.join("node"), true);
- let status = Command::new(std::env::current_exe().unwrap())
- .args([
- "--exact",
- "public_cli_discover_select_and_same_request_replay_are_self_contained",
- "--nocapture",
- ])
- .env(CHILD, "1")
- .env("HOME", home.path())
- .env("PATH", &bin)
- .env_remove("CODEX_HOME")
- .env_remove("CLAUDE_CONFIG_DIR")
- .env_remove("NPM_CONFIG_PREFIX")
- .env_remove("npm_config_prefix")
- .env_remove("NPM_CONFIG_CACHE")
- .env_remove("npm_config_cache")
- .status()
- .unwrap();
- assert!(status.success());
+ if !isolated_dependency_environment(
+ "public_cli_discover_select_and_same_request_replay_are_self_contained",
+ &[("codex", true), ("codex-acp", false), ("node", true)],
+ ) {
return;
}
@@ -124,9 +135,9 @@ fn public_cli_discover_select_and_same_request_replay_are_self_contained() {
);
let request = json!({
"harness": "codex_cli",
- "adapter_path": candidate_path(&discovery, "adapter"),
- "cli_path": candidate_path(&discovery, "cli"),
- "node_path": candidate_path(&discovery, "node"),
+ "adapter_path": candidate_path(&discovery, "codex_cli", "adapter"),
+ "cli_path": candidate_path(&discovery, "codex_cli", "cli"),
+ "node_path": candidate_path(&discovery, "codex_cli", "node"),
"expected_selection_revision": 0,
});
let request = serde_json::to_vec(&request).unwrap();
@@ -175,3 +186,100 @@ fn public_cli_discover_select_and_same_request_replay_are_self_contained() {
control.shutdown();
control.join(Duration::from_secs(10)).unwrap();
}
+
+#[test]
+fn public_cli_qoder_native_selection_replays_without_adapter_or_node() {
+ if !isolated_dependency_environment(
+ "public_cli_qoder_native_selection_replays_without_adapter_or_node",
+ &[("qodercli", true)],
+ ) {
+ return;
+ }
+
+ let root = tempfile::tempdir().unwrap();
+ let runtime = ProductionControlRuntime::open(root.path().join("storage")).unwrap();
+ let runtime_root = root.path().join("runtime");
+ let mut control = start_control(
+ ApplicationService::new(runtime.application_ports()),
+ &runtime_root,
+ )
+ .unwrap();
+ let discover_arguments = [
+ "worker",
+ "dependencies",
+ "discover",
+ "--harness",
+ "qoder_cli",
+ "--output",
+ "json",
+ ];
+ let discovery = run_cli(&runtime_root, &discover_arguments, None);
+ assert_eq!(discovery["status"], "succeeded");
+ assert_eq!(
+ discovery["data"]["selection_revisions"],
+ json!([{"harness": "qoder_cli", "revision": 0}])
+ );
+ assert!(discovery["data"]["selected"].as_array().unwrap().is_empty());
+ assert!(
+ discovery["data"]["candidates"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .all(|candidate| candidate["harness"] == "qoder_cli"
+ && candidate["component"] == "cli")
+ );
+ let cli_path = candidate_path(&discovery, "qoder_cli", "cli");
+ let request = serde_json::to_vec(&json!({
+ "harness": "qoder_cli",
+ "cli_path": cli_path,
+ "expected_selection_revision": 0,
+ }))
+ .unwrap();
+ let select_arguments = [
+ "worker",
+ "dependencies",
+ "select",
+ "--request-stdin",
+ "--output",
+ "json",
+ ];
+ let first = run_cli(&runtime_root, &select_arguments, Some(&request));
+ assert_eq!(first["status"], "accepted");
+ let selected = json!([{"harness": "qoder_cli", "cli_path": cli_path}]);
+ assert_eq!(first["data"]["selected"], selected);
+ assert_eq!(
+ first["data"]["selection_revisions"],
+ json!([{"harness": "qoder_cli", "revision": 1}])
+ );
+
+ let replay = run_cli(&runtime_root, &select_arguments, Some(&request));
+ assert_eq!(replay["status"], "accepted");
+ assert_eq!(replay["operation"], first["operation"]);
+ assert_eq!(replay["data"]["selected"], selected);
+ assert_eq!(
+ replay["data"]["selection_revisions"],
+ first["data"]["selection_revisions"]
+ );
+
+ let observed = run_cli(&runtime_root, &discover_arguments, None);
+ assert_eq!(observed["data"]["selected"], selected);
+ assert_eq!(observed["data"]["selection_revisions"][0]["revision"], 1);
+
+ let mut text_arguments = discover_arguments;
+ text_arguments[6] = "text";
+ let text = run_cli_output(&runtime_root, &text_arguments, None);
+ assert_eq!(
+ text.lines()
+ .filter(|line| line.starts_with("selected\t"))
+ .collect::<Vec<_>>(),
+ [format!("selected\tQoderCli\t{cli_path}")]
+ );
+ text_arguments[6] = "quiet";
+ assert_eq!(
+ run_cli_output(&runtime_root, &text_arguments, None),
+ "qoder_cli\n"
+ );
+
+ control.shutdown();
+ control.join(Duration::from_secs(10)).unwrap();
+}
diff --git a/crates/client-core/tests/transport.rs b/crates/client-core/tests/transport.rs
index 85a05c34..c6a9541f 100644
--- a/crates/client-core/tests/transport.rs
+++ b/crates/client-core/tests/transport.rs
@@ -392,6 +392,14 @@ async fn worker_executor_availability_is_an_empty_local_trust_query() {
"cancel": {"state":"unknown","reason":"runtime_unavailable"},
"continue_session": {"state":"unknown","reason":"runtime_unavailable"},
"restricted_policy": {"state":"unknown","reason":"runtime_unavailable"}
+ },
+ {
+ "harness": "qoder_cli",
+ "state": "ready",
+ "start_approve_all": {"state":"ready"},
+ "cancel": {"state":"ready"},
+ "continue_session": {"state":"unknown","reason":"capability_unverified"},
+ "restricted_policy": {"state":"unknown","reason":"restricted_policy_unverified"}
}
]
}),
@@ -407,7 +415,18 @@ async fn worker_executor_availability_is_an_empty_local_trust_query() {
.data
.unwrap();
assert!(response.valid());
- assert_eq!(response.executors[0].harness, WorkerHarnessV1::CodexCli);
+ assert_eq!(
+ response
+ .executors
+ .iter()
+ .map(|executor| executor.harness)
+ .collect::<Vec<_>>(),
+ [
+ WorkerHarnessV1::CodexCli,
+ WorkerHarnessV1::ClaudeCode,
+ WorkerHarnessV1::QoderCli
+ ]
+ );
server.await.unwrap();
}
diff --git a/crates/daemon/Cargo.toml b/crates/daemon/Cargo.toml
index eec392c2..7cd867d9 100644
--- a/crates/daemon/Cargo.toml
+++ b/crates/daemon/Cargo.toml
@@ -34,6 +34,7 @@ thiserror.workspace = true
tempfile.workspace = true
tokio = { workspace = true, features = ["process"] }
tokio-util = { workspace = true, features = ["codec", "rt"] }
+unicode-normalization.workspace = true
zeroize.workspace = true
[target.'cfg(unix)'.dependencies]
diff --git a/crates/daemon/src/control/runtime.rs b/crates/daemon/src/control/runtime.rs
index 3547d7be..6e7c047e 100644
--- a/crates/daemon/src/control/runtime.rs
+++ b/crates/daemon/src/control/runtime.rs
@@ -35,7 +35,7 @@ use hiroute_integrations::{
CLAUDE_PROFILE_ID_V1, CODEX_INTEGRATION_PROFILE_REF_V1, CODEX_PROFILE_ID_V1,
ClaudeRegistrationIndexV1, DiscoveredCredentialRefV1, FilesystemAgentDiscoveryV1,
FilesystemAgentScannerV1, PermissionHardeningRequiredV1, ProtectedAgentSubscriptionSourceV1,
- TrustedReleaseCatalog,
+ QODER_INTEGRATION_PROFILE_REF_V1, QODER_PROFILE_ID_V1, TrustedReleaseCatalog,
};
use hiroute_local_storage::{ApplyCapabilityRegistrationV1, LocalStorageSet, ManagedArtifactStore};
use hiroute_observation::{DigestAuthority, LocalObservationStore};
@@ -73,16 +73,19 @@ mod model_connections;
mod mutation;
mod native_claude_model;
mod native_model;
+mod native_qoder_model;
mod plan_content;
mod plan_content_snapshot;
mod plan_versions;
mod prices;
mod protected_inputs;
mod publication;
+mod qoder_model_budget;
mod release_install;
mod routing;
mod settings_codex_profile;
mod settings_facts;
+mod settings_retry;
mod settings_status;
mod source_authorization;
mod subscriptions;
@@ -300,12 +303,21 @@ impl ProductionControlRuntime {
)
.map_err(|error| error.to_string())?
.map(|(selection, _)| PathBuf::from(selection.cli_path));
+ let selected_qoder = stores
+ .control()
+ .worker_dependency_selection(
+ &WorkspaceId::default(),
+ hiroute_domain::delegation::WorkerHarnessV1::QoderCli,
+ )
+ .map_err(|error| error.to_string())?
+ .map(|(selection, _)| PathBuf::from(selection.cli_path));
release_agent_scanner(
&home,
&project,
&release_catalog,
overrides.codex_desktop_engine,
selected_claude,
+ selected_qoder,
)?
}
};
@@ -336,11 +348,23 @@ impl ProductionControlRuntime {
let profile_target = AgentConnectionEffectRoleV1::ManagedConfiguration
.target_for(&profile_subject)
.map_err(|error| error.to_string())?;
+ let qoder_subject = AgentConnectionTransactionSubjectV1::from_registered_profile(
+ "agent_qoder_default",
+ QODER_PROFILE_ID_V1,
+ QODER_INTEGRATION_PROFILE_REF_V1,
+ )
+ .map_err(|error| error.to_string())?;
let artifacts = stores
.open_managed_artifacts_with_external_targets(
storage_root.join("managed-artifacts"),
storage_root.join("artifact-restores"),
[
+ (
+ AgentConnectionEffectRoleV1::ManagedConfiguration
+ .target_for(&qoder_subject)
+ .map_err(|error| error.to_string())?,
+ scanner.qoder_user_config_target(),
+ ),
(claude_managed_target, scanner.claude_user_settings_target()),
(codex_managed_target, scanner.codex_user_config_target()),
(profile_target, scanner.codex_profile_config_target()),
@@ -356,6 +380,12 @@ impl ProductionControlRuntime {
.map_err(|error| error.to_string())?,
home.join(".claude/skills/hiroute-collaboration/SKILL.md"),
),
+ (
+ AgentConnectionEffectRoleV1::RoutingSkill
+ .target_for(&qoder_subject)
+ .map_err(|error| error.to_string())?,
+ scanner.qoder_user_skill_target(),
+ ),
],
)
.map_err(|error| error.to_string())?;
@@ -888,17 +918,14 @@ impl WorkerInstallationSelectionSource for LocalControlAdapter {
.control()
.worker_dependency_selection(&WorkspaceId::default(), harness)
.map_err(|_| hiroute_domain::delegation::DelegationErrorV1::StorageUnavailable)?;
- Ok(
- selected.map(|(selection, revision)| WorkerInstallationSelection {
- config: WorkerInstallationConfig {
- harness: selection.harness,
- adapter: PathBuf::from(selection.adapter_path),
- harness_binary: PathBuf::from(selection.cli_path),
- node_binary: selection.node_path.map(PathBuf::from),
- },
- revision,
- }),
- )
+ selected
+ .map(|(selection, revision)| {
+ Ok(WorkerInstallationSelection {
+ config: WorkerInstallationConfig::from_record(&selection)?,
+ revision,
+ })
+ })
+ .transpose()
}
}
@@ -1241,6 +1268,7 @@ fn release_agent_scanner(
catalog: &TrustedReleaseCatalog,
codex_desktop_engine: Option<PathBuf>,
selected_claude: Option<PathBuf>,
+ selected_qoder: Option<PathBuf>,
) -> Result<FilesystemAgentScannerV1, String> {
// ReleaseFacts verification already validated the registered connector/model metadata.
// Agent registration consumes that payload after the current rating snapshot and all
@@ -1255,6 +1283,9 @@ fn release_agent_scanner(
if let Some(executable) = selected_claude {
layout.claude_executable = executable;
}
+ if let Some(executable) = selected_qoder {
+ layout.qoder_executable = executable;
+ }
Ok(FilesystemAgentScannerV1::new(layout, index))
}
@@ -1284,6 +1315,7 @@ fn discovered_agent(
match kind {
AgentKindV1::Codex => "codex-responses-v1",
AgentKindV1::ClaudeCode => "claude-messages-v1",
+ AgentKindV1::Qoder => QODER_PROFILE_ID_V1,
}
.to_owned(),
version.clone(),
diff --git a/crates/daemon/src/control/runtime/agent_connection.rs b/crates/daemon/src/control/runtime/agent_connection.rs
index 2661167a..3c5a6d8c 100644
--- a/crates/daemon/src/control/runtime/agent_connection.rs
+++ b/crates/daemon/src/control/runtime/agent_connection.rs
@@ -4,7 +4,9 @@ use hiroute_application::agent_connection::{
AgentConnectionBeforeFingerprintsV1, AgentConnectionPlanningFactsV1,
AgentConnectionPlanningInputV1, RegisteredGatewayEndpointV1,
};
-use hiroute_application::control::{AgentConnectionControlPort, ControlReadError};
+use hiroute_application::control::{
+ AgentConnectionControlPort, CollaborationCheckError, ControlReadError,
+};
use hiroute_application_api::{
AGENT_CONNECTION_STATUS_SCHEMA_V1, AgentConnectSpecV1, AgentConnectionStateV1,
AgentConnectionStatusRequestV1, AgentConnectionStatusV1, AgentLaunchDescriptorRequestV1,
@@ -20,6 +22,9 @@ use hiroute_integrations::AgentDiscoveryOutcomeV1;
use super::LocalControlAdapter;
+#[cfg(unix)]
+#[path = "agent_connection_collaboration_check.rs"]
+mod collaboration_check;
#[path = "agent_connection_discovery.rs"]
mod discovery;
@@ -325,27 +330,33 @@ impl LocalControlAdapter {
}
impl AgentConnectionControlPort for LocalControlAdapter {
- fn check_collaboration(&self, agent_id: &str) -> Result<(), ControlReadError> {
+ fn check_collaboration(&self, agent_id: &str) -> Result<(), CollaborationCheckError> {
#[cfg(unix)]
{
// A sibling from the running installation, never a PATH-selected replacement.
let cli = std::env::current_exe()
.map_err(|_| ControlReadError::Unavailable)?
.with_file_name("hiroute");
+ if agent_id == "agent_qoder_default" {
+ return self
+ .scanner
+ .check_qoder_collaboration(&cli, self.qoder_collaboration_probe_target()?)
+ .map_err(collaboration_check::qoder_failure);
+ }
let result = match agent_id {
"agent_codex_default" => self.scanner.check_codex_collaboration(&cli),
"agent_claude_default" => self.scanner.check_claude_collaboration(&cli),
- _ => return Err(ControlReadError::NotFound),
+ _ => return Err(ControlReadError::NotFound.into()),
};
result.map_err(|error| {
eprintln!("native collaboration check: {error}");
- ControlReadError::Unavailable
+ ControlReadError::Unavailable.into()
})
}
#[cfg(not(unix))]
{
let _ = agent_id;
- Err(ControlReadError::Unavailable)
+ Err(ControlReadError::Unavailable.into())
}
}
fn check_native_authentication(&self, agent_id: &str) -> Result<(), ControlReadError> {
@@ -394,14 +405,14 @@ impl AgentConnectionControlPort for LocalControlAdapter {
&self,
request: &hiroute_application_api::AgentSettingsRetryV1,
) -> Result<hiroute_domain::OperationV1, ControlReadError> {
- self.retry_codex_operation(request)
+ self.retry_model_settings_operation(request)
}
fn settings_status(
&self,
request: &hiroute_application_api::AgentSettingsStatusRequestV2,
- ) -> Result<hiroute_application_api::AgentModelSettingsStatusV2, ControlReadError> {
- self.model_settings_status(request)
+ ) -> Result<hiroute_application_api::AgentSettingsStatusV2, ControlReadError> {
+ self.agent_settings_status(request)
}
fn settings_facts(
diff --git a/crates/daemon/src/control/runtime/agent_connection_collaboration_check.rs b/crates/daemon/src/control/runtime/agent_connection_collaboration_check.rs
new file mode 100644
index 00000000..fbfd3a51
--- /dev/null
+++ b/crates/daemon/src/control/runtime/agent_connection_collaboration_check.rs
@@ -0,0 +1,59 @@
+//! Project native implementation failures into the closed collaboration-check contract.
+use hiroute_application::control::CollaborationCheckError;
+use hiroute_application_api::AgentCollaborationCheckFailureReasonV1 as Reason;
+use hiroute_integrations::QoderNativeError;
+
+pub(super) fn qoder_failure(error: QoderNativeError) -> CollaborationCheckError {
+ let reason = match error.stage {
+ "native login required" => Reason::LoginRequired,
+ "installed user Skill missing" => Reason::InstalledSkillMissing,
+ "installed user Skill changed" => Reason::InstalledSkillChanged,
+ "installed user Skill target"
+ | "installed user Skill read"
+ | "installed user Skill encoding" => Reason::InstalledSkillInvalid,
+ "selected native context" => Reason::NativeContextUnavailable,
+ "native context changed" => Reason::NativeContextChanged,
+ "selected executable"
+ | "trusted CLI"
+ | "native executable identity"
+ | "trusted CLI identity"
+ | "trusted CLI path"
+ | "trusted CLI baseline"
+ | "trusted CLI contract" => Reason::DependencyUnavailable,
+ "native check deadline" => Reason::CheckTimedOut,
+ _ => Reason::VerificationFailed,
+ };
+ CollaborationCheckError::Failed(reason)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn native_failures_keep_actionable_causes_without_exposing_stage_text() {
+ for (stage, expected) in [
+ ("native login required", Reason::LoginRequired),
+ (
+ "installed user Skill missing",
+ Reason::InstalledSkillMissing,
+ ),
+ (
+ "installed user Skill changed",
+ Reason::InstalledSkillChanged,
+ ),
+ ("installed user Skill target", Reason::InstalledSkillInvalid),
+ ("native context changed", Reason::NativeContextChanged),
+ ("native check deadline", Reason::CheckTimedOut),
+ (
+ "unknown native failure /private/user token=never-export",
+ Reason::VerificationFailed,
+ ),
+ ] {
+ assert_eq!(
+ qoder_failure(QoderNativeError { stage }),
+ CollaborationCheckError::Failed(expected)
+ );
+ }
+ }
+}
diff --git a/crates/daemon/src/control/runtime/agent_live_check.rs b/crates/daemon/src/control/runtime/agent_live_check.rs
index 9352d236..93f10290 100644
--- a/crates/daemon/src/control/runtime/agent_live_check.rs
+++ b/crates/daemon/src/control/runtime/agent_live_check.rs
@@ -5,10 +5,9 @@ use hiroute_application_api::{AgentCheckRequestV1, AgentLaunchDescriptorRequestV
use hiroute_domain::{
AGENT_SURFACE_CHECK_SCHEMA, AgentModelSurfaceV2, AgentSurfaceCheckRecordV1,
AgentSurfaceCheckStateV1, CanonicalDigest, ContentMode, ControlRepositoryPort,
- FactsCompleteness, FrozenExecutionTrustV1, GatewayModelRouteV2,
- GatewayPublicationSnapshotProjectionV3, IngressProtocolV1, ModelRequestRouteV2,
+ FactsCompleteness, FrozenExecutionTrustV1, GatewayPublicationSnapshotProjectionV3,
ObservationQueryError, ObservationQueryPort, PublicationRepositoryPort, RequestOutcome,
- SelectorSourceV1, WorkspaceId,
+ WorkspaceId,
};
use hiroute_gateway::server::core_runtime::observation::{
NativeAgentObservationIdentityV1, derive_native_agent_observation_session_id,
@@ -21,6 +20,9 @@ use std::process::{Command, Stdio};
use std::thread;
use std::time::{Duration, Instant};
+#[path = "agent_live_check_qoder.rs"]
+mod qoder;
+
const LIVE_CHECK_BUDGET: Duration = Duration::from_secs(120);
const RECEIPT_WAIT_BUDGET: Duration = Duration::from_secs(5);
const OUTPUT_LIMIT: usize = 1024 * 1024;
@@ -99,6 +101,9 @@ impl LocalControlAdapter {
for (model, trust) in target.client_model_ids.iter().zip(&expected) {
let result = match target.surface {
+ AgentModelSurfaceV2::QoderCli => {
+ self.execute_qoder_live_attempt(&target.context_id, model, trust, deadline)
+ }
AgentModelSurfaceV2::ClaudeCli => {
let (descriptor, trusted_hiroute_executable) =
claude.as_ref().ok_or(ControlReadError::Corrupt)?;
@@ -398,72 +403,14 @@ fn expected_trust(
grant_id: &str,
served_model_id: &str,
) -> Result<FrozenExecutionTrustV1, ControlReadError> {
- let grant = snapshot
- .grants
- .iter()
- .find(|grant| grant.grant_id == grant_id)
- .ok_or(ControlReadError::Corrupt)?;
- let projected = grant
- .routes
- .get(served_model_id)
- .ok_or(ControlReadError::Corrupt)?;
- let (agent_plan_id, route, plan_display_name) = match projected {
- GatewayModelRouteV2::Plan {
- plan_id,
- alias,
- revision,
- semantic_digest,
- } => {
- let projected_alias = snapshot
- .aliases
- .iter()
- .find(|candidate| &candidate.served_model_id == alias)
- .ok_or(ControlReadError::Corrupt)?;
- let routing = projected_alias
- .routing
- .as_ref()
- .ok_or(ControlReadError::Corrupt)?;
- if routing.agent_plan_id != plan_id.as_str() {
- return Err(ControlReadError::Corrupt);
- }
- (
- Some(plan_id.clone()),
- ModelRequestRouteV2::Plan {
- revision: *revision,
- semantic_digest: semantic_digest.clone(),
- },
- routing.plan_display_name.clone(),
- )
- }
- GatewayModelRouteV2::Fixed { binding_digest, .. } => (
- None,
- ModelRequestRouteV2::Fixed {
- binding_digest: binding_digest.clone(),
- },
- None,
- ),
- };
- let ingress_protocol = match grant.protocol {
- hiroute_domain::AgentIngressProtocolV1::Responses => IngressProtocolV1::Responses,
- hiroute_domain::AgentIngressProtocolV1::Messages => IngressProtocolV1::Messages,
- };
- let trust = FrozenExecutionTrustV1 {
- authority_id: snapshot.authority_id.clone(),
- authority_epoch: snapshot.authority_epoch,
- served_model_id: served_model_id.to_owned(),
- selector_source: SelectorSourceV1::TrustedModelAlias,
- agent_plan_id,
- route,
- plan_display_name,
- gateway_publication_revision: snapshot.publication_revision.to_string(),
- gateway_publication_digest: CanonicalDigest::parse(snapshot.payload_digest.clone())
- .map_err(|_| ControlReadError::Corrupt)?,
- grant_id: grant.grant_id.clone(),
- grant_generation: grant.generation,
- ingress_protocol,
- };
- trust.validate().map_err(|_| ControlReadError::Corrupt)?;
- Ok(trust)
+ let snapshot: hiroute_gateway::server::publication::GatewayPublicationSnapshotV3 =
+ serde_json::from_value(
+ serde_json::to_value(snapshot).map_err(|_| ControlReadError::Corrupt)?,
+ )
+ .map_err(|_| ControlReadError::Corrupt)?;
+ snapshot
+ .native_agent_execution_trust(grant_id, served_model_id)
+ .map_err(|_| ControlReadError::Corrupt)
}
fn run_bounded(command: &mut Command, deadline: Instant) -> Result<ProcessOutput, AttemptFailure> {
diff --git a/crates/daemon/src/control/runtime/agent_live_check_qoder.rs b/crates/daemon/src/control/runtime/agent_live_check_qoder.rs
new file mode 100644
index 00000000..55c5ddbf
--- /dev/null
+++ b/crates/daemon/src/control/runtime/agent_live_check_qoder.rs
@@ -0,0 +1,198 @@
+//! A real Qoder print call selects the persisted provider; no route or credential overlay.
+use super::*;
+
+impl LocalControlAdapter {
+ #[cfg(unix)]
+ pub(super) fn execute_qoder_live_attempt(
+ &self,
+ context_id: &str,
+ model: &str,
+ trust: &FrozenExecutionTrustV1,
+ deadline: Instant,
+ ) -> Result<CanonicalDigest, AttemptFailure> {
+ use std::os::unix::fs::OpenOptionsExt;
+ use std::os::unix::process::CommandExt;
+ let unavailable = || AttemptFailure {
+ executed: false,
+ reason: CLIENT_FAILED,
+ };
+ let executable = self
+ .scanner
+ .qoder_executable_target()
+ .ok_or_else(unavailable)?;
+ let context = self
+ .scanner
+ .qoder_native_context()
+ .map_err(|_| unavailable())?;
+ let working = tempfile::tempdir().map_err(|_| unavailable())?;
+ let safety = working.path().join("safety.json");
+ let safety_bytes = serde_json::to_vec(&serde_json::json!({
+ "disableAllHooks":true,"general":{"enableAutoUpdate":false,"sessionRetention":{"enabled":false}},
+ "plugins":{"autoUpdate":false},"autoMemoryEnabled":false,"autoMemoryUserScopeEnabled":false,
+ "dream":{"enabled":false},"promptSuggestionEnabled":false
+ })).map_err(|_| unavailable())?;
+ use std::io::Write;
+ std::fs::OpenOptions::new()
+ .write(true)
+ .create_new(true)
+ .mode(0o600)
+ .open(&safety)
+ .and_then(|mut file| file.write_all(&safety_bytes))
+ .map_err(|_| unavailable())?;
+ let output_path = working.path().join("native-output.private");
+ let output = std::fs::OpenOptions::new()
+ .write(true)
+ .create_new(true)
+ .mode(0o600)
+ .open(&output_path)
+ .map_err(|_| unavailable())?;
+ let native_model = format!(
+ "{}/{}",
+ hiroute_application::agent_connection::qoder_model_provider_id(context_id),
+ model
+ );
+ let mut command = Command::new(executable);
+ command
+ .arg("--cwd")
+ .arg(working.path())
+ .arg("--config-dir")
+ .arg(&context.config_root)
+ .args(["--setting-sources", "user", "--settings"])
+ .arg(&safety)
+ .args([
+ "--model",
+ &native_model,
+ "--print",
+ "--no-session-persistence",
+ "--output-format",
+ "stream-json",
+ "--strict-mcp-config",
+ "--mcp-config",
+ "{\"mcpServers\":{}}",
+ "--tools",
+ "",
+ "--permission-mode",
+ "dont_ask",
+ "--max-model-request-retries",
+ "0",
+ "-p",
+ LIVE_PROMPT,
+ ])
+ .env_clear()
+ .env("HOME", &context.home)
+ .env("QODER_CONFIG_DIR", &context.config_root)
+ .env("TMPDIR", working.path())
+ .env("PATH", "/usr/local/bin:/usr/bin:/bin:/opt/homebrew/bin")
+ .stdin(Stdio::null())
+ .stdout(Stdio::from(output))
+ .stderr(Stdio::null())
+ .current_dir(working.path())
+ .process_group(0);
+ let child = command.spawn().map_err(|_| unavailable())?;
+ let mut child = hiroute_integrations::NativeProbeProcess::new(child);
+ let failure = |reason| AttemptFailure {
+ executed: true,
+ reason,
+ };
+ let success = loop {
+ if Instant::now() >= deadline {
+ return Err(failure(CHECK_TIMEOUT));
+ }
+ if std::fs::metadata(&output_path)
+ .map_err(|_| failure(CLIENT_OUTPUT_INVALID))?
+ .len()
+ > OUTPUT_LIMIT as u64
+ {
+ return Err(failure(CLIENT_OUTPUT_INVALID));
+ }
+ if let Some(success) = child.observe().map_err(|_| failure(CLIENT_FAILED))? {
+ break success;
+ }
+ thread::sleep(Duration::from_millis(20));
+ };
+ child.stop().map_err(|_| failure(CLIENT_FAILED))?;
+ if !success {
+ return Err(failure(CLIENT_FAILED));
+ }
+ let mut bytes = zeroize::Zeroizing::new(Vec::new());
+ std::fs::File::open(&output_path)
+ .map_err(|_| failure(CLIENT_OUTPUT_INVALID))?
+ .take(OUTPUT_LIMIT as u64 + 1)
+ .read_to_end(&mut bytes)
+ .map_err(|_| failure(CLIENT_OUTPUT_INVALID))?;
+ if bytes.len() > OUTPUT_LIMIT {
+ return Err(failure(CLIENT_OUTPUT_INVALID));
+ }
+ let identity = parse_qoder_output(&bytes).ok_or_else(|| failure(CLIENT_OUTPUT_INVALID))?;
+ let response_digest = CanonicalDigest::of_bytes(&bytes);
+ self.verify_live_receipt(trust, &[identity], &response_digest, deadline)
+ }
+
+ #[cfg(not(unix))]
+ pub(super) fn execute_qoder_live_attempt(
+ &self,
+ _context_id: &str,
+ _model: &str,
+ _trust: &FrozenExecutionTrustV1,
+ _deadline: Instant,
+ ) -> Result<CanonicalDigest, AttemptFailure> {
+ Err(AttemptFailure {
+ executed: false,
+ reason: CLIENT_FAILED,
+ })
+ }
+}
+
+fn parse_qoder_output(bytes: &[u8]) -> Option<NativeAgentObservationIdentityV1> {
+ let mut result = None;
+ for line in bytes
+ .split(|byte| *byte == b'\n')
+ .filter(|line| !line.iter().all(u8::is_ascii_whitespace))
+ {
+ let value: serde_json::Value = serde_json::from_slice(line).ok()?;
+ if value["type"] == "result" {
+ if result.is_some()
+ || value["subtype"] != "success"
+ || value["is_error"] != false
+ || value["result"].as_str()?.trim() != LIVE_PROMPT_RESPONSE
+ {
+ return None;
+ }
+ let session_id = value["session_id"].as_str()?;
+ if !valid_native_identity(session_id) {
+ return None;
+ }
+ result = Some(NativeAgentObservationIdentityV1::QoderSession {
+ session_id: session_id.into(),
+ });
+ }
+ }
+ result
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ #[test]
+ fn qoder_live_requires_successful_terminal_marker_and_exact_native_identity() {
+ let valid = br#"{"type":"result","subtype":"success","is_error":false,"result":"HIROUTE_LIVE_CHECK_OK","session_id":"native-session"}"#;
+ assert!(
+ matches!(parse_qoder_output(valid),Some(NativeAgentObservationIdentityV1::QoderSession{session_id}) if session_id=="native-session")
+ );
+ for changed in [
+ String::from_utf8(valid.to_vec())
+ .unwrap()
+ .replace("\"is_error\":false", "\"is_error\":true"),
+ String::from_utf8(valid.to_vec())
+ .unwrap()
+ .replace("HIROUTE_LIVE_CHECK_OK", "echo only"),
+ format!(
+ "{}\n{}",
+ std::str::from_utf8(valid).unwrap(),
+ std::str::from_utf8(valid).unwrap()
+ ),
+ ] {
+ assert!(parse_qoder_output(changed.as_bytes()).is_none());
+ }
+ }
+}
diff --git a/crates/daemon/src/control/runtime/collaboration_installation.rs b/crates/daemon/src/control/runtime/collaboration_installation.rs
index 76d99804..3b95fa96 100644
--- a/crates/daemon/src/control/runtime/collaboration_installation.rs
+++ b/crates/daemon/src/control/runtime/collaboration_installation.rs
@@ -80,6 +80,10 @@ impl LocalControlAdapter {
&skill_target,
)?;
}
+ // Only historical clients ever owned sealed collaboration credentials.
+ if class == SettingsAgentClass::Qoder {
+ return Ok(());
+ }
let legacy = self.legacy_collaboration_artifact_path(&spec.context_id)?;
if !legacy.exists() {
return Ok(());
@@ -105,6 +109,7 @@ impl LocalControlAdapter {
self.scanner.codex_user_config_target()
}
SettingsAgentClass::Claude => self.scanner.claude_user_settings_target(),
+ SettingsAgentClass::Qoder => return Err(error()),
};
let home = native
.parent()
@@ -116,6 +121,7 @@ impl LocalControlAdapter {
.join(match class {
SettingsAgentClass::Codex | SettingsAgentClass::CodexProfile => "codex.sealed",
SettingsAgentClass::Claude => "claude-code.sealed",
+ SettingsAgentClass::Qoder => return Err(error()),
}))
}
}
diff --git a/crates/daemon/src/control/runtime/collaboration_status.rs b/crates/daemon/src/control/runtime/collaboration_status.rs
index 3cc95a34..5765355b 100644
--- a/crates/daemon/src/control/runtime/collaboration_status.rs
+++ b/crates/daemon/src/control/runtime/collaboration_status.rs
@@ -91,25 +91,26 @@ impl LocalControlAdapter {
AgentFacetIntent::Configure { settings } => {
let skill_current = match skill {
Some(record) if record.contexts.contains(&spec.context_id) => {
- match record.file_ownership {
+ let ownership_current = match record.file_ownership {
hiroute_domain::CollaborationSkillFileOwnership::Managed => {
record.file_effect.is_some()
}
hiroute_domain::CollaborationSkillFileOwnership::BorrowedIdentical => {
- let target = class
- .skill_target()
- .map_err(|_| ControlReadError::Corrupt)?;
record.file_effect.is_none()
- && self
- .artifacts
- .read_native_target(&target)
- .map_err(super::map_port)?
- .is_some_and(|bytes| {
- CanonicalDigest::of_bytes(bytes.as_slice())
- == record.content_digest
- })
}
- }
+ };
+ let target = class
+ .skill_target()
+ .map_err(|_| ControlReadError::Corrupt)?;
+ ownership_current
+ && self
+ .artifacts
+ .read_native_target(&target)
+ .map_err(super::map_port)?
+ .is_some_and(|bytes| {
+ CanonicalDigest::of_bytes(bytes.as_slice())
+ == record.content_digest
+ })
}
_ => false,
};
diff --git a/crates/daemon/src/control/runtime/compute_routing/tests.rs b/crates/daemon/src/control/runtime/compute_routing/tests.rs
index 756deae5..416c5227 100644
--- a/crates/daemon/src/control/runtime/compute_routing/tests.rs
+++ b/crates/daemon/src/control/runtime/compute_routing/tests.rs
@@ -304,7 +304,7 @@ fn current_catalog_drift_excludes_only_stale_projection_from_routing_snapshot()
std::fs::create_dir_all(&home).unwrap();
std::fs::create_dir_all(&project).unwrap();
let scanner =
- super::super::release_agent_scanner(&home, &project, &catalog, None, None).unwrap();
+ super::super::release_agent_scanner(&home, &project, &catalog, None, None, None).unwrap();
assert_eq!(
scanner.claude_executable_target(),
std::path::PathBuf::from("claude")
@@ -316,6 +316,7 @@ fn current_catalog_drift_excludes_only_stale_projection_from_routing_snapshot()
&catalog,
None,
Some(selected_claude.clone()),
+ None,
)
.unwrap();
assert_eq!(selected_scanner.claude_executable_target(), selected_claude);
diff --git a/crates/daemon/src/control/runtime/delegation_maintenance_tests.rs b/crates/daemon/src/control/runtime/delegation_maintenance_tests.rs
index 4519b6fb..1d20ca91 100644
--- a/crates/daemon/src/control/runtime/delegation_maintenance_tests.rs
+++ b/crates/daemon/src/control/runtime/delegation_maintenance_tests.rs
@@ -1,19 +1,25 @@
use std::os::unix::fs::PermissionsExt;
-use std::path::PathBuf;
-use std::time::Duration;
+use std::path::{Path, PathBuf};
+use std::time::{Duration, SystemTime, UNIX_EPOCH};
+use hiroute_application_api::{
+ DelegationTaskInputV1, WORKER_CONTINUE_SCHEMA_V1, WorkerContinueRequestV1,
+};
use hiroute_domain::WorkspaceId;
use hiroute_domain::delegation::{
DELEGATION_NATIVE_ROOT_MARKER_FILE_V1, DelegationBodyRefV1, DelegationCheckpointV1,
DelegationNativeCleanupFailureKindV1, DelegationNativeRootReadyV1, DelegationNativeRootStateV1,
- DelegationRuntimePort, RunEventV1,
+ DelegationProcessBindingV1, DelegationRuntimePort, DelegationSessionBindingV1, RunEventV1,
+ RunProcessObservationV1, RunStateV1, RunStopEvidenceV1, RunStopScopeV1,
};
use hiroute_observation::managed_text::{
- ManagedTextInput, ManagedTextNativeCleanup, ManagedTextPurpose, ManagedTextScope,
+ ManagedTextInput, ManagedTextNativeCleanup, ManagedTextPurpose, ManagedTextScope, RETENTION_MS,
};
use super::*;
use crate::control::runtime::ProductionControlRuntime;
+use crate::delegation::content::read_required_body;
+use crate::delegation::profile::{SessionRootUse, TaskSessionRoot, native_history};
const BLOCKED_TEST: &str = "control::runtime::delegation_maintenance::tests::blocked_native_deletion_remains_claimed_and_unacknowledged";
const SUCCESS_TEST: &str = "control::runtime::delegation_maintenance::tests::owned_native_deletion_commits_removed_before_exact_ack";
@@ -155,21 +161,7 @@ fn owned_native_deletion_commits_removed_before_exact_ack() {
fn cleanup_fixture(suffix: &str) -> CleanupFixture {
let directory = tempfile::tempdir().unwrap();
- let storage = directory.path().join("storage");
- private_directory(&storage);
- let mut runtime = ProductionControlRuntime::open_with_release_catalog(
- &storage,
- crate::release_catalog::fixture_catalog(),
- )
- .unwrap();
- runtime._observation_maintenance.take();
- for _ in 0..100 {
- if !runtime.observation.maintenance_status().0 {
- break;
- }
- std::thread::sleep(Duration::from_millis(2));
- }
- assert!(!runtime.observation.maintenance_status().0);
+ let runtime = maintenance_runtime(directory.path());
let task_id = format!("cleanup-{suffix}-task");
let run_id = format!("cleanup-{suffix}-run");
@@ -276,7 +268,444 @@ fn cleanup_fixture(suffix: &str) -> CleanupFixture {
}
}
-fn private_directory(path: &std::path::Path) {
+#[test]
+fn deleted_worker_body_revokes_continue_and_cleans_only_owned_metadata() {
+ if crate::test_support::isolated_agent_home(
+ "control::runtime::delegation_maintenance::tests::deleted_worker_body_revokes_continue_and_cleans_only_owned_metadata",
+ ) {
+ return;
+ }
+ assert_borrowed_retention(RetentionAction::Delete);
+}
+
+#[test]
+fn expired_worker_body_revokes_continue_and_cleans_only_owned_metadata() {
+ if crate::test_support::isolated_agent_home(
+ "control::runtime::delegation_maintenance::tests::expired_worker_body_revokes_continue_and_cleans_only_owned_metadata",
+ ) {
+ return;
+ }
+ assert_borrowed_retention(RetentionAction::Expire);
+}
+
+enum RetentionAction {
+ Delete,
+ Expire,
+}
+
+struct RetainedTask {
+ reference: ManagedTextRef,
+ session: TaskSessionRoot,
+ native_session_id: String,
+}
+
+// These are retention-consumer fixtures: lifecycle checkpoints stand in for a completed Worker.
+// They exercise the real body barrier and cleanup consumer, not a public sessions.delete API.
+fn assert_borrowed_retention(action: RetentionAction) {
+ let directory = tempfile::tempdir().unwrap();
+ let runtime = maintenance_runtime(directory.path());
+ let base = std::fs::canonicalize(directory.path()).unwrap();
+ for name in ["native", "home", "workspace"] {
+ private_directory(&base.join(name));
+ }
+ let home = base.join("home");
+ for name in [".codex", ".codex/skills", ".codex/sessions"] {
+ private_directory(&home.join(name));
+ }
+ let shared_files: Vec<_> = [
+ ("user-note.txt", b"user-owned home bytes".as_slice()),
+ (".codex/config.toml", b"user-owned configuration".as_slice()),
+ (".codex/skills/skill.md", b"user-owned skill".as_slice()),
+ (
+ ".codex/sessions/target.jsonl",
+ b"opaque target native history".as_slice(),
+ ),
+ (
+ ".codex/sessions/neighbor.jsonl",
+ b"opaque neighbor native history".as_slice(),
+ ),
+ ]
+ .into_iter()
+ .map(|(relative, bytes)| {
+ let path = home.join(relative);
+ std::fs::write(&path, bytes).unwrap();
+ (path, bytes.to_vec())
+ })
+ .collect();
+ let now = i64::try_from(
+ SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .unwrap()
+ .as_millis(),
+ )
+ .unwrap();
+ let target = retained_borrowed_task(&runtime, &base, "target", now);
+ // A later body deadline keeps the neighbor visible during target expiry.
+ let neighbor = retained_borrowed_task(&runtime, &base, "neighbor", now + 1_000);
+ let workspace = &target.reference.scope.workspace_id;
+ let target_id = &target.reference.scope.task_id;
+ let before = DelegationRuntimePort::task(runtime.adapter.as_ref(), workspace, target_id)
+ .unwrap()
+ .unwrap();
+ assert!(before.resume_until_ms > now as u64);
+ assert!(
+ runtime
+ .adapter
+ .required_bodies_visible(&before, now)
+ .unwrap()
+ );
+ assert_eq!(
+ read_retained_body(&runtime, &target, now).unwrap(),
+ b"retained Worker body"
+ );
+ let neighbor_before = DelegationRuntimePort::task(
+ runtime.adapter.as_ref(),
+ workspace,
+ &neighbor.reference.scope.task_id,
+ )
+ .unwrap()
+ .unwrap();
+ let neighbor_metadata = owned_metadata_bytes(neighbor.session.path());
+ let effect_time = match action {
+ RetentionAction::Expire => now + RETENTION_MS,
+ RetentionAction::Delete => now + 1_001,
+ };
+ if matches!(action, RetentionAction::Expire) {
+ assert_eq!(
+ runtime
+ .observation
+ .managed_text_expire_pending(effect_time, 10)
+ .unwrap(),
+ 1
+ );
+ } else {
+ let preview = runtime
+ .observation
+ .managed_text_delete_preview(&target.reference.scope, effect_time, effect_time)
+ .unwrap();
+ assert!(
+ runtime
+ .observation
+ .managed_text_delete_apply(&preview)
+ .unwrap()
+ .native_gc_pending
+ );
+ }
+
+ // A retained native binding cannot restore text hidden by HiRoute's body authority, even
+ // before cleanup removes the owned metadata. This is the same reader Continue invokes.
+ target
+ .session
+ .verify_native_session(&target.native_session_id)
+ .unwrap();
+ assert_eq!(
+ read_retained_body(&runtime, &target, effect_time),
+ Err(DelegationErrorV1::ResumeUnavailable)
+ );
+ assert_eq!(
+ runtime
+ .observation
+ .managed_text_pending_native_cleanup_page(None, 10)
+ .unwrap()
+ .len(),
+ 1
+ );
+ runtime.adapter.scan_task_maintenance(effect_time).unwrap();
+ runtime.adapter.scan_native_cleanup(effect_time).unwrap();
+
+ let after = DelegationRuntimePort::task(runtime.adapter.as_ref(), workspace, target_id)
+ .unwrap()
+ .unwrap();
+ assert_eq!(after.resume_until_ms, 0);
+ assert!(after.title.is_none());
+ // Check the closed admission path after revocation. This fixture does not publish a Plan
+ // or prove a successful Continue; the body reader above covers the pre-cleanup barrier.
+ let request = WorkerContinueRequestV1 {
+ schema: WORKER_CONTINUE_SCHEMA_V1.into(),
+ task_id: target_id.clone(),
+ expected_latest_run_id: target.reference.scope.run_id.clone(),
+ cwd: None,
+ permission_policy: Default::default(),
+ run_timeout_secs: 60,
+ input: DelegationTaskInputV1 {
+ goal: "Continue the retained task".into(),
+ context: String::new(),
+ constraints: String::new(),
+ acceptance_criteria: String::new(),
+ },
+ submission_key: "retention-continue".into(),
+ };
+ assert!(matches!(
+ runtime.adapter.continue_worker(&request),
+ Err(DelegationErrorV1::ResumeUnavailable)
+ ));
+ let removed =
+ DelegationRuntimePort::native_root(runtime.adapter.as_ref(), workspace, target_id)
+ .unwrap()
+ .unwrap();
+ assert_eq!(removed.root.state, DelegationNativeRootStateV1::Removed);
+ assert!(!target.session.path().exists());
+ assert!(
+ runtime
+ .observation
+ .managed_text_pending_native_cleanup_page(None, 10)
+ .unwrap()
+ .is_empty()
+ );
+ assert!(
+ DelegationRuntimePort::pending_continuation_releases(runtime.adapter.as_ref(), 10)
+ .unwrap()
+ .is_empty()
+ );
+
+ assert_eq!(
+ DelegationRuntimePort::task(
+ runtime.adapter.as_ref(),
+ workspace,
+ &neighbor.reference.scope.task_id
+ )
+ .unwrap()
+ .unwrap(),
+ neighbor_before
+ );
+ assert_eq!(
+ owned_metadata_bytes(neighbor.session.path()),
+ neighbor_metadata
+ );
+ neighbor
+ .session
+ .verify_native_session(&neighbor.native_session_id)
+ .unwrap();
+ assert_eq!(
+ read_retained_body(&runtime, &neighbor, effect_time).unwrap(),
+ b"retained Worker body"
+ );
+ for (path, expected) in shared_files {
+ assert_eq!(
+ std::fs::read(&path).unwrap(),
+ expected,
+ "borrowed file changed: {}",
+ path.display()
+ );
+ }
+}
+
+fn retained_borrowed_task(
+ runtime: &ProductionControlRuntime,
+ base: &Path,
+ suffix: &str,
+ created_at_ms: i64,
+) -> RetainedTask {
+ let task_id = format!("retention-{suffix}-task");
+ let run_id = format!("retention-{suffix}-run");
+ let scope = ManagedTextScope {
+ workspace_id: WorkspaceId::default(),
+ task_id,
+ run_id,
+ };
+ let reference = runtime
+ .observation
+ .managed_text_put(
+ &ManagedTextInput {
+ scope: scope.clone(),
+ purpose: ManagedTextPurpose::Result,
+ source_event_id: format!("retention-{suffix}-body"),
+ source_revision: 1,
+ original_created_at_ms: created_at_ms,
+ import_origin: None,
+ },
+ created_at_ms,
+ )
+ .unwrap();
+ runtime
+ .observation
+ .managed_text_append(
+ &scope,
+ &reference,
+ 0,
+ b"retained Worker body",
+ created_at_ms,
+ )
+ .unwrap();
+ let reference = runtime
+ .observation
+ .managed_text_finish(&scope, &reference, 1, created_at_ms)
+ .unwrap();
+ let body = DelegationBodyRefV1 {
+ opaque_id: reference.opaque_id.clone(),
+ scope_run_id: scope.run_id.clone(),
+ visibility_generation: reference.visibility_generation,
+ original_retention_deadline_ms: reference.original_retention_deadline_ms,
+ };
+ let mut acceptance = super::super::tests::worker_list_acceptance(
+ &scope.task_id,
+ &scope.run_id,
+ body.clone(),
+ created_at_ms as u64,
+ );
+ acceptance.run.idempotency_key = format!("retention-{suffix}-start");
+ acceptance.run.request_digest = hiroute_domain::CanonicalDigest::of_bytes(suffix.as_bytes());
+ acceptance.run.execution_owner_ref = format!("retention-{suffix}-owner");
+ acceptance.run.lease_id = format!("retention-{suffix}-lease");
+ acceptance.run.launch_nonce = format!("retention-{suffix}-launch");
+ acceptance.title_lookup_key = Some(format!("retention-{suffix}-title"));
+ let mut run = DelegationRuntimePort::accept(runtime.adapter.as_ref(), &acceptance).unwrap();
+ let creating = DelegationRuntimePort::native_root(
+ runtime.adapter.as_ref(),
+ &scope.workspace_id,
+ &scope.task_id,
+ )
+ .unwrap()
+ .unwrap();
+ let native_base = base.join("native");
+ let session = TaskSessionRoot::prepare(
+ &native_base,
+ &scope.workspace_id,
+ &creating.root.workspace_root_identity,
+ &scope.task_id,
+ creating.root.harness,
+ SessionRootUse::New,
+ )
+ .unwrap();
+ session
+ .bind_borrowed_context(
+ &base.join("home"),
+ &base.join("home/.codex"),
+ &base.join("workspace"),
+ )
+ .unwrap();
+ let identity = session
+ .create_ownership_marker(&native_base, &creating.root)
+ .unwrap();
+ DelegationRuntimePort::commit_native_root_ready(
+ runtime.adapter.as_ref(),
+ &DelegationNativeRootReadyV1 {
+ workspace_id: scope.workspace_id.clone(),
+ task_id: scope.task_id.clone(),
+ root_generation: creating.root.root_generation,
+ creation_nonce: creating.root.creation_nonce,
+ managed_base_path: native_base.to_str().unwrap().into(),
+ filesystem_identity: identity,
+ },
+ )
+ .unwrap();
+ let native_session_id = format!("retention-{suffix}-native");
+ let checkpoints = [
+ DelegationCheckpointV1::Progress {
+ event: RunEventV1::Preparing,
+ },
+ DelegationCheckpointV1::ProcessSpawned {
+ binding: DelegationProcessBindingV1 {
+ launch_nonce: run.launch_nonce.clone(),
+ handle_id: format!("retention-{suffix}-process"),
+ creation_identity: format!("retention-{suffix}-created"),
+ },
+ },
+ DelegationCheckpointV1::SessionBound {
+ binding: DelegationSessionBindingV1 {
+ acp_session_id: native_session_id.clone(),
+ native_session_id: Some(native_session_id.clone()),
+ },
+ },
+ DelegationCheckpointV1::Progress {
+ event: RunEventV1::PromptSendIntent,
+ },
+ DelegationCheckpointV1::ResultRecorded {
+ body: Some(body.clone()),
+ incomplete: false,
+ },
+ DelegationCheckpointV1::Progress {
+ event: RunEventV1::PromptCompleted,
+ },
+ DelegationCheckpointV1::ProcessStopped {
+ evidence: RunStopEvidenceV1 {
+ scope: RunStopScopeV1::ProcessGroup,
+ observation: RunProcessObservationV1::Exited { code: Some(0) },
+ scope_stopped: true,
+ residual_unknown: false,
+ },
+ },
+ ];
+ for (index, checkpoint) in checkpoints.iter().enumerate() {
+ run = DelegationRuntimePort::checkpoint(
+ runtime.adapter.as_ref(),
+ &scope.workspace_id,
+ &scope.run_id,
+ run.progress.revision,
+ &format!("retention-{suffix}-{index}"),
+ checkpoint,
+ )
+ .unwrap();
+ }
+ assert_eq!(run.progress.state, RunStateV1::Succeeded);
+ assert!(run.progress.workspace_releasable());
+ let history =
+ native_history(session.path(), creating.root.harness, &native_session_id).unwrap();
+ DelegationRuntimePort::set_resume_materials(
+ runtime.adapter.as_ref(),
+ &scope.workspace_id,
+ &scope.task_id,
+ &scope.run_id,
+ reference.original_retention_deadline_ms as u64,
+ &[body],
+ &history,
+ )
+ .unwrap();
+ RetainedTask {
+ reference,
+ session,
+ native_session_id,
+ }
+}
+
+fn read_retained_body(
+ runtime: &ProductionControlRuntime,
+ task: &RetainedTask,
+ now_ms: i64,
+) -> Result<Vec<u8>, DelegationErrorV1> {
+ read_required_body(
+ &runtime.observation,
+ &task.reference.scope,
+ &task.reference,
+ now_ms,
+ 1_024,
+ |_| Ok(()),
+ )
+}
+
+fn owned_metadata_bytes(root: &Path) -> Vec<(PathBuf, Vec<u8>)> {
+ let mut files: Vec<_> = std::fs::read_dir(root)
+ .unwrap()
+ .map(|entry| {
+ let path = entry.unwrap().path();
+ let bytes = std::fs::read(&path).unwrap();
+ (path, bytes)
+ })
+ .collect();
+ files.sort();
+ files
+}
+
+fn maintenance_runtime(directory: &Path) -> ProductionControlRuntime {
+ let storage = directory.join("storage");
+ private_directory(&storage);
+ let mut runtime = ProductionControlRuntime::open_with_release_catalog(
+ &storage,
+ crate::release_catalog::fixture_catalog(),
+ )
+ .unwrap();
+ runtime._observation_maintenance.take();
+ for _ in 0..100 {
+ if !runtime.observation.maintenance_status().0 {
+ break;
+ }
+ std::thread::sleep(Duration::from_millis(2));
+ }
+ assert!(!runtime.observation.maintenance_status().0);
+ runtime
+}
+
+fn private_directory(path: &Path) {
std::fs::create_dir(path).unwrap();
std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o700)).unwrap();
}
diff --git a/crates/daemon/src/control/runtime/delegation_task_queries.rs b/crates/daemon/src/control/runtime/delegation_task_queries.rs
index 69074229..2172cd6b 100644
--- a/crates/daemon/src/control/runtime/delegation_task_queries.rs
+++ b/crates/daemon/src/control/runtime/delegation_task_queries.rs
@@ -256,6 +256,7 @@ pub(super) fn run_view(task: &DelegationTaskV1, run: &DelegationRunV1) -> Delega
let display_name = match task.plan.harness {
hiroute_domain::delegation::WorkerHarnessV1::CodexCli => "Codex",
hiroute_domain::delegation::WorkerHarnessV1::ClaudeCode => "Claude Code",
+ hiroute_domain::delegation::WorkerHarnessV1::QoderCli => "Qoder",
};
DelegationRunViewV1 {
task_id: run.task_id.clone(),
diff --git a/crates/daemon/src/control/runtime/effects.rs b/crates/daemon/src/control/runtime/effects.rs
index fcbf2466..04117789 100644
--- a/crates/daemon/src/control/runtime/effects.rs
+++ b/crates/daemon/src/control/runtime/effects.rs
@@ -109,6 +109,10 @@ impl LocalControlAdapter {
hiroute_application::agent_connection::decode_settings_claude_model_file(intent)?;
return Ok(None);
}
+ if super::native_qoder_model::is_settings_qoder_model(intent) {
+ hiroute_application::agent_connection::decode_settings_qoder_model_file(intent)?;
+ return Ok(None);
+ }
let envelope: AgentConfigurationEnvelopeV1 =
serde_json::from_value(intent.desired().clone())
.map_err(|_| invalid("agent-config.intent.decode"))?;
@@ -361,6 +365,9 @@ impl ExternalEffectPort for LocalControlAdapter {
if super::native_claude_model::is_settings_claude_model(intent) {
return self.stage_settings_claude_model(operation, intent);
}
+ if super::native_qoder_model::is_settings_qoder_model(intent) {
+ return self.stage_settings_qoder_model(operation, intent);
+ }
let Some(permission) = self.permission_intent(intent)? else {
if let Some(change) = self.native_claude_change(intent)? {
let rendered = self
diff --git a/crates/daemon/src/control/runtime/mutation.rs b/crates/daemon/src/control/runtime/mutation.rs
index 74988bd3..87f54b94 100644
--- a/crates/daemon/src/control/runtime/mutation.rs
+++ b/crates/daemon/src/control/runtime/mutation.rs
@@ -220,9 +220,12 @@ impl ControlRepositoryPort for LocalControlAdapter {
fn begin_local_operation(&self, operation: &OperationV1) -> PortResult<BeginOperationOutcome> {
self.guard_codex_pending_change(Some(&operation.operation_id))?;
- self.stores_lock()?
- .control()
- .begin_local_operation(operation)
+ let stores = self.stores_lock()?;
+ super::qoder_model_budget::guard_pending_model_change(
+ stores.control(),
+ Some(&operation.operation_id),
+ )?;
+ stores.control().begin_local_operation(operation)
}
fn verify_apply_authorization(
@@ -250,9 +253,12 @@ impl ControlRepositoryPort for LocalControlAdapter {
authorization: &VerifiedApplyAuthorizationV1,
) -> PortResult<BeginOperationOutcome> {
self.guard_codex_pending_change(Some(&operation.operation_id))?;
- self.stores_lock()?
- .control()
- .begin_operation(operation, authorization)
+ let stores = self.stores_lock()?;
+ super::qoder_model_budget::guard_pending_model_change(
+ stores.control(),
+ Some(&operation.operation_id),
+ )?;
+ stores.control().begin_operation(operation, authorization)
}
fn operation_is_current(&self, operation: &OperationV1) -> PortResult<bool> {
diff --git a/crates/daemon/src/control/runtime/native_qoder_model.rs b/crates/daemon/src/control/runtime/native_qoder_model.rs
new file mode 100644
index 00000000..37cfa5dc
--- /dev/null
+++ b/crates/daemon/src/control/runtime/native_qoder_model.rs
@@ -0,0 +1,220 @@
+//! Qoder's additive model file is an ordinary protected settings effect.
+use super::LocalControlAdapter;
+use hiroute_application::agent_connection::{
+ QoderModelFileAction, settings_qoder_model_file_for_operation,
+};
+use hiroute_domain::{
+ AgentAccessGrantRefV1, AgentIngressProtocolV1, AgentModelGrantV2, AgentModelRouteV2,
+ ControlRepositoryPort, ExternalEffectIntentV1, GatewayPublicationV1, OperationState,
+ OperationStepKind, OperationV1, OwnedEffectV1, PortError, PortErrorCode, PortResult,
+ QoderAdditionalModelV1, SecretStorePort, WorkspaceId, is_agent_access_grant_effect,
+};
+
+pub(super) fn is_settings_qoder_model(intent: &ExternalEffectIntentV1) -> bool {
+ intent.effect_id() == "agent-connection-managed-configuration"
+ && intent.desired()["transaction"] == "settings"
+ && intent.desired()["subject"]["agent_id"] == "agent_qoder_default"
+}
+
+pub(super) fn qoder_model_endpoint(gateway_base_url: &str) -> PortResult<String> {
+ let origin = gateway_base_url
+ .strip_suffix("/v1")
+ .ok_or_else(|| conflict("qoder.settings.endpoint"))?;
+ Ok(format!("{origin}{}", hiroute_domain::QODER_MODEL_BASE_PATH))
+}
+
+pub(super) fn qoder_models_for_grant(
+ publication: &GatewayPublicationV1,
+ grant: &AgentModelGrantV2,
+) -> PortResult<Vec<QoderAdditionalModelV1>> {
+ grant
+ .routes
+ .iter()
+ .map(|(name, route)| {
+ let AgentModelRouteV2::Plan {
+ plan_id,
+ revision,
+ semantic_digest,
+ ..
+ } = route
+ else {
+ return Err(conflict("qoder.models.route"));
+ };
+ let plan = publication
+ .plans
+ .iter()
+ .find(|plan| {
+ plan.agent_plan_id() == plan_id && plan.body.agent_plan_revision == *revision
+ })
+ .ok_or_else(|| conflict("qoder.models.plan"))?
+ .clone()
+ .into_current()
+ .map_err(|_| conflict("qoder.models.plan"))?;
+ if &plan.body.materialized_route_digest != semantic_digest {
+ return Err(conflict("qoder.models.plan.digest"));
+ }
+ let budget = hiroute_integrations::qoder_plan_token_budget(&plan.body.materialized)
+ .map_err(|_| conflict("qoder.models.budget"))?;
+ Ok(QoderAdditionalModelV1 {
+ alias: name.clone(),
+ context_window_tokens: budget.context_window_tokens,
+ max_output_tokens: budget.max_output_tokens,
+ })
+ })
+ .collect()
+}
+
+impl LocalControlAdapter {
+ pub(super) fn stage_settings_qoder_model(
+ &self,
+ operation: &OperationV1,
+ intent: &ExternalEffectIntentV1,
+ ) -> PortResult<OwnedEffectV1> {
+ if operation.state != OperationState::ApplyingAgentArtifacts {
+ return Err(conflict("qoder.settings.phase"));
+ }
+ let payload = settings_qoder_model_file_for_operation(operation, intent)?;
+ let stores = self.stores_lock()?;
+ match &payload.change {
+ QoderModelFileAction::Configure {
+ previous_operation,
+ provider_id,
+ endpoint,
+ models,
+ } => {
+ let [mutation] = operation.plan.agent_access_grants() else {
+ return Err(conflict("qoder.settings.grant"));
+ };
+ let scope = mutation
+ .desired_scope()
+ .ok_or_else(|| conflict("qoder.settings.scope"))?;
+ if mutation.owner_scope() != operation.workspace_id.as_str()
+ || scope.connection_id() != format!("agent-connection/{}", payload.context_id)
+ || scope.protocol() != AgentIngressProtocolV1::Responses
+ {
+ return Err(conflict("qoder.settings.grant.binding"));
+ }
+ let gateway_base_url = self
+ .managed_agent_runtime
+ .lock()
+ .map_err(|_| conflict("qoder.settings.runtime"))?
+ .as_ref()
+ .map(|runtime| runtime.gateway_base_url.clone())
+ .ok_or_else(|| conflict("qoder.settings.runtime"))?;
+ if qoder_model_endpoint(&gateway_base_url)? != *endpoint {
+ return Err(conflict("qoder.settings.endpoint"));
+ }
+ let active = stores
+ .secrets()
+ .inspect_agent_access_grant(WorkspaceId::DEFAULT, scope.connection_id())?;
+ let previous = if let Some(id) = previous_operation {
+ let original = stores
+ .control()
+ .load_operation(id)?
+ .ok_or_else(|| conflict("qoder.settings.previous"))?;
+ let previous_intent = qoder_original_intent(&original, operation, intent)?;
+ let [previous_mutation] = original.plan.agent_access_grants() else {
+ return Err(conflict("qoder.settings.previous.grant"));
+ };
+ let effect = original
+ .step(OperationStepKind::ApplySecrets)
+ .effects
+ .iter()
+ .find(|effect| is_agent_access_grant_effect(effect))
+ .ok_or_else(|| conflict("qoder.settings.previous.effect"))?;
+ let reference =
+ AgentAccessGrantRefV1::from_ensure_effect(effect, previous_mutation)
+ .map_err(|_| conflict("qoder.settings.previous.reference"))?;
+ if active.as_ref() != Some(&reference)
+ || reference.generation() != mutation.expected_generation()
+ {
+ return Err(conflict("qoder.settings.previous.binding"));
+ }
+ Some((original, previous_intent))
+ } else {
+ if active.is_some() {
+ return Err(conflict("qoder.settings.previous.missing"));
+ }
+ None
+ };
+ let material = stores
+ .secrets()
+ .resolve_prepared_agent_access_grant(&operation.operation_id, mutation)?;
+ drop(stores);
+ let configuration = hiroute_integrations::QoderFileConfiguration {
+ expected_content: &payload.expected_content,
+ provider_id,
+ endpoint,
+ models,
+ local_grant: &material,
+ };
+ match previous {
+ Some((original, previous_intent)) => {
+ hiroute_integrations::stage_qoder_reconfiguration(
+ &self.artifacts,
+ &operation.operation_id,
+ intent,
+ &original.operation_id,
+ &previous_intent,
+ configuration,
+ )
+ }
+ None => hiroute_integrations::stage_qoder_configuration(
+ &self.artifacts,
+ &operation.operation_id,
+ intent,
+ configuration,
+ ),
+ }
+ }
+ QoderModelFileAction::Restore { original_operation } => {
+ let original = stores
+ .control()
+ .load_operation(original_operation)?
+ .ok_or_else(|| conflict("qoder.settings.restore.original"))?;
+ let original_intent = qoder_original_intent(&original, operation, intent)?;
+ drop(stores);
+ hiroute_integrations::stage_qoder_restoration(
+ &self.artifacts,
+ &operation.operation_id,
+ intent,
+ original_operation,
+ &original_intent,
+ )
+ }
+ }
+ }
+}
+
+fn qoder_original_intent(
+ original: &OperationV1,
+ operation: &OperationV1,
+ intent: &ExternalEffectIntentV1,
+) -> PortResult<ExternalEffectIntentV1> {
+ if original.workspace_id != operation.workspace_id
+ || original.state != OperationState::Succeeded
+ || original.operation_id == operation.operation_id
+ {
+ return Err(conflict("qoder.settings.original.owner"));
+ }
+ let original_intent = original
+ .plan
+ .external()
+ .iter()
+ .find(|candidate| {
+ candidate.target() == intent.target() && is_settings_qoder_model(candidate)
+ })
+ .ok_or_else(|| conflict("qoder.settings.original.intent"))?;
+ let before = settings_qoder_model_file_for_operation(original, original_intent)?;
+ let after = settings_qoder_model_file_for_operation(operation, intent)?;
+ if before.context_id != after.context_id
+ || !matches!(before.change, QoderModelFileAction::Configure { .. })
+ {
+ return Err(conflict("qoder.settings.original.context"));
+ }
+ Ok(original_intent.clone())
+}
+
+fn conflict(context: &'static str) -> PortError {
+ PortError::new(PortErrorCode::Conflict, context)
+}
diff --git a/crates/daemon/src/control/runtime/publication/lifecycle.rs b/crates/daemon/src/control/runtime/publication/lifecycle.rs
index c396c529..b0c40de3 100644
--- a/crates/daemon/src/control/runtime/publication/lifecycle.rs
+++ b/crates/daemon/src/control/runtime/publication/lifecycle.rs
@@ -20,6 +20,7 @@ impl LocalControlAdapter {
return Ok(());
}
self.guard_codex_pending_change(None)?;
+ self.guard_qoder_pending_model_change(None)?;
if intent.desired()["transaction"] == "settings" {
hiroute_domain::validate_settings_model_publication_intent(intent)
.map_err(|_| invalid("publication.settings.admission"))?;
@@ -27,6 +28,7 @@ impl LocalControlAdapter {
if let Some(record) = routing_publication_record(intent)
.map_err(|_| invalid("publication.admission.record"))?
{
+ self.validate_qoder_installed_model_budgets(&record)?;
record
.verify()
.map_err(|_| invalid("publication.admission.verify"))?
@@ -73,6 +75,7 @@ impl LocalControlAdapter {
) -> PortResult<()> {
self.require_current_operation(operation)?;
self.guard_codex_pending_change(Some(&operation.operation_id))?;
+ self.guard_qoder_pending_model_change(Some(&operation.operation_id))?;
self.begin_plan_content_activation(operation)?;
// Settings model publications are hot-swappable: the aggregate ArcSwap cutover keeps
// every in-flight pin on its old root, so normal B updates never suspend admission.
@@ -116,6 +119,7 @@ impl LocalControlAdapter {
.record
.as_ref()
.expect("publication_marker always returns the current shape");
+ self.validate_qoder_installed_model_budgets(record)?;
record
.verify()
.map_err(|_| invalid("publication.install.record"))?
diff --git a/crates/daemon/src/control/runtime/qoder_model_budget.rs b/crates/daemon/src/control/runtime/qoder_model_budget.rs
new file mode 100644
index 00000000..115ad939
--- /dev/null
+++ b/crates/daemon/src/control/runtime/qoder_model_budget.rs
@@ -0,0 +1,132 @@
+//! Installed native catalog budgets constrain subsequent publication updates.
+use super::LocalControlAdapter;
+use hiroute_application::agent_connection::{
+ QoderModelFileAction, settings_qoder_model_file_for_operation,
+};
+use hiroute_domain::{
+ AgentAccessGrantRefV1, AgentModelRouteV2, ControlRepositoryPort, OperationStepKind, PortError,
+ PortErrorCode, PortResult, PublicationRecordV1, SecretStorePort, WorkspaceId,
+ is_agent_access_grant_effect,
+};
+
+impl LocalControlAdapter {
+ /// A completed service segment still owns its native tail until exact recovery finishes.
+ /// Do not reinterpret a pending generation as an unconfigured native catalog.
+ pub(super) fn guard_qoder_pending_model_change(
+ &self,
+ same_operation: Option<&hiroute_domain::OperationId>,
+ ) -> PortResult<()> {
+ guard_pending_model_change(self.stores_lock()?.control(), same_operation)
+ }
+
+ /// Run at admission and again before sealing Install. A published smaller budget would
+ /// otherwise leave Qoder sending requests under a larger persisted native declaration.
+ pub(super) fn validate_qoder_installed_model_budgets(
+ &self,
+ record: &PublicationRecordV1,
+ ) -> PortResult<()> {
+ let next = record.verify().map_err(|_| invalid())?;
+ let stores = self.stores_lock()?;
+ for operation in stores.control().succeeded_agent_operations_for_kind(
+ &WorkspaceId::default(),
+ "ApplyAgentConnectionChange",
+ )? {
+ let Some(intent) = operation
+ .plan
+ .external()
+ .iter()
+ .find(|intent| super::native_qoder_model::is_settings_qoder_model(intent))
+ else {
+ continue;
+ };
+ let payload = settings_qoder_model_file_for_operation(&operation, intent)?;
+ let QoderModelFileAction::Configure { models, .. } = payload.change else {
+ continue;
+ };
+ let [mutation] = operation.plan.agent_access_grants() else {
+ return Err(invalid());
+ };
+ let effect = operation
+ .step(OperationStepKind::ApplySecrets)
+ .effects
+ .iter()
+ .find(|effect| is_agent_access_grant_effect(effect))
+ .ok_or_else(invalid)?;
+ let owned = AgentAccessGrantRefV1::from_ensure_effect(effect, mutation)
+ .map_err(|_| invalid())?;
+ let active = stores
+ .secrets()
+ .inspect_agent_access_grant(WorkspaceId::DEFAULT, owned.scope().connection_id())?;
+ if active.as_ref() != Some(&owned) {
+ continue;
+ }
+ // A Restore publication explicitly removes this grant. Its file was restored
+ // before service withdrawal, so its old declaration no longer constrains plans.
+ if !next.grants.iter().any(|grant| {
+ grant.grant_id == owned.grant_id() && grant.generation == owned.generation()
+ }) {
+ continue;
+ }
+ for model in models {
+ let Some(AgentModelRouteV2::Plan { plan_id, .. }) =
+ owned.scope().model_grant().routes.get(&model.alias)
+ else {
+ return Err(invalid());
+ };
+ let plan = next
+ .plans
+ .iter()
+ .find(|plan| plan.agent_plan_id() == plan_id)
+ .ok_or_else(shrinking)?
+ .clone()
+ .into_current()
+ .map_err(|_| shrinking())?;
+ let budget = hiroute_integrations::qoder_plan_token_budget(&plan.body.materialized)
+ .map_err(|_| shrinking())?;
+ if budget.context_window_tokens < model.context_window_tokens
+ || budget.max_output_tokens < model.max_output_tokens
+ {
+ return Err(shrinking());
+ }
+ }
+ }
+ Ok(())
+ }
+}
+
+/// The caller holds the same store lock through admission, so a file tail cannot
+/// become parked between this check and claiming the next Operation.
+pub(super) fn guard_pending_model_change(
+ control: &dyn ControlRepositoryPort,
+ same_operation: Option<&hiroute_domain::OperationId>,
+) -> PortResult<()> {
+ for operation in control.recoverable_operations()? {
+ if same_operation == Some(&operation.operation_id) {
+ continue;
+ }
+ if operation
+ .step(OperationStepKind::Activate)
+ .terminal_result
+ .as_deref()
+ .and_then(hiroute_domain::SettingsServiceCompletionV1::parse)
+ .is_some()
+ && operation
+ .plan
+ .external()
+ .iter()
+ .any(super::native_qoder_model::is_settings_qoder_model)
+ {
+ return Err(PortError::new(
+ PortErrorCode::Conflict,
+ "qoder.pending_file_tail.change",
+ ));
+ }
+ }
+ Ok(())
+}
+fn invalid() -> PortError {
+ PortError::new(PortErrorCode::InvalidData, "qoder.model.budget.binding")
+}
+fn shrinking() -> PortError {
+ PortError::new(PortErrorCode::Conflict, "qoder.model.budget.shrink")
+}
diff --git a/crates/daemon/src/control/runtime/settings_codex_profile.rs b/crates/daemon/src/control/runtime/settings_codex_profile.rs
index e3053cd3..883a186f 100644
--- a/crates/daemon/src/control/runtime/settings_codex_profile.rs
+++ b/crates/daemon/src/control/runtime/settings_codex_profile.rs
@@ -318,46 +318,4 @@ impl LocalControlAdapter {
}
Ok(fields)
}
-
- pub(super) fn retry_codex_operation(
- &self,
- request: &hiroute_application_api::AgentSettingsRetryV1,
- ) -> Result<hiroute_domain::OperationV1, ControlReadError> {
- if request.schema != "hiroute.agent-settings-retry/v1"
- || self
- .settings_agent_for_context(&request.context_id)
- .is_none_or(|class| !class.is_codex())
- {
- return Err(ControlReadError::Denied);
- }
- let stores = self.stores_lock().map_err(super::map_port)?;
- let op = stores
- .control()
- .load_operation(&request.operation_id)
- .map_err(super::map_port)?
- .ok_or(ControlReadError::NotFound)?;
- if op.workspace_id != WorkspaceId::default()
- || op.plan.spec().command_id != "agents.settings.apply"
- || op.plan.spec().resource_id.as_deref() != Some(&request.context_id)
- {
- return Err(ControlReadError::Denied);
- }
- let spec: AgentSettingsSpecV2 =
- serde_json::from_value(op.plan.spec().desired_state.clone())
- .map_err(|_| ControlReadError::Corrupt)?;
- if matches!(spec.model, AgentFacetIntent::Keep) {
- return Err(ControlReadError::Denied);
- }
- drop(stores);
- hiroute_application::TransactionCoordinator::new(
- self,
- self,
- self,
- self,
- self,
- &self.admission,
- )
- .run(&request.operation_id)
- .map_err(|_| ControlReadError::Unavailable)
- }
}
diff --git a/crates/daemon/src/control/runtime/settings_entry_qoder_model_tests.rs b/crates/daemon/src/control/runtime/settings_entry_qoder_model_tests.rs
new file mode 100644
index 00000000..e6e08c7d
--- /dev/null
+++ b/crates/daemon/src/control/runtime/settings_entry_qoder_model_tests.rs
@@ -0,0 +1,614 @@
+//! Additive model settings through the public transaction and real native artifact store.
+use super::*;
+
+fn model_spec(fixture: &QoderFixture) -> serde_json::Value {
+ let publication = fixture
+ .runtime
+ .adapter
+ .stores_lock()
+ .unwrap()
+ .control()
+ .active_publication(&WorkspaceId::default())
+ .unwrap()
+ .unwrap()
+ .verify()
+ .unwrap();
+ let plan = publication
+ .published_agent_plans()
+ .unwrap()
+ .into_iter()
+ .find(|plan| {
+ plan.active
+ && plan
+ .supported_ingress
+ .contains(&AgentIngressProtocolV1::Responses)
+ })
+ .unwrap();
+ json!({"schema_version":{"major":2,"minor":0},"context_id":fixture.context,"model":{"intent":"configure","settings":{"mode":"qoder_additional","allowed_plan_ids":[plan.agent_plan_id]}}})
+}
+fn model_status(fixture: &QoderFixture) -> serde_json::Value {
+ let result = fixture.service.dispatch_wire(request(
+ "GetAgentConnectionStatus",
+ json!({"schema_version":{"major":2,"minor":0},"context_id":fixture.context}),
+ None,
+ ));
+ assert!(result.error.is_none(), "{result:?}");
+ result.data.unwrap()
+}
+fn restore_spec(fixture: &QoderFixture, status: &serde_json::Value) -> serde_json::Value {
+ json!({"schema_version":{"major":2,"minor":0},"context_id":fixture.context,"model":{"intent":"restore","restore_point_ref":status["restore_point_ref"]}})
+}
+
+#[test]
+fn qoder_additional_models_preserve_native_default_and_restore_independently_of_skill() {
+ if crate::test_support::isolated_agent_home(
+ "control::runtime::native_model::tests::settings_entry_tests::qoder::models::qoder_additional_models_preserve_native_default_and_restore_independently_of_skill",
+ ) {
+ return;
+ }
+ let fixture = QoderFixture::with_models(true);
+ let before = fs::read(&fixture.native_config).unwrap();
+ apply(
+ &fixture.service,
+ &fixture.runtime,
+ fixture.configure("explicit"),
+ "qoder-model-skill",
+ );
+ let skill = fs::read(&fixture.skill).unwrap();
+ let spec = model_spec(&fixture);
+ let installed = apply(
+ &fixture.service,
+ &fixture.runtime,
+ spec.clone(),
+ "qoder-model-install",
+ );
+ assert_eq!(installed["state"], "succeeded");
+ let status = model_status(&fixture);
+ assert_eq!(status["state"], "configured");
+ assert_eq!(status["current_selection"], spec["model"]["settings"]);
+ assert_eq!(status["model_verified"], false);
+ assert_eq!(status["live_check_targets"][0]["surface"], "qoder_cli");
+ let configured: serde_json::Value =
+ serde_json::from_slice(&fs::read(&fixture.native_config).unwrap()).unwrap();
+ assert_eq!(configured["model"]["name"], "native/default");
+ assert_eq!(
+ configured["providers"]["native"],
+ json!({"user":"preserved"})
+ );
+ assert_eq!(configured["unknown"], json!({"keep":true}));
+ assert_eq!(
+ fs::metadata(&fixture.native_config)
+ .unwrap()
+ .permissions()
+ .mode()
+ & 0o777,
+ 0o600
+ );
+ assert_eq!(fs::read(&fixture.skill).unwrap(), skill);
+ let provider = hiroute_application::agent_connection::qoder_model_provider_id(&fixture.context);
+ assert_eq!(
+ configured["providers"][&provider]["baseUrl"],
+ "http://127.0.0.1:5837/_hiroute/qoder/v1"
+ );
+ let bearer = configured["providers"][&provider]["apiKey"]
+ .as_str()
+ .unwrap();
+ let stores = fixture.runtime.adapter.stores_lock().unwrap();
+ for operation in stores
+ .control()
+ .succeeded_agent_operations_for_kind(&WorkspaceId::default(), "ApplyAgentConnectionChange")
+ .unwrap()
+ {
+ let operation = stores
+ .control()
+ .load_operation(&operation.operation_id)
+ .unwrap()
+ .unwrap();
+ let serialized = serde_json::to_string(&operation).unwrap();
+ assert!(
+ !serialized.contains(bearer),
+ "connection bearer must stay outside journal"
+ );
+ assert!(
+ !serialized.contains("native/default"),
+ "original configuration stays in encrypted restore material"
+ );
+ }
+ drop(stores);
+ let restore = restore_spec(&fixture, &status);
+ apply(
+ &fixture.service,
+ &fixture.runtime,
+ restore,
+ "qoder-model-restore",
+ );
+ assert_eq!(model_status(&fixture)["state"], "not_configured");
+ assert_eq!(fs::read(&fixture.skill).unwrap(), skill);
+ assert_eq!(
+ serde_json::from_slice::<serde_json::Value>(&fs::read(&fixture.native_config).unwrap())
+ .unwrap(),
+ serde_json::from_slice::<serde_json::Value>(&before).unwrap()
+ );
+ // Re-enabling uses the durable post-revocation generation, never a fresh generation zero.
+ apply(
+ &fixture.service,
+ &fixture.runtime,
+ spec,
+ "qoder-model-reenable",
+ );
+ assert_eq!(model_status(&fixture)["state"], "configured");
+ assert_eq!(fs::read(&fixture.skill).unwrap(), skill);
+}
+
+#[test]
+fn qoder_restore_rejects_native_default_reference_then_preserves_unrelated_edits() {
+ if crate::test_support::isolated_agent_home(
+ "control::runtime::native_model::tests::settings_entry_tests::qoder::models::qoder_restore_rejects_native_default_reference_then_preserves_unrelated_edits",
+ ) {
+ return;
+ }
+ let fixture = QoderFixture::with_models(true);
+ apply(
+ &fixture.service,
+ &fixture.runtime,
+ model_spec(&fixture),
+ "qoder-default-install",
+ );
+ let status = model_status(&fixture);
+ let restore = restore_spec(&fixture, &status);
+ let provider = hiroute_application::agent_connection::qoder_model_provider_id(&fixture.context);
+ let alias = status["live_check_targets"][0]["client_model_ids"][0]
+ .as_str()
+ .unwrap();
+ let mut native: serde_json::Value =
+ serde_json::from_slice(&fs::read(&fixture.native_config).unwrap()).unwrap();
+ native["model"]["name"] = json!(format!("{provider}/{alias}"));
+ native["unknown"]["new_user_value"] = json!(9);
+ private_file(
+ &fixture.native_config,
+ &serde_json::to_vec(&native).unwrap(),
+ );
+ let prior = fs::read(&fixture.native_config).unwrap();
+ let preview = fixture.service.dispatch_wire(request(
+ "PreviewAgentConnectionRestore",
+ json!({"spec":restore}),
+ None,
+ ));
+ assert!(preview.error.is_none(), "{preview:?}");
+ let preview = preview.data.unwrap();
+ assert_eq!(preview["applicable"], false);
+ assert!(
+ preview["blockers"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .any(|block| block["reason"] == "qoder_default_in_use")
+ );
+ assert_eq!(fs::read(&fixture.native_config).unwrap(), prior);
+ assert_eq!(model_status(&fixture)["state"], "configured");
+ native["model"]["name"] = json!("native/default");
+ private_file(
+ &fixture.native_config,
+ &serde_json::to_vec(&native).unwrap(),
+ );
+ apply(
+ &fixture.service,
+ &fixture.runtime,
+ restore,
+ "qoder-default-restore",
+ );
+ let restored: serde_json::Value =
+ serde_json::from_slice(&fs::read(&fixture.native_config).unwrap()).unwrap();
+ assert!(restored["providers"].get(&provider).is_none());
+ assert_eq!(restored["unknown"]["new_user_value"], 9);
+ assert_eq!(restored["model"]["name"], "native/default");
+}
+
+fn smaller_budget_operation(fixture: &QoderFixture) -> (OperationV1, PublicationRecordV1) {
+ let stores = fixture.runtime.adapter.stores_lock().unwrap();
+ let current = stores
+ .control()
+ .active_publication(&WorkspaceId::default())
+ .unwrap()
+ .unwrap();
+ let mut next = current.verify().unwrap();
+ let alias = next
+ .grants
+ .iter()
+ .find(|grant| grant.model_grant.protocol == AgentIngressProtocolV1::Responses)
+ .unwrap()
+ .model_grant
+ .routes
+ .keys()
+ .next()
+ .unwrap()
+ .clone();
+ let index = next
+ .plans
+ .iter()
+ .position(|plan| plan.model_alias().as_str() == alias)
+ .unwrap();
+ // The shared publication fixture predates durable Plan heads. Adopt its authenticated
+ // current compiled content through the same existing first-edit compatibility path.
+ let original_version = hiroute_domain::PlanVersionV1::from_unversioned_compiled_recovery(
+ WorkspaceId::default(),
+ next.plans[index].clone(),
+ )
+ .unwrap();
+ if next.plan_heads.is_empty() {
+ next.plan_heads = next
+ .plans
+ .iter()
+ .cloned()
+ .map(|plan| {
+ let version = hiroute_domain::PlanVersionV1::from_unversioned_compiled_recovery(
+ WorkspaceId::default(),
+ plan,
+ )
+ .unwrap();
+ hiroute_domain::PlanHeadV1 {
+ head_revision: version.reference.content_revision,
+ model_alias: version.compiled.model_alias().clone(),
+ reference: version.reference,
+ status: hiroute_domain::PlanLifecycleV1::Enabled,
+ }
+ })
+ .collect();
+ next.plan_heads
+ .sort_by(|a, b| a.reference.plan_id.cmp(&b.reference.plan_id));
+ }
+ let before = next
+ .plan_heads
+ .iter()
+ .find(|head| head.reference.plan_id == *next.plans[index].agent_plan_id())
+ .unwrap()
+ .clone();
+ let mut body = (*next.plans[index].body).clone();
+ let budget = hiroute_integrations::qoder_plan_token_budget(&body.materialized).unwrap();
+ body.materialized.attempt_owned.limits.context_window_tokens =
+ Some(budget.context_window_tokens - 1);
+ body.agent_plan_revision += 1;
+ body.materialized_route_digest = body.materialized.route_digest().unwrap();
+ let compiled = hiroute_domain::CompiledAgentPlanV1::seal_current(body).unwrap();
+ let legacy = hiroute_domain::PlanVersionV1::from_unversioned_compiled_recovery(
+ WorkspaceId::default(),
+ compiled.clone(),
+ )
+ .unwrap();
+ let version =
+ hiroute_domain::PlanVersionV1::new(WorkspaceId::default(), legacy.configuration, compiled)
+ .unwrap();
+ let head = hiroute_domain::PlanHeadV1 {
+ reference: version.reference.clone(),
+ head_revision: before.head_revision + 1,
+ model_alias: version.compiled.model_alias().clone(),
+ status: hiroute_domain::PlanLifecycleV1::Enabled,
+ };
+ let mut heads = next.plan_heads.clone();
+ *heads
+ .iter_mut()
+ .find(|item| item.reference.plan_id == head.reference.plan_id)
+ .unwrap() = head.clone();
+ let next = next
+ .next_with_plan_content(
+ hiroute_domain::GatewayPublicationRevision::new(current.publication_revision.get() + 1)
+ .unwrap(),
+ next.alias_registry.clone(),
+ version.compiled.clone(),
+ heads,
+ )
+ .unwrap();
+ let record = PublicationRecordV1::from_publication(WorkspaceId::default(), &next).unwrap();
+ let change = api::PlanContentChangeV2 {
+ schema: api::PLAN_CONTENT_CHANGE_SCHEMA_V2.into(),
+ target: api::PlanContentTargetV2::Update {
+ plan_id: head.reference.plan_id.clone(),
+ expected_head_revision: before.head_revision,
+ },
+ editor: version
+ .configuration
+ .editor(Some(head.model_alias.as_str().into()))
+ .unwrap(),
+ consumed_draft: None,
+ };
+ let spec = hiroute_domain::ChangeSpecV1 {
+ schema_version: hiroute_domain::CHANGE_SPEC_SCHEMA_V1,
+ command_id: "routing.apply".into(),
+ resource_id: Some(format!("agent-plan/{}", head.reference.plan_id.as_str())),
+ desired_state: serde_json::to_value(change).unwrap(),
+ };
+ let plan = hiroute_domain::TransactionPlanV1::from_plan_content_planner(
+ spec,
+ version,
+ head,
+ Some(before),
+ None,
+ record.clone(),
+ Some(current.digest),
+ )
+ .unwrap()
+ .with_legacy_plan_source(original_version)
+ .unwrap();
+ let scope = hiroute_domain::IdempotencyScopeV1::new(
+ "interactive-user",
+ "ApplyAgentPlanChange",
+ "qoder-smaller-budget",
+ )
+ .unwrap();
+ let digest = CanonicalDigest::of_bytes(b"qoder-smaller-budget");
+ let operation = OperationV1::new(
+ OperationId::derive(&WorkspaceId::default(), &scope, &digest),
+ WorkspaceId::default(),
+ scope,
+ digest.clone(),
+ digest,
+ stores
+ .control()
+ .current_revisions(&WorkspaceId::default())
+ .unwrap(),
+ plan,
+ )
+ .unwrap();
+ (operation, record)
+}
+
+#[test]
+fn qoder_installed_budget_rejects_publication_admission_and_install_checkpoint_without_cutover() {
+ if crate::test_support::isolated_agent_home(
+ "control::runtime::native_model::tests::settings_entry_tests::qoder::models::qoder_installed_budget_rejects_publication_admission_and_install_checkpoint_without_cutover",
+ ) {
+ return;
+ }
+ let fixture = QoderFixture::with_models(true);
+ apply(
+ &fixture.service,
+ &fixture.runtime,
+ model_spec(&fixture),
+ "qoder-budget-install",
+ );
+ let bytes = fs::read(&fixture.native_config).unwrap();
+ let before_status = model_status(&fixture);
+ let (operation, _) = smaller_budget_operation(&fixture);
+ let intent = operation.plan.external()[0].clone();
+ let error = fixture
+ .runtime
+ .adapter
+ .validate_external_admission(&intent)
+ .unwrap_err();
+ assert_eq!(
+ hiroute_application::TransactionError::Port(error.clone()).error_code(),
+ api::ErrorCode::QoderModelBudgetConflict
+ );
+ assert_eq!(error.context, "qoder.model.budget.shrink");
+ assert!(
+ fixture
+ .runtime
+ .adapter
+ .stores_lock()
+ .unwrap()
+ .control()
+ .load_operation(&operation.operation_id)
+ .unwrap()
+ .is_none()
+ );
+ // Inject an already-admitted checkpoint to exercise the independent recovery-time guard.
+ // Public admission above rejected this same record before journal mutation.
+ let stores = fixture.runtime.adapter.stores_lock().unwrap();
+ assert_eq!(
+ stores.control().begin_local_operation(&operation).unwrap(),
+ hiroute_domain::BeginOperationOutcome::Created
+ );
+ drop(stores);
+ // Recovery must reach the independent Install guard through the production
+ // coordinator, compensate the staged publication, and retain the public error.
+ let adapter = fixture.runtime.adapter.as_ref();
+ let recovered = hiroute_application::TransactionCoordinator::new(
+ adapter,
+ adapter,
+ adapter,
+ adapter,
+ adapter,
+ &adapter.admission,
+ )
+ .run(&operation.operation_id)
+ .unwrap();
+ assert_eq!(
+ recovered.state,
+ OperationState::RolledBack,
+ "{recovered:#?}"
+ );
+ assert_eq!(
+ recovered.safe_error_code.as_deref(),
+ Some("QODER_MODEL_BUDGET_CONFLICT")
+ );
+ assert_eq!(fs::read(&fixture.native_config).unwrap(), bytes);
+ assert_eq!(model_status(&fixture), before_status);
+}
+
+#[test]
+fn qoder_pending_file_tail_keeps_collaboration_preview_independent_and_retries_exact_operation() {
+ if crate::test_support::isolated_agent_home(
+ "control::runtime::native_model::tests::settings_entry_tests::qoder::models::qoder_pending_file_tail_keeps_collaboration_preview_independent_and_retries_exact_operation",
+ ) {
+ return;
+ }
+ let fixture = QoderFixture::with_models(true);
+ let before = fs::read(&fixture.native_config).unwrap();
+ let spec = model_spec(&fixture);
+ let mut ports = fixture
+ .runtime
+ .application_ports()
+ .with_agent_connection(Arc::new(FixtureFacts::collaboration(
+ fixture.runtime.adapter.clone(),
+ )));
+ ports.mutation = Some(Arc::new(super::super::fault::FileRace {
+ adapter: fixture.runtime.adapter.clone(),
+ path: fixture.native_config.clone(),
+ fail_after_file: false,
+ }));
+ let racing = LocalControlDaemon::new(ApplicationService::new(ports));
+ let preview = racing.dispatch_wire(request(
+ "PreviewAgentConnectionChange",
+ json!({"spec":spec}),
+ None,
+ ));
+ assert!(preview.error.is_none(), "{preview:?}");
+ let preview = preview.data.unwrap();
+ assert_eq!(preview["applicable"], true);
+ let parked = racing.dispatch_wire(request(
+ "ApplyAgentConnectionChange",
+ json!({"spec":spec,
+ "accept_digest":preview["accept_digest"],"dependency_digest":preview["dependency_digest"],
+ "expected_revisions":preview["expected_revisions"],"idempotency_key":"qoder-parked-model"}),
+ None,
+ ));
+ assert!(parked.error.is_none(), "{parked:?}");
+ let parked = parked.data.unwrap();
+ assert_eq!(parked["state"], "activating");
+ assert_eq!(model_status(&fixture)["state"], "pending");
+ let id: OperationId = serde_json::from_value(parked["operation_id"].clone()).unwrap();
+ assert!(
+ fixture
+ .runtime
+ .adapter
+ .guard_qoder_pending_model_change(None)
+ .is_err()
+ );
+ assert!(
+ fixture
+ .runtime
+ .adapter
+ .guard_qoder_pending_model_change(Some(&id))
+ .is_ok()
+ );
+ let blocked = fixture.service.dispatch_wire(request(
+ "PreviewAgentConnectionChange",
+ json!({"spec":spec}),
+ None,
+ ));
+ assert!(blocked.error.is_some());
+ // A collaboration preview still does not read the damaged native model file. Its Apply
+ // must wait for the old tail because the existing coordinator owns one Control revision.
+ let skill_preview = fixture.service.dispatch_wire(request(
+ "PreviewAgentConnectionChange",
+ json!({"spec":fixture.configure("explicit")}),
+ None,
+ ));
+ assert!(skill_preview.error.is_none(), "{skill_preview:?}");
+ let skill_preview = skill_preview.data.unwrap();
+ assert_eq!(skill_preview["applicable"], true);
+ let revisions = fixture
+ .runtime
+ .adapter
+ .stores_lock()
+ .unwrap()
+ .control()
+ .current_revisions(&WorkspaceId::default())
+ .unwrap();
+ let deferred = fixture.service.dispatch_wire(request("ApplyAgentConnectionChange", json!({
+ "spec":fixture.configure("explicit"), "accept_digest":skill_preview["accept_digest"],
+ "dependency_digest":skill_preview["dependency_digest"], "expected_revisions":skill_preview["expected_revisions"],
+ "idempotency_key":"qoder-skill-before-tail-recovery"}), None));
+ assert!(deferred.error.is_some());
+ assert!(deferred.operation.is_none());
+ assert!(!fixture.skill.exists());
+ let stores = fixture.runtime.adapter.stores_lock().unwrap();
+ assert_eq!(
+ stores
+ .control()
+ .current_revisions(&WorkspaceId::default())
+ .unwrap(),
+ revisions
+ );
+ let scope = hiroute_domain::IdempotencyScopeV1::new(
+ "interactive-user",
+ "ApplyAgentConnectionChange",
+ "qoder-skill-before-tail-recovery",
+ )
+ .unwrap();
+ assert!(
+ stores
+ .control()
+ .operation_for_idempotency(&WorkspaceId::default(), &scope)
+ .unwrap()
+ .is_none()
+ );
+ drop(stores);
+ let wrong = fixture.service.dispatch_wire(request("ApplyAgentConnectionChange", json!({
+ "schema":"hiroute.agent-settings-retry/v1","context_id":fixture.runtime.adapter.settings_context(SettingsAgentClass::Codex),"operation_id":id}),None));
+ assert!(wrong.error.is_some());
+ assert_eq!(model_status(&fixture)["state"], "pending");
+ private_file(&fixture.native_config, &before);
+ let request_body = json!({"schema":"hiroute.agent-settings-retry/v1","context_id":fixture.context,"operation_id":id});
+ for _ in 0..2 {
+ let resumed = fixture.service.dispatch_wire(request(
+ "ApplyAgentConnectionChange",
+ request_body.clone(),
+ None,
+ ));
+ assert!(resumed.error.is_none(), "{resumed:?}");
+ let resumed = resumed.data.unwrap();
+ assert_eq!(resumed["state"], "succeeded");
+ assert_eq!(resumed["operation_id"], parked["operation_id"]);
+ }
+ assert_eq!(model_status(&fixture)["state"], "configured");
+ assert!(
+ fixture
+ .runtime
+ .adapter
+ .guard_qoder_pending_model_change(None)
+ .is_ok()
+ );
+ apply(
+ &fixture.service,
+ &fixture.runtime,
+ fixture.configure("explicit"),
+ "qoder-skill-after-tail",
+ );
+ assert!(fixture.skill.exists());
+}
+
+#[test]
+fn qoder_managed_bearer_permission_drift_revokes_live_eligibility_but_allows_restore() {
+ if crate::test_support::isolated_agent_home(
+ "control::runtime::native_model::tests::settings_entry_tests::qoder::models::qoder_managed_bearer_permission_drift_revokes_live_eligibility_but_allows_restore",
+ ) {
+ return;
+ }
+ let fixture = QoderFixture::with_models(true);
+ // An unmanaged user file may be readable by others; the confirmed managed write seals it.
+ fs::set_permissions(&fixture.native_config, fs::Permissions::from_mode(0o644)).unwrap();
+ apply(
+ &fixture.service,
+ &fixture.runtime,
+ model_spec(&fixture),
+ "qoder-permission-install",
+ );
+ let status = model_status(&fixture);
+ assert_eq!(status["state"], "configured");
+ assert_eq!(
+ fs::metadata(&fixture.native_config)
+ .unwrap()
+ .permissions()
+ .mode()
+ & 0o777,
+ 0o600
+ );
+ fs::set_permissions(&fixture.native_config, fs::Permissions::from_mode(0o644)).unwrap();
+ let drift = model_status(&fixture);
+ assert_eq!(drift["state"], "drift");
+ assert_eq!(drift["model_verified"], false);
+ assert!(drift["live_check_targets"].is_null() || drift["live_check_targets"] == json!([]));
+ apply(
+ &fixture.service,
+ &fixture.runtime,
+ restore_spec(&fixture, &status),
+ "qoder-permission-restore",
+ );
+ assert_eq!(model_status(&fixture)["state"], "not_configured");
+ let restored: serde_json::Value =
+ serde_json::from_slice(&fs::read(&fixture.native_config).unwrap()).unwrap();
+ assert_eq!(restored["model"]["name"], "native/default");
+ let provider = hiroute_application::agent_connection::qoder_model_provider_id(&fixture.context);
+ assert!(restored["providers"].get(&provider).is_none());
+}
diff --git a/crates/daemon/src/control/runtime/settings_entry_qoder_tests.rs b/crates/daemon/src/control/runtime/settings_entry_qoder_tests.rs
new file mode 100644
index 00000000..17e7c201
--- /dev/null
+++ b/crates/daemon/src/control/runtime/settings_entry_qoder_tests.rs
@@ -0,0 +1,618 @@
+//! Public V2 settings -> coordinator -> real stores and Skill files. The explicit capability
+//! fixture does not prove native Qoder loading or real delegation; product acceptance does.
+use super::*;
+use crate::control::runtime::settings_facts::SettingsAgentClass;
+use hiroute_integrations::QoderCollaborationProbeTarget;
+use std::path::{Path, PathBuf};
+
+struct QoderFixture {
+ _root: tempfile::TempDir,
+ runtime: ProductionControlRuntime,
+ service: LocalControlDaemon,
+ context: String,
+ native_config: PathBuf,
+ skill: PathBuf,
+ untouched: Vec<(PathBuf, Vec<u8>)>,
+}
+
+impl QoderFixture {
+ fn new() -> Self {
+ Self::with_models(false)
+ }
+
+ fn with_models(models: bool) -> Self {
+ let root = tempfile::tempdir().unwrap();
+ fs::set_permissions(root.path(), fs::Permissions::from_mode(0o700)).unwrap();
+ let home = PathBuf::from(std::env::var_os("HOME").unwrap());
+ let config_root = home.join("selected-qoder");
+ private_file(
+ &config_root.join("settings.json"),
+ b"native settings are opaque to HiRoute\n",
+ );
+ let executable = root.path().join("qoder-fixture");
+ private_file(&executable, b"#!/bin/sh\nexit 97\n");
+ fs::set_permissions(&executable, fs::Permissions::from_mode(0o700)).unwrap();
+ let mut layout = AgentFilesystemLayoutV1::from_process(&home, root.path());
+ layout.codex_executable = root.path().join("missing-codex");
+ layout.claude_executable = root.path().join("missing-claude");
+ layout.qoder_executable = executable;
+ layout.qoder_home = home.clone();
+ layout.qoder_config_root = config_root.clone();
+ let registry = serde_json::from_slice(include_bytes!(
+ "../../../../../assets/connector-registry/current/registry-seed.json"
+ ))
+ .unwrap();
+ let model_data: hiroute_domain::ReleaseModelDataBundleV2 = serde_json::from_slice(
+ include_bytes!("../../../../../assets/release-facts/current/bundle/model-data.json"),
+ )
+ .unwrap();
+ let scanner = FilesystemAgentScannerV1::new(
+ layout,
+ ClaudeRegistrationIndexV1::from_verified_model_data(&registry, &model_data.data)
+ .unwrap(),
+ );
+ let native_config = scanner.qoder_user_config_target();
+ let skill = scanner.qoder_user_skill_target();
+ // Native executables/workspace are not storage contents. Production deliberately
+ // refuses to initialize a store over an unrelated pre-existing file tree.
+ let storage = root.path().join("storage");
+ let runtime = ProductionControlRuntime::prepare_for_role_all_with_scanner(
+ &storage,
+ crate::release_catalog::fixture_catalog(),
+ None,
+ scanner,
+ )
+ .unwrap();
+ let runtime = if models {
+ configure_runtime_with_initial(&storage, runtime, golden_publication_plans_only())
+ } else {
+ runtime
+ };
+ if models {
+ private_file(&native_config, br#"{"model":{"name":"native/default"},"providers":{"native":{"user":"preserved"}},"unknown":{"keep":true}}"#);
+ }
+ runtime.adapter.reconcile_startup_and_open().unwrap();
+ let context = runtime
+ .adapter
+ .settings_context_for_agent("agent_qoder_default")
+ .unwrap();
+ let service = LocalControlDaemon::new(ApplicationService::new(
+ runtime.application_ports().with_agent_connection(Arc::new(
+ FixtureFacts::collaboration(runtime.adapter.clone()),
+ )),
+ ));
+ let mut untouched = vec![(native_config.clone(), fs::read(&native_config).unwrap())];
+ for path in [
+ config_root.join("auth.json"),
+ config_root.join("skills/personal/SKILL.md"),
+ home.join(".qoder/settings.json"),
+ home.join(".hiroute/credential-artifacts/qoder.sealed"),
+ home.join(".hiroute/credential-artifacts/codex.sealed"),
+ home.join(".hiroute/credential-artifacts/claude-code.sealed"),
+ ] {
+ let bytes = b"synthetic user-owned sentinel; never a HiRoute credential\n".to_vec();
+ private_file(&path, &bytes);
+ untouched.push((path, bytes));
+ }
+ Self {
+ _root: root,
+ runtime,
+ service,
+ context,
+ native_config,
+ skill,
+ untouched,
+ }
+ }
+
+ fn configure(&self, mode: &str) -> serde_json::Value {
+ json!({"schema_version":{"major":2,"minor":0},"context_id":self.context,
+ "collaboration":{"intent":"configure","settings":{"trigger_mode":mode}}})
+ }
+
+ fn status(&self) -> serde_json::Value {
+ let response = self.service.dispatch_wire(request(
+ "GetAgentConnectionStatus",
+ json!({"schema_version":{"major":2,"minor":0},"context_id":self.context}),
+ None,
+ ));
+ assert!(response.error.is_none(), "{response:?}");
+ let status = response.data.unwrap();
+ assert_eq!(status["schema"], "hiroute.agent-model-settings-status/v2");
+ assert_eq!(status["context_id"], self.context);
+ assert_eq!(status["state"], "not_configured");
+ assert_eq!(status["model_verified"], false);
+ assert_eq!(status["current_selection"], serde_json::Value::Null);
+ assert!(
+ status["live_check_targets"].is_null() || status["live_check_targets"] == json!([])
+ );
+ status
+ }
+
+ fn restore(&self) -> serde_json::Value {
+ json!({"schema_version":{"major":2,"minor":0},"context_id":self.context,
+ "collaboration":{"intent":"restore","restore_point_ref":self.status()["collaboration"]["restore_point_ref"]}})
+ }
+
+ fn assert_no_model_effects(&self) {
+ for (path, bytes) in &self.untouched {
+ assert_eq!(
+ fs::read(path).unwrap(),
+ *bytes,
+ "changed {}",
+ path.display()
+ );
+ }
+ let stores = self.runtime.adapter.stores_lock().unwrap();
+ assert!(
+ stores
+ .control()
+ .active_publication(&WorkspaceId::default())
+ .unwrap()
+ .is_none()
+ );
+ assert!(
+ stores
+ .secrets()
+ .inspect_agent_access_grant(
+ WorkspaceId::DEFAULT,
+ &format!("agent-connection/{}", self.context)
+ )
+ .unwrap()
+ .is_none()
+ );
+ assert_eq!(
+ stores
+ .secrets()
+ .agent_access_grant_generation(
+ WorkspaceId::DEFAULT,
+ &format!("agent-connection/{}", self.context)
+ )
+ .unwrap(),
+ 0
+ );
+ for operation in stores
+ .control()
+ .succeeded_agent_operations_for_kinds(
+ &WorkspaceId::default(),
+ &["ApplyAgentConnectionChange", "ApplyAgentConnectionRestore"],
+ )
+ .unwrap()
+ {
+ assert!(operation.plan.agent_access_grants().is_empty());
+ let target = SettingsAgentClass::Qoder.skill_target().unwrap();
+ assert!(
+ operation
+ .plan
+ .external()
+ .iter()
+ .all(|effect| effect.target() == target)
+ );
+ }
+ }
+}
+
+fn private_file(path: &Path, bytes: &[u8]) {
+ let parent = path.parent().unwrap();
+ fs::create_dir_all(parent).unwrap();
+ fs::set_permissions(parent, fs::Permissions::from_mode(0o700)).unwrap();
+ fs::write(path, bytes).unwrap();
+ fs::set_permissions(path, fs::Permissions::from_mode(0o600)).unwrap();
+}
+
+#[test]
+fn qoder_collaboration_configure_trigger_replay_and_restore_preserve_native_context() {
+ if crate::test_support::isolated_agent_home(
+ "control::runtime::native_model::tests::settings_entry_tests::qoder::qoder_collaboration_configure_trigger_replay_and_restore_preserve_native_context",
+ ) {
+ return;
+ }
+ let fixture = QoderFixture::new();
+ assert!(!SettingsAgentClass::Qoder.is_codex());
+ assert_ne!(
+ fixture.context,
+ fixture
+ .runtime
+ .adapter
+ .settings_context(SettingsAgentClass::Codex)
+ );
+ assert!(
+ fixture
+ .native_config
+ .ends_with("selected-qoder/settings.json")
+ );
+ let initial: api::AgentSettingsSpecV2 =
+ serde_json::from_value(fixture.configure("explicit")).unwrap();
+ let facts = fixture
+ .runtime
+ .adapter
+ .capture_settings_facts(&initial)
+ .unwrap();
+ assert!(facts.model_file.is_none());
+ assert!(facts.facts.model.is_none());
+ assert!(matches!(
+ fixture
+ .runtime
+ .adapter
+ .qoder_collaboration_probe_target()
+ .unwrap(),
+ QoderCollaborationProbeTarget::PreinstallCapability
+ ));
+ let ordinary =
+ LocalControlDaemon::new(ApplicationService::new(fixture.runtime.application_ports()));
+ let blocked = ordinary.dispatch_wire(request(
+ "PreviewAgentConnectionChange",
+ json!({"spec":initial}),
+ None,
+ ));
+ assert!(blocked.error.is_none(), "{blocked:?}");
+ let blocked = blocked.data.unwrap();
+ assert_eq!(blocked["applicable"], false);
+ assert!(
+ blocked["blockers"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .any(|blocker| blocker["reason"] == "capability_unavailable")
+ );
+
+ apply(
+ &fixture.service,
+ &fixture.runtime,
+ fixture.configure("delegate_by_default"),
+ "qoder-enable",
+ );
+ assert_eq!(
+ fixture.status()["collaboration"]["current_selection"]["trigger_mode"],
+ "delegate_by_default"
+ );
+ let first = fs::read(&fixture.skill).unwrap();
+ assert!(
+ matches!(fixture.runtime.adapter.qoder_collaboration_probe_target().unwrap(),
+ QoderCollaborationProbeTarget::InstalledUserSkill { expected_content }
+ if expected_content == CanonicalDigest::of_bytes(&first))
+ );
+ apply(
+ &fixture.service,
+ &fixture.runtime,
+ fixture.configure("explicit"),
+ "qoder-explicit",
+ );
+ let second = fs::read(&fixture.skill).unwrap();
+ assert_ne!(first, second);
+ assert_eq!(
+ fixture.status()["collaboration"]["current_selection"]["trigger_mode"],
+ "explicit"
+ );
+ fixture.assert_no_model_effects();
+ apply(
+ &fixture.service,
+ &fixture.runtime,
+ fixture.restore(),
+ "qoder-disable",
+ );
+ assert_eq!(fixture.status()["collaboration"]["state"], "restored");
+ assert!(!fixture.skill.exists());
+ fixture.assert_no_model_effects();
+}
+
+#[test]
+fn qoder_restore_only_rejects_change_entry_without_mutation_and_restore_remains_readable() {
+ if crate::test_support::isolated_agent_home(
+ "control::runtime::native_model::tests::settings_entry_tests::qoder::qoder_restore_only_rejects_change_entry_without_mutation_and_restore_remains_readable",
+ ) {
+ return;
+ }
+ let fixture = QoderFixture::new();
+ apply(
+ &fixture.service,
+ &fixture.runtime,
+ fixture.configure("explicit"),
+ "qoder-restore-entry-enable",
+ );
+ let before_skill = fs::read(&fixture.skill).unwrap();
+ let before_status = fixture.status();
+ let before_revisions = fixture
+ .runtime
+ .adapter
+ .stores_lock()
+ .unwrap()
+ .control()
+ .current_revisions(&WorkspaceId::default())
+ .unwrap();
+ let spec = fixture.restore();
+ let wrong_preview = fixture.service.dispatch_wire(request(
+ "PreviewAgentConnectionChange",
+ json!({"spec":spec}),
+ None,
+ ));
+ assert_eq!(
+ wrong_preview.error.unwrap().code,
+ api::ErrorCode::InvalidArguments
+ );
+ assert!(wrong_preview.operation.is_none());
+
+ // A genuine Restore confirmation is still invalid on the Change descriptor. Reject
+ // before admission rather than writing a succeeded journal row the strict reader rejects.
+ let preview = fixture.service.dispatch_wire(request(
+ "PreviewAgentConnectionRestore",
+ json!({"spec":spec}),
+ None,
+ ));
+ assert!(preview.error.is_none(), "{preview:?}");
+ let preview = preview.data.unwrap();
+ assert_eq!(preview["applicable"], true);
+ let key = "qoder-restore-entry";
+ let wrong_apply = fixture.service.dispatch_wire(request(
+ "ApplyAgentConnectionChange",
+ json!({"spec":spec,"accept_digest":preview["accept_digest"],
+ "dependency_digest":preview["dependency_digest"],"expected_revisions":preview["expected_revisions"],
+ "idempotency_key":key}),
+ None,
+ ));
+ assert_eq!(
+ wrong_apply.error.unwrap().code,
+ api::ErrorCode::InvalidArguments
+ );
+ assert!(wrong_apply.operation.is_none());
+ {
+ let stores = fixture.runtime.adapter.stores_lock().unwrap();
+ let control = stores.control();
+ assert_eq!(
+ control.current_revisions(&WorkspaceId::default()).unwrap(),
+ before_revisions
+ );
+ assert!(control.writer_claim_operation().unwrap().is_none());
+ for kind in ["ApplyAgentConnectionChange", "ApplyAgentConnectionRestore"] {
+ let scope =
+ hiroute_domain::IdempotencyScopeV1::new("interactive-user", kind, key).unwrap();
+ assert!(
+ control
+ .operation_for_idempotency(&WorkspaceId::default(), &scope)
+ .unwrap()
+ .is_none()
+ );
+ }
+ }
+ assert_eq!(fs::read(&fixture.skill).unwrap(), before_skill);
+ assert_eq!(fixture.status(), before_status);
+
+ // The same idempotency key remains usable on the correct descriptor. The shared apply
+ // helper replays the exact confirmation; status exercises the strict succeeded reader.
+ let restored = apply(&fixture.service, &fixture.runtime, spec, key);
+ assert_eq!(fixture.status()["collaboration"]["state"], "restored");
+ assert!(!fixture.skill.exists());
+ let operation_id = OperationId::parse(restored["operation_id"].as_str().unwrap()).unwrap();
+ let restored = fixture
+ .runtime
+ .adapter
+ .stores_lock()
+ .unwrap()
+ .control()
+ .load_operation(&operation_id)
+ .unwrap()
+ .unwrap();
+ assert_eq!(
+ restored.idempotency.operation_kind,
+ "ApplyAgentConnectionRestore"
+ );
+ fixture.assert_no_model_effects();
+}
+
+#[test]
+fn qoder_cross_client_model_and_unowned_restore_intents_are_rejected_before_any_operation() {
+ if crate::test_support::isolated_agent_home(
+ "control::runtime::native_model::tests::settings_entry_tests::qoder::qoder_cross_client_model_and_unowned_restore_intents_are_rejected_before_any_operation",
+ ) {
+ return;
+ }
+ let fixture = QoderFixture::new();
+ let model = json!({"intent":"configure","settings":{"mode":"codex_default",
+ "native_model_mode":"hiroute_only","fixed_models":[],"allowed_plan_ids":["plan-qoder-forbidden"],
+ "default_selection":{"kind":"plan","plan_id":"plan-qoder-forbidden"}}});
+ for (intent, token) in [
+ (model.clone(), json!({"intent":"keep"})),
+ (model.clone(), json!({"intent":"regenerate"})),
+ (
+ model,
+ json!({"intent":"set","input_slot":"agent-access-token-candidate/forbidden"}),
+ ),
+ (
+ json!({"intent":"restore","restore_point_ref":"restore-point/forbidden"}),
+ json!({"intent":"keep"}),
+ ),
+ ] {
+ let mut spec = fixture.configure("explicit");
+ spec["model"] = intent;
+ spec["access_token"] = token;
+ let restore = spec["model"]["intent"] == "restore";
+ if restore {
+ spec["collaboration"] = json!({"intent":"keep"});
+ }
+ let command = if restore {
+ "PreviewAgentConnectionRestore"
+ } else {
+ "PreviewAgentConnectionChange"
+ };
+ let rejected = fixture
+ .service
+ .dispatch_wire(request(command, json!({"spec":spec}), None));
+ let expected = if restore {
+ api::ErrorCode::ResourceNotFound
+ } else {
+ api::ErrorCode::InvalidArguments
+ };
+ assert_eq!(rejected.error.unwrap().code, expected);
+ assert!(rejected.operation.is_none());
+ // Even a caller carrying a real collaboration preview cannot smuggle a model/token
+ // intent past the backend confirmation boundary. Depending on the supplied intent,
+ // its changed dependencies or the invalid model selection can reject first.
+ let preview = fixture
+ .service
+ .dispatch_wire(request(
+ "PreviewAgentConnectionChange",
+ json!({"spec":fixture.configure("explicit")}),
+ None,
+ ))
+ .data
+ .unwrap();
+ let rejected = fixture.service.dispatch_wire(request(
+ if restore { "ApplyAgentConnectionRestore" } else { "ApplyAgentConnectionChange" },
+ json!({"spec":spec,"accept_digest":preview["accept_digest"],
+ "dependency_digest":preview["dependency_digest"],"expected_revisions":preview["expected_revisions"],
+ "idempotency_key":"qoder-forbidden-model"}), None));
+ assert!(matches!(
+ rejected.error.unwrap().code,
+ api::ErrorCode::InvalidArguments
+ | api::ErrorCode::ChangePreviewStale
+ | api::ErrorCode::ResourceNotFound
+ ));
+ assert!(rejected.operation.is_none());
+ }
+ assert!(!fixture.skill.exists());
+ fixture.assert_no_model_effects();
+}
+
+#[test]
+fn qoder_owned_skill_drift_rejects_stale_apply_and_keeps_installed_verification_phase() {
+ if crate::test_support::isolated_agent_home(
+ "control::runtime::native_model::tests::settings_entry_tests::qoder::qoder_owned_skill_drift_rejects_stale_apply_and_keeps_installed_verification_phase",
+ ) {
+ return;
+ }
+ let fixture = QoderFixture::new();
+ apply(
+ &fixture.service,
+ &fixture.runtime,
+ fixture.configure("explicit"),
+ "qoder-drift-enable",
+ );
+ let restore = fixture.restore();
+ let preview = fixture
+ .service
+ .dispatch_wire(request(
+ "PreviewAgentConnectionRestore",
+ json!({"spec":restore}),
+ None,
+ ))
+ .data
+ .unwrap();
+ assert_eq!(preview["applicable"], true);
+ let edited = b"user changed this installed skill\n";
+ private_file(&fixture.skill, edited);
+ let edited_status = fixture.status();
+ assert_eq!(edited_status["collaboration"]["state"], "drift");
+ assert!(edited_status["collaboration"]["current_selection"].is_null());
+ assert_eq!(
+ edited_status["collaboration"]["restore_point_ref"],
+ restore["collaboration"]["restore_point_ref"]
+ );
+ assert!(
+ matches!(fixture.runtime.adapter.qoder_collaboration_probe_target().unwrap(),
+ QoderCollaborationProbeTarget::InstalledUserSkill { expected_content }
+ if expected_content != CanonicalDigest::of_bytes(edited))
+ );
+ let stale = fixture.service.dispatch_wire(request("ApplyAgentConnectionRestore", json!({
+ "spec":restore,"accept_digest":preview["accept_digest"],"dependency_digest":preview["dependency_digest"],
+ "expected_revisions":preview["expected_revisions"],"idempotency_key":"qoder-stale-restore"}), None));
+ assert!(stale.error.is_some(), "{stale:?}");
+ let fresh = fixture
+ .service
+ .dispatch_wire(request(
+ "PreviewAgentConnectionRestore",
+ json!({"spec":restore}),
+ None,
+ ))
+ .data
+ .unwrap();
+ assert_eq!(fresh["applicable"], false);
+ assert!(
+ fresh["blockers"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .any(|blocker| blocker["reason"] == "skill_file_conflict")
+ );
+ assert_eq!(fs::read(&fixture.skill).unwrap(), edited);
+ fs::remove_file(&fixture.skill).unwrap();
+ let missing_status = fixture.status();
+ assert_eq!(missing_status["collaboration"]["state"], "drift");
+ assert!(missing_status["collaboration"]["current_selection"].is_null());
+ assert!(matches!(
+ fixture
+ .runtime
+ .adapter
+ .qoder_collaboration_probe_target()
+ .unwrap(),
+ QoderCollaborationProbeTarget::InstalledUserSkill { .. }
+ ));
+ fixture.assert_no_model_effects();
+}
+
+#[test]
+fn qoder_borrowed_skill_restore_releases_only_the_reference_after_user_edits() {
+ if crate::test_support::isolated_agent_home(
+ "control::runtime::native_model::tests::settings_entry_tests::qoder::qoder_borrowed_skill_restore_releases_only_the_reference_after_user_edits",
+ ) {
+ return;
+ }
+ let fixture = QoderFixture::new();
+ let spec: api::AgentSettingsSpecV2 =
+ serde_json::from_value(fixture.configure("explicit")).unwrap();
+ let facts = fixture
+ .runtime
+ .adapter
+ .capture_settings_facts(&spec)
+ .unwrap();
+ private_file(&fixture.skill, facts.skill_file.template.content.as_bytes());
+ apply(
+ &fixture.service,
+ &fixture.runtime,
+ fixture.configure("explicit"),
+ "qoder-borrow",
+ );
+ let restore = fixture.restore();
+ let record = fixture
+ .runtime
+ .adapter
+ .stores_lock()
+ .unwrap()
+ .control()
+ .skill_installation(
+ &WorkspaceId::default(),
+ SettingsAgentClass::Qoder.skill_root_ref(),
+ )
+ .unwrap()
+ .unwrap();
+ assert_eq!(
+ record.file_ownership,
+ CollaborationSkillFileOwnership::BorrowedIdentical
+ );
+ let edited = b"user keeps their independent skill\n";
+ private_file(&fixture.skill, edited);
+ apply(
+ &fixture.service,
+ &fixture.runtime,
+ restore,
+ "qoder-release-borrowed",
+ );
+ assert_eq!(fixture.status()["collaboration"]["state"], "restored");
+ assert_eq!(fs::read(&fixture.skill).unwrap(), edited);
+ let record = fixture
+ .runtime
+ .adapter
+ .stores_lock()
+ .unwrap()
+ .control()
+ .skill_installation(
+ &WorkspaceId::default(),
+ SettingsAgentClass::Qoder.skill_root_ref(),
+ )
+ .unwrap()
+ .unwrap();
+ assert!(!record.contexts.contains(&fixture.context));
+ fixture.assert_no_model_effects();
+}
+
+#[path = "settings_entry_qoder_model_tests.rs"]
+mod models;
diff --git a/crates/daemon/src/control/runtime/settings_entry_tests.rs b/crates/daemon/src/control/runtime/settings_entry_tests.rs
index 86e4b7da..7f671cc0 100644
--- a/crates/daemon/src/control/runtime/settings_entry_tests.rs
+++ b/crates/daemon/src/control/runtime/settings_entry_tests.rs
@@ -940,10 +940,17 @@ impl FixtureFacts {
}
impl AgentConnectionControlPort for FixtureFacts {
+ fn retry_settings_operation(
+ &self,
+ request: &api::AgentSettingsRetryV1,
+ ) -> Result<OperationV1, ControlReadError> {
+ self.adapter.retry_settings_operation(request)
+ }
+
fn settings_status(
&self,
request: &api::AgentSettingsStatusRequestV2,
- ) -> Result<api::AgentModelSettingsStatusV2, ControlReadError> {
+ ) -> Result<api::AgentSettingsStatusV2, ControlReadError> {
self.adapter.settings_status(request)
}
@@ -964,8 +971,10 @@ impl AgentConnectionControlPort for FixtureFacts {
let mut capabilities = vec![
AgentCapability::EffectiveConfiguration,
AgentCapability::AtomicManagedReplace,
- AgentCapability::IngressAuthentication,
];
+ if input.facts.model.is_some() {
+ capabilities.push(AgentCapability::IngressAuthentication);
+ }
if self.fixture_worker_metadata {
capabilities.extend([
AgentCapability::SkillLoading,
@@ -1011,3 +1020,9 @@ mod facets;
#[path = "settings_profile_tests.rs"]
mod settings_profile_tests;
+
+#[path = "settings_entry_qoder_tests.rs"]
+mod qoder;
+
+#[path = "settings_profile_fault.rs"]
+mod fault;
diff --git a/crates/daemon/src/control/runtime/settings_facts.rs b/crates/daemon/src/control/runtime/settings_facts.rs
index b05dad9a..c5af3490 100644
--- a/crates/daemon/src/control/runtime/settings_facts.rs
+++ b/crates/daemon/src/control/runtime/settings_facts.rs
@@ -3,10 +3,11 @@ use super::*;
use hiroute_application::agent_connection::{
AgentSettingsFacts, AgentSettingsPlanningInput, CodexModelFileAction,
CollaborationSkillTemplate, SettingsClaudeModelFacts, SettingsModelCatalogFacts,
- SettingsModelFileFacts, SettingsModelTargetFacts, SettingsSkillFileFacts, SkillFileAction,
- codex_model_restore_point_ref, decode_settings_login_item, is_settings_login_item,
- plan_skill_install, plan_skill_remove, settings_claude_model_file_for_operation,
- settings_codex_catalog_target, settings_codex_model_file_for_operation,
+ SettingsModelFacts, SettingsModelFileFacts, SettingsModelTargetFacts, SettingsSkillFileFacts,
+ SkillFileAction, codex_model_restore_point_ref, decode_settings_login_item,
+ is_settings_login_item, plan_skill_install, plan_skill_remove,
+ settings_claude_model_file_for_operation, settings_codex_catalog_target,
+ settings_codex_model_file_for_operation,
};
use hiroute_application::control::RoutingFactsPort;
use hiroute_application_api::{
@@ -31,6 +32,8 @@ use std::collections::{BTreeMap, BTreeSet};
mod codex_association;
#[path = "settings_facts/codex_models.rs"]
mod codex_models;
+mod qoder;
+mod qoder_model;
use codex_association::{
connector_account_matches, endpoint_matches_target, mark_catalog_structure_proven,
};
@@ -51,17 +54,19 @@ pub(super) enum SettingsAgentClass {
Codex,
CodexProfile,
Claude,
+ Qoder,
}
impl SettingsAgentClass {
pub(super) fn is_codex(self) -> bool {
- self != Self::Claude
+ matches!(self, Self::Codex | Self::CodexProfile)
}
pub(super) fn agent_id(self) -> &'static str {
match self {
Self::Codex | Self::CodexProfile => "agent_codex_default",
Self::Claude => "agent_claude_default",
+ Self::Qoder => "agent_qoder_default",
}
}
@@ -69,6 +74,7 @@ impl SettingsAgentClass {
match self {
Self::Codex | Self::CodexProfile => "codex",
Self::Claude => "claude",
+ Self::Qoder => "qoder",
}
}
@@ -77,6 +83,7 @@ impl SettingsAgentClass {
Self::Codex => scanner.codex_user_config_target(),
Self::CodexProfile => scanner.codex_profile_config_target(),
Self::Claude => scanner.claude_user_settings_target(),
+ Self::Qoder => scanner.qoder_user_config_target(),
}
}
@@ -84,6 +91,7 @@ impl SettingsAgentClass {
match self {
Self::Codex | Self::CodexProfile => "skill-root/agent_codex_default",
Self::Claude => "skill-root/agent_claude_default",
+ Self::Qoder => "skill-root/agent_qoder_default",
}
}
@@ -97,6 +105,10 @@ impl SettingsAgentClass {
hiroute_integrations::CLAUDE_PROFILE_ID_V1,
hiroute_integrations::CLAUDE_INTEGRATION_PROFILE_REF_V1,
),
+ Self::Qoder => (
+ hiroute_integrations::QODER_PROFILE_ID_V1,
+ hiroute_integrations::QODER_INTEGRATION_PROFILE_REF_V1,
+ ),
};
let subject = AgentConnectionTransactionSubjectV1::from_registered_profile(
self.agent_id(),
@@ -112,6 +124,7 @@ impl LocalControlAdapter {
let class = match agent_id {
"agent_codex_default" => SettingsAgentClass::Codex,
"agent_claude_default" => SettingsAgentClass::Claude,
+ "agent_qoder_default" => SettingsAgentClass::Qoder,
_ => return None,
};
Some(self.settings_context(class))
@@ -122,6 +135,7 @@ impl LocalControlAdapter {
SettingsAgentClass::Codex,
SettingsAgentClass::CodexProfile,
SettingsAgentClass::Claude,
+ SettingsAgentClass::Qoder,
]
.into_iter()
.find(|class| context == self.settings_context(*class))
@@ -158,6 +172,9 @@ impl LocalControlAdapter {
spec: &AgentSettingsSpecV2,
class: SettingsAgentClass,
) -> Result<AgentSettingsPlanningInput, ControlReadError> {
+ if class == SettingsAgentClass::Qoder {
+ return self.attach_qoder_model_facts(spec, self.qoder_settings_snapshot(spec)?);
+ }
let owned_claude = if class == SettingsAgentClass::Claude {
if let Some(join) = self.configured_model_settings_join(&spec.context_id)? {
let stores = self.stores_lock().map_err(super::map_port)?;
@@ -361,6 +378,7 @@ impl LocalControlAdapter {
SettingsAgentClass::Claude
}
SettingsAgentClass::Claude => SettingsAgentClass::Codex,
+ SettingsAgentClass::Qoder => return Err(ControlReadError::Denied),
};
let other_grant = stores
.secrets()
@@ -426,6 +444,7 @@ impl LocalControlAdapter {
selected_collaboration_restore = Some(original.operation_id.clone());
}
let model = match class {
+ SettingsAgentClass::Qoder => return Err(ControlReadError::Denied),
SettingsAgentClass::Codex | SettingsAgentClass::CodexProfile => original
.plan
.external()
@@ -511,24 +530,7 @@ impl LocalControlAdapter {
} else {
(None, None)
};
- let trigger_mode = match &spec.collaboration {
- AgentFacetIntent::Configure { settings } => settings.trigger_mode,
- AgentFacetIntent::Keep | AgentFacetIntent::Restore { .. } => {
- AgentCollaborationTriggerModeV2::Explicit
- }
- };
- let (template_revision, template_content) = match trigger_mode {
- AgentCollaborationTriggerModeV2::Explicit => (
- COLLABORATION_SKILL_EXPLICIT_REVISION,
- COLLABORATION_SKILL_EXPLICIT_CONTENT,
- ),
- AgentCollaborationTriggerModeV2::DelegateByDefault => (
- COLLABORATION_SKILL_DEFAULT_REVISION,
- COLLABORATION_SKILL_DEFAULT_CONTENT,
- ),
- };
- let template = CollaborationSkillTemplate::bundled(template_revision, template_content)
- .map_err(|_| ControlReadError::Corrupt)?;
+ let template = collaboration_template(spec)?;
let collaboration_file_conflict = match &spec.collaboration {
AgentFacetIntent::Configure { .. } => plan_skill_install(
class.skill_root_ref(),
@@ -578,6 +580,7 @@ impl LocalControlAdapter {
None
};
let native_default_model = match class {
+ SettingsAgentClass::Qoder => return Err(ControlReadError::Denied),
SettingsAgentClass::Codex | SettingsAgentClass::CodexProfile => codex_catalog_summary
.as_ref()
.map(|catalog| catalog.native_default_model.clone()),
@@ -865,6 +868,7 @@ impl LocalControlAdapter {
))
.map_err(|_| ControlReadError::Corrupt)?;
let model_target = match class {
+ SettingsAgentClass::Qoder => return Err(ControlReadError::Denied),
SettingsAgentClass::Codex | SettingsAgentClass::CodexProfile => {
SettingsModelTargetFacts::Codex {
provider_id: "hiroute".into(),
@@ -888,7 +892,7 @@ impl LocalControlAdapter {
collaboration_state,
expected_revisions,
subject,
- model_file: SettingsModelFileFacts {
+ model_file: Some(SettingsModelFileFacts {
expected_content,
before_fingerprint,
publication_digest: publication.map(|record| record.digest),
@@ -897,7 +901,7 @@ impl LocalControlAdapter {
active_configuration,
restore: selected_restore,
target: model_target,
- },
+ }),
skill_file: SettingsSkillFileFacts {
root_ref: class.skill_root_ref().into(),
target: skill_target,
@@ -907,32 +911,40 @@ impl LocalControlAdapter {
template,
},
facts: AgentSettingsFacts {
- codex_context_override,
- claude_context_override,
- claude_plan_capability_unavailable,
context_id: spec.context_id.clone(),
dependency_digest,
capabilities,
- ingress: installation.profile.client_protocol(),
- available_surfaces: self.scanner.available_model_surfaces(class.agent_id()),
- model_publication: active,
- model_catalog,
- login_item_required,
- login_item_removal_required,
- fixed_candidate_facts,
- preserved_codex_models,
- preserved_codex_bindings,
- required_native_model_ids,
- require_native_model_routes: preserve_native_models,
- unproven_native_model_ids,
- native_default_must_be_original,
- native_default_model,
- native_claude_presets,
- restore_native_model_ids,
- restore_inherits_root: class == SettingsAgentClass::CodexProfile,
- restored_native_model,
collaboration_file_conflict,
restore_points,
+ model: Some(SettingsModelFacts {
+ qoder_model_conflict: None,
+ codex_context_override,
+ claude_context_override,
+ claude_plan_capability_unavailable,
+ ingress: installation
+ .profile
+ .model_connection()
+ .map_err(|_| ControlReadError::Corrupt)?
+ .ok_or(ControlReadError::Denied)?
+ .ingress_protocol,
+ available_surfaces: self.scanner.available_model_surfaces(class.agent_id()),
+ model_publication: active,
+ model_catalog,
+ login_item_required,
+ login_item_removal_required,
+ fixed_candidate_facts,
+ preserved_codex_models,
+ preserved_codex_bindings,
+ required_native_model_ids,
+ require_native_model_routes: preserve_native_models,
+ unproven_native_model_ids,
+ native_default_must_be_original,
+ native_default_model,
+ native_claude_presets,
+ restore_native_model_ids,
+ restore_inherits_root: class == SettingsAgentClass::CodexProfile,
+ restored_native_model,
+ }),
},
})
}
@@ -965,3 +977,26 @@ fn login_item_owned_by_this_feature(
}
Ok(false)
}
+
+fn collaboration_template(
+ spec: &AgentSettingsSpecV2,
+) -> Result<CollaborationSkillTemplate, ControlReadError> {
+ let trigger_mode = match &spec.collaboration {
+ AgentFacetIntent::Configure { settings } => settings.trigger_mode,
+ AgentFacetIntent::Keep | AgentFacetIntent::Restore { .. } => {
+ AgentCollaborationTriggerModeV2::Explicit
+ }
+ };
+ let (template_revision, template_content) = match trigger_mode {
+ AgentCollaborationTriggerModeV2::Explicit => (
+ COLLABORATION_SKILL_EXPLICIT_REVISION,
+ COLLABORATION_SKILL_EXPLICIT_CONTENT,
+ ),
+ AgentCollaborationTriggerModeV2::DelegateByDefault => (
+ COLLABORATION_SKILL_DEFAULT_REVISION,
+ COLLABORATION_SKILL_DEFAULT_CONTENT,
+ ),
+ };
+ CollaborationSkillTemplate::bundled(template_revision, template_content)
+ .map_err(|_| ControlReadError::Corrupt)
+}
diff --git a/crates/daemon/src/control/runtime/settings_facts/qoder.rs b/crates/daemon/src/control/runtime/settings_facts/qoder.rs
new file mode 100644
index 00000000..3fcec855
--- /dev/null
+++ b/crates/daemon/src/control/runtime/settings_facts/qoder.rs
@@ -0,0 +1,200 @@
+//! Collaboration facts deliberately exclude native models, login material and model grants.
+use super::*;
+use hiroute_integrations::QoderCollaborationProbeTarget;
+
+impl LocalControlAdapter {
+ pub(super) fn qoder_settings_snapshot(
+ &self,
+ spec: &AgentSettingsSpecV2,
+ ) -> Result<AgentSettingsPlanningInput, ControlReadError> {
+ let class = SettingsAgentClass::Qoder;
+ let discovery = self.scanner.qoder_settings_discovery(matches!(
+ spec.collaboration,
+ AgentFacetIntent::Configure { .. }
+ ));
+ let AgentDiscoveryOutcomeV1::Supported { installation } = discovery.outcome else {
+ return Err(ControlReadError::NotFound);
+ };
+ if installation.agent_id != class.agent_id() {
+ return Err(ControlReadError::Corrupt);
+ }
+ let subject = AgentConnectionTransactionSubjectV1::from_registered_profile(
+ installation.agent_id.clone(),
+ installation.profile.profile_id.clone(),
+ installation.profile.integration_profile_ref.clone(),
+ )
+ .map_err(|_| ControlReadError::Corrupt)?;
+ let target = class
+ .skill_target()
+ .map_err(|_| ControlReadError::Corrupt)?;
+ // Keep does not acquire or validate the other facet's native file.
+ let (before_fingerprint, observed_file) =
+ if matches!(spec.collaboration, AgentFacetIntent::Keep) {
+ (None, None)
+ } else {
+ let before_fingerprint = self
+ .artifacts
+ .current_external_fingerprint(&target)
+ .map_err(super::super::map_port)?;
+ let observed_file = self
+ .artifacts
+ .read_native_target(&target)
+ .map_err(super::super::map_port)?
+ .as_deref()
+ .map(|bytes| CanonicalDigest::of_bytes(bytes.as_slice()));
+ if before_fingerprint
+ != self
+ .artifacts
+ .current_external_fingerprint(&target)
+ .map_err(super::super::map_port)?
+ {
+ return Err(ControlReadError::SnapshotChanged);
+ }
+ (before_fingerprint, observed_file)
+ };
+ let stores = self.stores_lock().map_err(super::super::map_port)?;
+ let workspace = WorkspaceId::default();
+ let expected_revisions = stores
+ .control()
+ .current_revisions(&workspace)
+ .map_err(super::super::map_port)?;
+ let before = stores
+ .control()
+ .skill_installation(&workspace, class.skill_root_ref())
+ .map_err(super::super::map_port)?;
+ let mut restore_points = BTreeMap::new();
+ if before
+ .as_ref()
+ .is_some_and(|record| record.contexts.contains(&spec.context_id))
+ {
+ for operation in stores
+ .control()
+ .succeeded_agent_operations_for_kind(&workspace, "ApplyAgentConnectionChange")
+ .map_err(super::super::map_port)?
+ {
+ if operation.plan.spec().command_id != "agents.settings.apply"
+ || operation.plan.spec().resource_id.as_deref() != Some(&spec.context_id)
+ {
+ continue;
+ }
+ let original: AgentSettingsSpecV2 =
+ serde_json::from_value(operation.plan.spec().desired_state.clone())
+ .map_err(|_| ControlReadError::Corrupt)?;
+ if original.context_id == spec.context_id
+ && matches!(original.collaboration, AgentFacetIntent::Configure { .. })
+ {
+ restore_points.insert(
+ codex_model_restore_point_ref(&operation.operation_id),
+ AgentSettingsFacet::Collaboration,
+ );
+ break;
+ }
+ }
+ }
+ drop(stores);
+ let template = collaboration_template(spec)?;
+ let collaboration_file_conflict = match spec.collaboration {
+ AgentFacetIntent::Configure { .. } => plan_skill_install(
+ class.skill_root_ref(),
+ &spec.context_id,
+ &template,
+ before.as_ref(),
+ observed_file.as_ref(),
+ )
+ .is_err(),
+ AgentFacetIntent::Restore { .. } => before.as_ref().is_some_and(|record| {
+ plan_skill_remove(&spec.context_id, record, observed_file.as_ref())
+ .map_or(true, |plan| plan.file_action == SkillFileAction::Conflict)
+ }),
+ AgentFacetIntent::Keep => false,
+ };
+ let collaboration_state = self.settings_collaboration_state(spec)?;
+ let releases_borrowed_reference =
+ matches!(spec.collaboration, AgentFacetIntent::Restore { .. })
+ && before.as_ref().is_some_and(|record| {
+ record.file_ownership
+ == hiroute_domain::CollaborationSkillFileOwnership::BorrowedIdentical
+ && record.contexts.contains(&spec.context_id)
+ });
+ let semantic_evidence: Vec<_> = installation
+ .capability_evidence
+ .iter()
+ .map(|item| {
+ (
+ item.capability,
+ item.state,
+ &item.adapter_contract,
+ &item.dependency_digest,
+ item.reason,
+ )
+ })
+ .collect();
+ let dependency_digest = CanonicalDigest::of(&serde_json::json!({
+ "schema":"qoder-collaboration-facts/v1",
+ "context":spec.context_id,
+ "observation":installation.observation_digest,
+ "capabilities":semantic_evidence,
+ "skill_content":if releases_borrowed_reference { None } else { observed_file.as_ref() },
+ "skill_fingerprint":if releases_borrowed_reference { None } else { before_fingerprint.as_ref() },
+ "skill_record":before,"skill_template":template.digest,
+ "revisions":expected_revisions,"restores":restore_points,
+ "worker_channel":"local_trust_v1","collaboration_state":collaboration_state,
+ "collaboration_file_conflict":collaboration_file_conflict,
+ })).map_err(|_| ControlReadError::Corrupt)?;
+ let capabilities =
+ AgentCapabilitySet::new(installation.capability_evidence.iter().cloned().map(
+ |mut item| {
+ if item.dependency_digest == installation.observation_digest {
+ item.dependency_digest = dependency_digest.clone();
+ }
+ item
+ },
+ ))
+ .map_err(|_| ControlReadError::Corrupt)?;
+ Ok(AgentSettingsPlanningInput {
+ collaboration_state,
+ expected_revisions,
+ subject,
+ model_file: None,
+ skill_file: SettingsSkillFileFacts {
+ root_ref: class.skill_root_ref().into(),
+ target,
+ before,
+ observed_file,
+ before_fingerprint,
+ template,
+ },
+ facts: AgentSettingsFacts {
+ context_id: spec.context_id.clone(),
+ dependency_digest,
+ capabilities,
+ collaboration_file_conflict,
+ restore_points,
+ model: None,
+ },
+ })
+ }
+
+ /// Persisted ownership selects the verification phase. A changed or missing owned file
+ /// must fail installed verification, never silently fall back to a temporary probe.
+ pub(in crate::control::runtime) fn qoder_collaboration_probe_target(
+ &self,
+ ) -> Result<QoderCollaborationProbeTarget, ControlReadError> {
+ let class = SettingsAgentClass::Qoder;
+ let context = self.settings_context(class);
+ let record = self
+ .stores_lock()
+ .map_err(super::super::map_port)?
+ .control()
+ .skill_installation(&WorkspaceId::default(), class.skill_root_ref())
+ .map_err(super::super::map_port)?;
+ Ok(match record {
+ Some(record) if record.contexts.contains(&context) => {
+ QoderCollaborationProbeTarget::InstalledUserSkill {
+ expected_content: record.content_digest,
+ }
+ }
+ _ => QoderCollaborationProbeTarget::PreinstallCapability,
+ })
+ }
+}
diff --git a/crates/daemon/src/control/runtime/settings_facts/qoder_model.rs b/crates/daemon/src/control/runtime/settings_facts/qoder_model.rs
new file mode 100644
index 00000000..f7972e37
--- /dev/null
+++ b/crates/daemon/src/control/runtime/settings_facts/qoder_model.rs
@@ -0,0 +1,312 @@
+//! Optional Qoder model facts. Pure collaboration never enters this file reader.
+use super::*;
+use hiroute_application::agent_connection::{
+ QoderModelFileAction, qoder_model_provider_id, settings_qoder_model_file_for_operation,
+};
+use hiroute_domain::{
+ AgentCapability, AgentIngressProtocolV1, AgentModelSelectionV2, AgentModelSurfaceV2,
+ CapabilityEvidence, CapabilityState,
+};
+
+impl LocalControlAdapter {
+ pub(super) fn attach_qoder_model_facts(
+ &self,
+ spec: &AgentSettingsSpecV2,
+ mut input: AgentSettingsPlanningInput,
+ ) -> Result<AgentSettingsPlanningInput, ControlReadError> {
+ // A model-capable installation does not make unrelated native settings a dependency
+ // of the Skill. The ordinary planner still rejects token changes without Configure.
+ if matches!(spec.model, AgentFacetIntent::Keep) {
+ return Ok(input);
+ }
+ if spec.restore_native_model.is_some() {
+ return Ok(input);
+ }
+ if let AgentFacetIntent::Configure { settings } = &spec.model
+ && !matches!(settings, AgentModelSelectionV2::QoderAdditional { .. })
+ {
+ return Ok(input);
+ }
+ self.guard_qoder_pending_model_change(None)
+ .map_err(super::super::map_port)?;
+ let target = AgentConnectionEffectRoleV1::ManagedConfiguration
+ .settings_target_for(&input.subject)
+ .map_err(|_| ControlReadError::Corrupt)?;
+ let before_fingerprint = self
+ .artifacts
+ .current_external_fingerprint(&target)
+ .map_err(super::super::map_port)?;
+ let bytes = self
+ .artifacts
+ .read_native_target(&target)
+ .map_err(super::super::map_port)?;
+ let expected_content =
+ CanonicalDigest::of_bytes(bytes.as_deref().map_or(&[][..], Vec::as_slice));
+ drop(bytes);
+ if before_fingerprint
+ != self
+ .artifacts
+ .current_external_fingerprint(&target)
+ .map_err(super::super::map_port)?
+ {
+ return Err(ControlReadError::SnapshotChanged);
+ }
+ let stores = self.stores_lock().map_err(super::super::map_port)?;
+ let workspace = WorkspaceId::default();
+ let publication = stores
+ .control()
+ .active_publication(&workspace)
+ .map_err(super::super::map_port)?
+ .ok_or(ControlReadError::NotFound)?;
+ let active = publication
+ .verify()
+ .map_err(|_| ControlReadError::Corrupt)?;
+ let current_grant = stores
+ .secrets()
+ .inspect_agent_access_grant(
+ workspace.as_str(),
+ &format!("agent-connection/{}", spec.context_id),
+ )
+ .map_err(super::super::map_port)?;
+ let token_input_fingerprint = match &spec.access_token {
+ AgentAccessTokenIntentV1::Keep => None,
+ AgentAccessTokenIntentV1::Regenerate if current_grant.is_some() => None,
+ AgentAccessTokenIntentV1::Set { input_slot } if current_grant.is_some() => {
+ let inputs = self
+ .agent_token_inputs
+ .lock()
+ .map_err(|_| ControlReadError::Unavailable)?;
+ let secret = inputs.get(input_slot).ok_or(ControlReadError::NotFound)?;
+ if !hiroute_domain::valid_user_agent_token(secret.expose()) {
+ return Err(ControlReadError::Denied);
+ }
+ Some(
+ stores
+ .secrets()
+ .fingerprint(secret)
+ .map_err(super::super::map_port)?,
+ )
+ }
+ _ => return Err(ControlReadError::Denied),
+ };
+ let previous = if let Some(reference) = &current_grant {
+ let mut found = None;
+ for operation in stores
+ .control()
+ .succeeded_agent_operations_for_kind(&workspace, "ApplyAgentConnectionChange")
+ .map_err(super::super::map_port)?
+ {
+ if operation.plan.spec().resource_id.as_deref() != Some(&spec.context_id) {
+ continue;
+ }
+ let Some(intent) = operation
+ .plan
+ .external()
+ .iter()
+ .find(|intent| {
+ super::super::native_qoder_model::is_settings_qoder_model(intent)
+ })
+ .cloned()
+ else {
+ continue;
+ };
+ let payload = settings_qoder_model_file_for_operation(&operation, &intent)
+ .map_err(super::super::map_port)?;
+ if !matches!(payload.change, QoderModelFileAction::Configure { .. }) {
+ return Err(ControlReadError::Corrupt);
+ }
+ let [mutation] = operation.plan.agent_access_grants() else {
+ return Err(ControlReadError::Corrupt);
+ };
+ let effect = operation
+ .step(hiroute_domain::OperationStepKind::ApplySecrets)
+ .effects
+ .iter()
+ .find(|effect| is_agent_access_grant_effect(effect))
+ .ok_or(ControlReadError::Corrupt)?;
+ let original = AgentAccessGrantRefV1::from_ensure_effect(effect, mutation)
+ .map_err(|_| ControlReadError::Corrupt)?;
+ if &original == reference {
+ found = Some((operation, intent));
+ break;
+ }
+ }
+ Some(found.ok_or(ControlReadError::Corrupt)?)
+ } else {
+ None
+ };
+ let generation = stores
+ .secrets()
+ .agent_access_grant_generation(
+ WorkspaceId::DEFAULT,
+ &format!("agent-connection/{}", spec.context_id),
+ )
+ .map_err(super::super::map_port)?;
+ drop(stores);
+ let provider_id = qoder_model_provider_id(&spec.context_id);
+ let endpoint = self
+ .managed_agent_runtime
+ .lock()
+ .map_err(|_| ControlReadError::Unavailable)?
+ .as_ref()
+ .map(|runtime| runtime.gateway_base_url.clone())
+ .ok_or(ControlReadError::Unavailable)?;
+ let endpoint = super::super::native_qoder_model::qoder_model_endpoint(&endpoint)
+ .map_err(super::super::map_port)?;
+ let mut restore = None;
+ if let (Some((operation, _)), Some(reference)) = (&previous, &current_grant) {
+ input.facts.restore_points.insert(
+ codex_model_restore_point_ref(&operation.operation_id),
+ AgentSettingsFacet::Model,
+ );
+ restore = Some((operation.operation_id.clone(), reference.clone()));
+ }
+ let qoder_model_conflict;
+ let models = match &spec.model {
+ AgentFacetIntent::Configure { settings } => {
+ let grant = hiroute_domain::AgentModelGrantV2::derive(
+ AgentIngressProtocolV1::Responses,
+ settings,
+ &active,
+ &BTreeMap::new(),
+ )
+ .map_err(|_| ControlReadError::Denied)?;
+ let models =
+ super::super::native_qoder_model::qoder_models_for_grant(&active, &grant)
+ .map_err(super::super::map_port)?;
+ qoder_model_conflict =
+ qoder_model_validation(hiroute_integrations::validate_qoder_configuration(
+ &self.artifacts,
+ &target,
+ &provider_id,
+ &endpoint,
+ &models,
+ previous
+ .as_ref()
+ .map(|(op, intent)| (&op.operation_id, intent)),
+ ))?;
+ models
+ }
+ AgentFacetIntent::Restore { restore_point_ref } => {
+ let (original, intent) = previous
+ .as_ref()
+ .filter(|(op, _)| {
+ codex_model_restore_point_ref(&op.operation_id) == *restore_point_ref
+ })
+ .ok_or(ControlReadError::Denied)?;
+ qoder_model_conflict =
+ qoder_model_validation(hiroute_integrations::validate_qoder_restoration(
+ &self.artifacts,
+ &target,
+ &original.operation_id,
+ intent,
+ ))?;
+ Vec::new()
+ }
+ AgentFacetIntent::Keep => unreachable!(),
+ };
+ let dependency_digest = CanonicalDigest::of(&serde_json::json!({
+ "schema":"qoder-model-facts/v1", "collaboration":input.facts.dependency_digest,
+ "content":expected_content,"fingerprint":before_fingerprint,"publication":publication.digest,
+ "grant":current_grant,"token":token_input_fingerprint,"provider":provider_id,"endpoint":endpoint,
+ "conflict":qoder_model_conflict,"models":models,"previous":previous.as_ref().map(|(op,_)| &op.operation_id),"restore":restore,
+ })).map_err(|_| ControlReadError::Corrupt)?;
+ let old_digest = input.facts.dependency_digest.clone();
+ let mut capabilities = [
+ AgentCapability::EffectiveConfiguration,
+ AgentCapability::AtomicManagedReplace,
+ AgentCapability::IngressAuthentication,
+ AgentCapability::ModelCatalog,
+ AgentCapability::SkillLoading,
+ AgentCapability::TrustedCliExecution,
+ AgentCapability::IsolatedVerification,
+ ]
+ .iter()
+ .filter_map(|kind| input.facts.capabilities.get(*kind).cloned())
+ .map(|mut proof| {
+ if proof.dependency_digest == old_digest {
+ proof.dependency_digest = dependency_digest.clone();
+ }
+ proof
+ })
+ .collect::<Vec<_>>();
+ for capability in [
+ AgentCapability::EffectiveConfiguration,
+ AgentCapability::AtomicManagedReplace,
+ ] {
+ capabilities.retain(|proof| proof.capability != capability);
+ capabilities.push(CapabilityEvidence {
+ capability,
+ state: CapabilityState::Proven,
+ adapter_contract: "hiroute.qoder-additional-model/v1".into(),
+ observed_at_unix_ms: self.now_ms()?.max(1) as u64,
+ dependency_digest: dependency_digest.clone(),
+ reason: None,
+ });
+ }
+ input.facts.capabilities =
+ AgentCapabilitySet::new(capabilities).map_err(|_| ControlReadError::Corrupt)?;
+ input.facts.dependency_digest = dependency_digest;
+ input.facts.model = Some(SettingsModelFacts {
+ qoder_model_conflict,
+ codex_context_override: false,
+ claude_context_override: false,
+ claude_plan_capability_unavailable: false,
+ ingress: AgentIngressProtocolV1::Responses,
+ available_surfaces: [AgentModelSurfaceV2::QoderCli].into(),
+ model_publication: Some(active),
+ model_catalog: None,
+ login_item_required: false,
+ login_item_removal_required: false,
+ fixed_candidate_facts: Vec::new(),
+ preserved_codex_models: Vec::new(),
+ preserved_codex_bindings: BTreeMap::new(),
+ required_native_model_ids: None,
+ unproven_native_model_ids: Vec::new(),
+ require_native_model_routes: false,
+ native_default_must_be_original: false,
+ native_default_model: None,
+ restore_native_model_ids: None,
+ restore_inherits_root: false,
+ restored_native_model: None,
+ native_claude_presets: None,
+ });
+ input.model_file = Some(SettingsModelFileFacts {
+ expected_content,
+ before_fingerprint,
+ publication_digest: Some(publication.digest),
+ expected_grant_generation: generation,
+ token_input_fingerprint,
+ active_configuration: previous.as_ref().map(|(op, _)| op.operation_id.clone()),
+ restore,
+ target: SettingsModelTargetFacts::Qoder {
+ provider_id,
+ endpoint,
+ models,
+ },
+ });
+ Ok(input)
+ }
+}
+
+fn qoder_model_validation(
+ result: hiroute_domain::PortResult<()>,
+) -> Result<Option<hiroute_application::agent_connection::SettingsBlockReason>, ControlReadError> {
+ use hiroute_application::agent_connection::SettingsBlockReason;
+ match result {
+ Ok(()) => Ok(None),
+ Err(error)
+ if error.code == hiroute_domain::PortErrorCode::Conflict
+ && error.context == "qoder.default.in-use" =>
+ {
+ Ok(Some(SettingsBlockReason::QoderDefaultInUse))
+ }
+ Err(error)
+ if error.code == hiroute_domain::PortErrorCode::Conflict
+ && error.context == "qoder.native.fields" =>
+ {
+ Ok(Some(SettingsBlockReason::QoderModelFileConflict))
+ }
+ Err(error) => Err(super::super::map_port(error)),
+ }
+}
diff --git a/crates/daemon/src/control/runtime/settings_profile_fault.rs b/crates/daemon/src/control/runtime/settings_profile_fault.rs
index 125b4c51..4a4e5b64 100644
--- a/crates/daemon/src/control/runtime/settings_profile_fault.rs
+++ b/crates/daemon/src/control/runtime/settings_profile_fault.rs
@@ -115,7 +115,8 @@ impl ExternalEffectPort for FileRace {
if !self.fail_after_file
&& op.plan.external().iter().any(|i| {
i.target() == e.target
- && crate::control::runtime::native_model::is_settings_codex_model(i)
+ && (crate::control::runtime::native_model::is_settings_codex_model(i)
+ || crate::control::runtime::native_qoder_model::is_settings_qoder_model(i))
})
{
let original = fs::read_to_string(&self.path).unwrap();
diff --git a/crates/daemon/src/control/runtime/settings_profile_tests.rs b/crates/daemon/src/control/runtime/settings_profile_tests.rs
index 04b027af..e2bdd4c1 100644
--- a/crates/daemon/src/control/runtime/settings_profile_tests.rs
+++ b/crates/daemon/src/control/runtime/settings_profile_tests.rs
@@ -234,9 +234,6 @@ fn profile_lifecycle_inheritance_slot_and_safe_restore() {
apply(&service, &runtime, root_spec, "switch-after-revoke");
}
-#[path = "settings_profile_fault.rs"]
-mod fault;
-
#[path = "settings_profile_legacy_tests.rs"]
mod legacy;
diff --git a/crates/daemon/src/control/runtime/settings_retry.rs b/crates/daemon/src/control/runtime/settings_retry.rs
new file mode 100644
index 00000000..d21da490
--- /dev/null
+++ b/crates/daemon/src/control/runtime/settings_retry.rs
@@ -0,0 +1,60 @@
+//! Resume only the original context-bound native settings Operation and its sealed effects.
+use super::settings_facts::SettingsAgentClass;
+use super::*;
+use hiroute_domain::{AgentFacetIntent, AgentSettingsSpecV2, ControlRepositoryPort};
+
+impl LocalControlAdapter {
+ pub(super) fn retry_model_settings_operation(
+ &self,
+ request: &hiroute_application_api::AgentSettingsRetryV1,
+ ) -> Result<hiroute_domain::OperationV1, ControlReadError> {
+ if request.schema != "hiroute.agent-settings-retry/v1"
+ || self
+ .settings_agent_for_context(&request.context_id)
+ .is_none_or(|class| !class.is_codex() && class != SettingsAgentClass::Qoder)
+ {
+ return Err(ControlReadError::Denied);
+ }
+ let stores = self.stores_lock().map_err(super::map_port)?;
+ let op = stores
+ .control()
+ .load_operation(&request.operation_id)
+ .map_err(super::map_port)?
+ .ok_or(ControlReadError::NotFound)?;
+ if op.workspace_id != WorkspaceId::default()
+ || op.plan.spec().command_id != "agents.settings.apply"
+ || op.plan.spec().resource_id.as_deref() != Some(&request.context_id)
+ {
+ return Err(ControlReadError::Denied);
+ }
+ let spec: AgentSettingsSpecV2 =
+ serde_json::from_value(op.plan.spec().desired_state.clone())
+ .map_err(|_| ControlReadError::Corrupt)?;
+ if matches!(spec.model, AgentFacetIntent::Keep) {
+ return Err(ControlReadError::Denied);
+ }
+ if self.settings_agent_for_context(&request.context_id) == Some(SettingsAgentClass::Qoder) {
+ let intent = op
+ .plan
+ .external()
+ .iter()
+ .find(|intent| super::native_qoder_model::is_settings_qoder_model(intent))
+ .ok_or(ControlReadError::Denied)?;
+ hiroute_application::agent_connection::settings_qoder_model_file_for_operation(
+ &op, intent,
+ )
+ .map_err(super::map_port)?;
+ }
+ drop(stores);
+ hiroute_application::TransactionCoordinator::new(
+ self,
+ self,
+ self,
+ self,
+ self,
+ &self.admission,
+ )
+ .run(&request.operation_id)
+ .map_err(|_| ControlReadError::Unavailable)
+ }
+}
diff --git a/crates/daemon/src/control/runtime/settings_status.rs b/crates/daemon/src/control/runtime/settings_status.rs
index 9149463c..c99004f2 100644
--- a/crates/daemon/src/control/runtime/settings_status.rs
+++ b/crates/daemon/src/control/runtime/settings_status.rs
@@ -29,6 +29,15 @@ pub(super) struct ConfiguredModelSettings {
}
impl LocalControlAdapter {
+ pub(super) fn agent_settings_status(
+ &self,
+ request: &AgentSettingsStatusRequestV2,
+ ) -> Result<hiroute_application_api::AgentSettingsStatusV2, ControlReadError> {
+ self.model_settings_status(request)
+ .map(Box::new)
+ .map(hiroute_application_api::AgentSettingsStatusV2::Model)
+ }
+
pub(super) fn validate_model_check_target(
&self,
request: &hiroute_application_api::AgentCheckRequestV1,
@@ -192,7 +201,14 @@ impl LocalControlAdapter {
status.operation_state = Some(operation.state.as_str().into());
let (active_grant, configured_join) = match action {
ModelAction::Configure => {
- let file_applied = if class == SettingsAgentClass::Claude {
+ let file_applied = if class == SettingsAgentClass::Qoder {
+ hiroute_integrations::qoder_native_configuration_is_applied(
+ &self.artifacts,
+ &operation.operation_id,
+ intent,
+ )
+ .map_err(super::map_port)?
+ } else if class == SettingsAgentClass::Claude {
let policy =
hiroute_application::agent_connection::decode_settings_claude_model_file(
intent,
@@ -299,6 +315,10 @@ impl LocalControlAdapter {
},
SettingsAgentClass::Claude,
) => surfaces.clone(),
+ (
+ hiroute_domain::AgentModelSelectionV2::QoderAdditional { .. },
+ SettingsAgentClass::Qoder,
+ ) => [hiroute_domain::AgentModelSurfaceV2::QoderCli].into(),
_ => return Err(ControlReadError::Corrupt),
};
// The applied revision is the installed publication this configuration was
@@ -432,6 +452,9 @@ fn model_intent(
super::settings_facts::SettingsAgentClass::Claude => {
super::native_claude_model::is_settings_claude_model(intent)
}
+ super::settings_facts::SettingsAgentClass::Qoder => {
+ super::native_qoder_model::is_settings_qoder_model(intent)
+ }
})
}
@@ -441,6 +464,20 @@ fn model_action(
intent: &hiroute_domain::ExternalEffectIntentV1,
) -> hiroute_domain::PortResult<ModelAction> {
match class {
+ super::settings_facts::SettingsAgentClass::Qoder => {
+ match hiroute_application::agent_connection::settings_qoder_model_file_for_operation(
+ operation, intent,
+ )?
+ .change
+ {
+ hiroute_application::agent_connection::QoderModelFileAction::Configure {
+ ..
+ } => Ok(ModelAction::Configure),
+ hiroute_application::agent_connection::QoderModelFileAction::Restore { .. } => {
+ Ok(ModelAction::Restore)
+ }
+ }
+ }
super::settings_facts::SettingsAgentClass::Codex
| super::settings_facts::SettingsAgentClass::CodexProfile => {
match settings_codex_model_file_for_operation(operation, intent)?.change {
diff --git a/crates/daemon/src/control/runtime/work_plans.rs b/crates/daemon/src/control/runtime/work_plans.rs
index b9805344..61463432 100644
--- a/crates/daemon/src/control/runtime/work_plans.rs
+++ b/crates/daemon/src/control/runtime/work_plans.rs
@@ -229,53 +229,30 @@ mod tests {
.0,
WorkPlanAvailabilityV1::Unavailable
);
- let configured = hiroute_application_api::WorkerExecutorAvailabilityListV1 {
- schema: hiroute_application_api::WORKER_EXECUTOR_AVAILABILITY_SCHEMA_V1.to_owned(),
- executors: vec![
- hiroute_application_api::WorkerExecutorAvailabilityV1 {
- harness: WorkerHarnessV1::CodexCli,
- state: hiroute_application_api::WorkerExecutorAvailabilityStateV1::Ready,
- reason: None,
- start_approve_all: hiroute_application_api::WorkerExecutorCapabilityAvailabilityV1 {
- state: hiroute_application_api::WorkerExecutorAvailabilityStateV1::Ready,
- reason: None,
- },
- cancel: hiroute_application_api::WorkerExecutorCapabilityAvailabilityV1 {
- state: hiroute_application_api::WorkerExecutorAvailabilityStateV1::Ready,
- reason: None,
- },
- continue_session: hiroute_application_api::WorkerExecutorCapabilityAvailabilityV1 {
- state: hiroute_application_api::WorkerExecutorAvailabilityStateV1::Unknown,
- reason: Some(hiroute_application_api::WorkerExecutorAvailabilityReasonV1::CapabilityUnverified),
- },
- restricted_policy: hiroute_application_api::WorkerExecutorCapabilityAvailabilityV1 {
- state: hiroute_application_api::WorkerExecutorAvailabilityStateV1::Unknown,
- reason: Some(hiroute_application_api::WorkerExecutorAvailabilityReasonV1::RestrictedPolicyUnverified),
- },
- },
- hiroute_application_api::WorkerExecutorAvailabilityV1 {
- harness: WorkerHarnessV1::ClaudeCode,
- state: hiroute_application_api::WorkerExecutorAvailabilityStateV1::Unavailable,
- reason: Some(hiroute_application_api::WorkerExecutorAvailabilityReasonV1::InstallationNotConfigured),
- start_approve_all: hiroute_application_api::WorkerExecutorCapabilityAvailabilityV1 {
- state: hiroute_application_api::WorkerExecutorAvailabilityStateV1::Unavailable,
- reason: Some(hiroute_application_api::WorkerExecutorAvailabilityReasonV1::InstallationNotConfigured),
- },
- cancel: hiroute_application_api::WorkerExecutorCapabilityAvailabilityV1 {
- state: hiroute_application_api::WorkerExecutorAvailabilityStateV1::Unavailable,
- reason: Some(hiroute_application_api::WorkerExecutorAvailabilityReasonV1::InstallationNotConfigured),
- },
- continue_session: hiroute_application_api::WorkerExecutorCapabilityAvailabilityV1 {
- state: hiroute_application_api::WorkerExecutorAvailabilityStateV1::Unavailable,
- reason: Some(hiroute_application_api::WorkerExecutorAvailabilityReasonV1::InstallationNotConfigured),
- },
- restricted_policy: hiroute_application_api::WorkerExecutorCapabilityAvailabilityV1 {
- state: hiroute_application_api::WorkerExecutorAvailabilityStateV1::Unavailable,
- reason: Some(hiroute_application_api::WorkerExecutorAvailabilityReasonV1::InstallationNotConfigured),
- },
- },
- ],
+ let mut configured = WorkerExecutorAvailabilityRegistry::unconfigured().snapshot();
+ let codex = configured
+ .executors
+ .iter_mut()
+ .find(|executor| executor.harness == WorkerHarnessV1::CodexCli)
+ .unwrap();
+ codex.state = hiroute_application_api::WorkerExecutorAvailabilityStateV1::Ready;
+ codex.reason = None;
+ codex.start_approve_all = hiroute_application_api::WorkerExecutorCapabilityAvailabilityV1 {
+ state: hiroute_application_api::WorkerExecutorAvailabilityStateV1::Ready,
+ reason: None,
+ };
+ codex.cancel = codex.start_approve_all.clone();
+ codex.continue_session = hiroute_application_api::WorkerExecutorCapabilityAvailabilityV1 {
+ state: hiroute_application_api::WorkerExecutorAvailabilityStateV1::Unknown,
+ reason: Some(
+ hiroute_application_api::WorkerExecutorAvailabilityReasonV1::CapabilityUnverified,
+ ),
+ };
+ codex.restricted_policy = hiroute_application_api::WorkerExecutorCapabilityAvailabilityV1 {
+ state: hiroute_application_api::WorkerExecutorAvailabilityStateV1::Unknown,
+ reason: Some(hiroute_application_api::WorkerExecutorAvailabilityReasonV1::RestrictedPolicyUnverified),
};
+ assert!(configured.valid());
assert_eq!(
worker_availability(Some(&configured), WorkerHarnessV1::CodexCli),
(WorkPlanAvailabilityV1::Ready, None)
diff --git a/crates/daemon/src/control/runtime_worker_dependencies_tests.rs b/crates/daemon/src/control/runtime_worker_dependencies_tests.rs
index b4f178b8..bee182e7 100644
--- a/crates/daemon/src/control/runtime_worker_dependencies_tests.rs
+++ b/crates/daemon/src/control/runtime_worker_dependencies_tests.rs
@@ -37,7 +37,7 @@ fn select_request(root: &std::path::Path, suffix: &str) -> WorkerDependenciesSel
executable(&node);
WorkerDependenciesSelectRequestV1 {
harness: WorkerHarnessV1::CodexCli,
- adapter_path: adapter.to_string_lossy().into_owned(),
+ adapter_path: Some(adapter.to_string_lossy().into_owned()),
cli_path: cli.to_string_lossy().into_owned(),
node_path: Some(node.to_string_lossy().into_owned()),
expected_selection_revision: 0,
@@ -92,7 +92,7 @@ fn local_worker_dependency_selection_is_cas_durable_and_replays_before_metadata(
assert_eq!(selected.revision, 1);
assert_eq!(
selected.config.adapter,
- std::path::PathBuf::from(&request.adapter_path)
+ request.adapter_path.as_ref().map(std::path::PathBuf::from)
);
std::fs::remove_dir_all(directory.path().join("first")).unwrap();
@@ -100,8 +100,8 @@ fn local_worker_dependency_selection_is_cas_durable_and_replays_before_metadata(
assert!(replay.error.is_none(), "{replay:?}");
assert_eq!(replay.operation, applied.operation);
assert_eq!(
- replay.data.as_ref().unwrap()["selected"][0]["adapter_path"],
- request.adapter_path
+ replay.data.as_ref().unwrap()["selected"][0]["adapter_path"].as_str(),
+ request.adapter_path.as_deref()
);
assert!(
replay.data.as_ref().unwrap()["candidates"]
diff --git a/crates/daemon/src/delegation/acp/README.md b/crates/daemon/src/delegation/acp/README.md
new file mode 100644
index 00000000..ceea37f6
--- /dev/null
+++ b/crates/daemon/src/delegation/acp/README.md
@@ -0,0 +1,34 @@
+# Worker ACP boundary
+
+This owner starts or loads one exact native session, selects the frozen Plan's
+model and native permission mode, then sends one prompt. It does not resolve user
+configuration, choose a Plan, retry a prompt, or replace a failed Continue with a
+new session. See the [Worker launcher](../local_worker/README.md) for process and
+temporary-material ownership.
+
+The profile applies startup overrides, but those alone do not establish the
+session's model. Native resume and user model settings can change the adapter's
+effective selection. [Model selection](model.rs) therefore checks the `model`
+config selector returned by both `session/new` and `session/load`. If necessary,
+it sets the exact frozen alias and requires the reply to confirm it before the
+journal records prompt intent. Missing, ambiguous, rejected or unconfirmed model
+selection is `CapabilityUnavailable`. Cancellation and deadline remain their own
+errors. No approximate alias resolution or legacy RPC fallback is permitted.
+
+The supported wire behavior was inspected in `codex-acp` 1.1.5 and
+`claude-agent-acp` 0.60.0. Both expose `configOptions` with `id: "model"` and
+support `session/set_config_option`. Codex reports its base model separately from
+the reasoning-effort selector. Claude can catch a failed resume model override
+and return the prior live model; the check here prevents prompting that session
+under a different Plan. These observations justify the capability check, not a
+version allowlist. This owner does not infer effort semantics from model IDs.
+
+The Rust ACP dependency provides typed config options and a typed setter; its
+current v1 schema does not retain legacy `models` response fields. A legacy
+`currentModelId` claim cannot substitute for confirming the current selector.
+
+[Model regressions](model_tests.rs) exercise new and continued tasks, an already
+correct selection, a corrected selection, and each failure before prompt intent.
+They prove protocol behavior, not that a real installed Agent loaded user skills
+or sent the selected model to Gateway. The real Worker product journey must prove
+those effects through its actual adapter and native client.
diff --git a/crates/daemon/src/delegation/acp/identity.rs b/crates/daemon/src/delegation/acp/identity.rs
index a69077c4..fe8077a4 100644
--- a/crates/daemon/src/delegation/acp/identity.rs
+++ b/crates/daemon/src/delegation/acp/identity.rs
@@ -10,6 +10,7 @@ pub enum AcpNativeIdentityContract {
ExplicitResponseMetadata,
CodexThreadV1,
ClaudeSessionV1,
+ QoderSessionV1,
}
impl AcpNativeIdentityContract {
@@ -21,7 +22,7 @@ impl AcpNativeIdentityContract {
match self {
Self::Unverified => Ok(None),
Self::ExplicitResponseMetadata => Ok(metadata_id(response)),
- Self::CodexThreadV1 | Self::ClaudeSessionV1 => {
+ Self::CodexThreadV1 | Self::ClaudeSessionV1 | Self::QoderSessionV1 => {
if !valid_id(acp_id) {
return Err(DelegationErrorV1::ProtocolFailed);
}
@@ -36,7 +37,7 @@ impl AcpNativeIdentityContract {
Self::ExplicitResponseMetadata => {
metadata_id(response).as_ref() == binding.native_session_id.as_ref()
}
- Self::CodexThreadV1 | Self::ClaudeSessionV1 => {
+ Self::CodexThreadV1 | Self::ClaudeSessionV1 | Self::QoderSessionV1 => {
valid_id(&binding.acp_session_id)
&& binding.native_session_id.as_deref() == Some(binding.acp_session_id.as_str())
}
diff --git a/crates/daemon/src/delegation/acp/identity_tests.rs b/crates/daemon/src/delegation/acp/identity_tests.rs
index 926cc450..b4b28a2f 100644
--- a/crates/daemon/src/delegation/acp/identity_tests.rs
+++ b/crates/daemon/src/delegation/acp/identity_tests.rs
@@ -1,10 +1,11 @@
use super::*;
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
-fn contracts() -> [AcpNativeIdentityContract; 2] {
+fn contracts() -> [AcpNativeIdentityContract; 3] {
[
AcpNativeIdentityContract::CodexThreadV1,
AcpNativeIdentityContract::ClaudeSessionV1,
+ AcpNativeIdentityContract::QoderSessionV1,
]
}
@@ -62,7 +63,7 @@ async fn execute(
}
#[tokio::test]
-async fn both_native_profile_mappings_resume_exact_native_id_without_generic_metadata() {
+async fn declared_native_profile_mappings_resume_exact_native_id_without_generic_metadata() {
for contract in contracts() {
let mut request = tests::input();
request.identity_contract = contract.clone();
diff --git a/crates/daemon/src/delegation/acp/mod.rs b/crates/daemon/src/delegation/acp/mod.rs
index 56b947a8..2e15529a 100644
--- a/crates/daemon/src/delegation/acp/mod.rs
+++ b/crates/daemon/src/delegation/acp/mod.rs
@@ -20,6 +20,7 @@ use tokio_util::sync::CancellationToken;
use super::progress::ProgressSink;
mod identity;
+mod model;
mod transport;
pub use identity::AcpNativeIdentityContract;
pub use transport::MAX_ACP_FRAME_BYTES;
@@ -43,12 +44,19 @@ pub struct AcpRunInput {
/// Exact adapter-owned native mode selected after new/load and before the first prompt.
/// Production profiles always set this; `None` exists for protocol-only test fixtures.
pub native_session_mode: Option<String>,
+ /// Profile's exact native model selector ID, confirmed before prompting. The frozen
+ /// Plan/Gateway alias remains separate when the native client adds a provider prefix.
+ /// Production runs and installation probes set this; protocol-only fixtures may omit it.
+ pub expected_model: Option<String>,
pub authentication: Option<Value>,
pub deadline: Instant,
pub cancellation: CancellationToken,
}
pub trait AcpRunJournal: Send + Sync {
+ /// Transient startup receipt after a successful, version-checked initialize.
+ /// It does not imply session/model readiness or permission to send a prompt.
+ fn initialized(&self) {}
fn session_bound(&self, binding: &AcpSessionBinding) -> Result<(), DelegationErrorV1>;
/// Must durably record the send intent before returning Ok. Failure means no prompt.
fn before_prompt(&self) -> Result<(), DelegationErrorV1>;
@@ -217,6 +225,7 @@ async fn run_session(
if initialized.protocol_version != ProtocolVersion::V1 {
return Err(DelegationErrorV1::CapabilityUnavailable);
}
+ journal.initialized();
if let Some(authentication) = input.authentication {
let request: AuthenticateRequest = serde_json::from_value(authentication)
.map_err(|_| DelegationErrorV1::InvalidArguments)?;
@@ -227,7 +236,7 @@ async fn run_session(
)
.await?;
}
- let (binding, modes) = match input.session {
+ let (binding, modes, config_options) = match input.session {
AcpSessionStart::New => {
let request: NewSessionRequest = serde_json::from_value(json!({
"cwd":input.cwd,"mcpServers":[],"_meta":input.session_meta,
@@ -249,6 +258,7 @@ async fn run_session(
.new_native(&response.session_id.to_string(), &raw)?,
},
response.modes,
+ response.config_options,
)
}
AcpSessionStart::Load(expected) => {
@@ -283,7 +293,7 @@ async fn run_session(
if !identity_verified {
return Err(DelegationErrorV1::ResumeUnavailable);
}
- (expected, response.modes)
+ (expected, response.modes, response.config_options)
}
};
if binding.acp_session_id.is_empty() || binding.acp_session_id.len() > 1024 {
@@ -292,6 +302,17 @@ async fn run_session(
updates.lock().unwrap_or_else(|e| e.into_inner()).session =
Some(binding.acp_session_id.clone());
journal.session_bound(&binding)?;
+ if let Some(expected_model) = input.expected_model.as_deref() {
+ model::ensure_model(
+ &connection,
+ &binding.acp_session_id,
+ config_options.as_deref(),
+ expected_model,
+ &input.cancellation,
+ input.deadline,
+ )
+ .await?;
+ }
if let Some(native_session_mode) = input.native_session_mode {
let mode_available = modes.as_ref().is_some_and(|modes| {
modes
@@ -486,6 +507,8 @@ async fn phase<T>(
#[cfg(test)]
mod identity_tests;
#[cfg(test)]
+mod model_tests;
+#[cfg(test)]
mod security_tests;
#[cfg(test)]
mod tests;
diff --git a/crates/daemon/src/delegation/acp/model.rs b/crates/daemon/src/delegation/acp/model.rs
new file mode 100644
index 00000000..1fe04011
--- /dev/null
+++ b/crates/daemon/src/delegation/acp/model.rs
@@ -0,0 +1,84 @@
+//! The supported Codex and Claude adapters expose the exact base model as the `model`
+//! config selector. Legacy `models.currentModelId` is not the current typed ACP contract
+//! and may append an effort suffix. Never fuzzy-match aliases or trust launch settings
+//! alone: a resumed native session or user model allowlist can override those settings.
+use agent_client_protocol::schema::v1::{
+ SessionConfigKind, SessionConfigOption, SessionConfigSelect, SessionConfigSelectOptions,
+ SetSessionConfigOptionRequest,
+};
+use agent_client_protocol::{Agent, ConnectionTo};
+use hiroute_domain::delegation::DelegationErrorV1;
+use tokio::time::Instant;
+use tokio_util::sync::CancellationToken;
+
+pub(super) async fn ensure_model(
+ connection: &ConnectionTo<Agent>,
+ session_id: &str,
+ config_options: Option<&[SessionConfigOption]>,
+ expected_model: &str,
+ cancellation: &CancellationToken,
+ deadline: Instant,
+) -> Result<(), DelegationErrorV1> {
+ let model = model_selector(config_options)?;
+ if model.current_value.to_string() == expected_model {
+ return Ok(());
+ }
+ let available = match &model.options {
+ SessionConfigSelectOptions::Ungrouped(options) => options
+ .iter()
+ .any(|option| option.value.to_string() == expected_model),
+ SessionConfigSelectOptions::Grouped(groups) => groups.iter().any(|group| {
+ group
+ .options
+ .iter()
+ .any(|option| option.value.to_string() == expected_model)
+ }),
+ _ => false,
+ };
+ if !available {
+ return Err(DelegationErrorV1::CapabilityUnavailable);
+ }
+ let response = super::phase(
+ cancellation,
+ deadline,
+ connection
+ .send_request(SetSessionConfigOptionRequest::new(
+ session_id.to_owned(),
+ "model",
+ expected_model,
+ ))
+ .block_task(),
+ )
+ .await
+ .map_err(|error| match error {
+ DelegationErrorV1::ProtocolFailed => DelegationErrorV1::CapabilityUnavailable,
+ error => error,
+ })?;
+ if model_selector(Some(&response.config_options))?
+ .current_value
+ .to_string()
+ != expected_model
+ {
+ return Err(DelegationErrorV1::CapabilityUnavailable);
+ }
+ Ok(())
+}
+
+fn model_selector(
+ options: Option<&[SessionConfigOption]>,
+) -> Result<&SessionConfigSelect, DelegationErrorV1> {
+ let mut models = options
+ .unwrap_or_default()
+ .iter()
+ .filter(|option| option.id.to_string() == "model");
+ let Some(option) = models.next() else {
+ return Err(DelegationErrorV1::CapabilityUnavailable);
+ };
+ if models.next().is_some() {
+ return Err(DelegationErrorV1::CapabilityUnavailable);
+ }
+ match &option.kind {
+ SessionConfigKind::Select(model) => Ok(model),
+ _ => Err(DelegationErrorV1::CapabilityUnavailable),
+ }
+}
diff --git a/crates/daemon/src/delegation/acp/model_tests.rs b/crates/daemon/src/delegation/acp/model_tests.rs
new file mode 100644
index 00000000..4131ac86
--- /dev/null
+++ b/crates/daemon/src/delegation/acp/model_tests.rs
@@ -0,0 +1,218 @@
+//! A native model override must never turn a delegated task into a different Plan.
+use super::*;
+use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
+
+const PLAN_MODEL: &str = "hiroute/frozen-plan";
+
+#[derive(Default)]
+struct Journal(Mutex<Vec<&'static str>>);
+
+impl AcpRunJournal for Journal {
+ fn session_bound(&self, _: &AcpSessionBinding) -> Result<(), DelegationErrorV1> {
+ self.0.lock().unwrap().push("session");
+ Ok(())
+ }
+
+ fn before_prompt(&self) -> Result<(), DelegationErrorV1> {
+ self.0.lock().unwrap().push("send_intent");
+ Ok(())
+ }
+
+ fn text_update(&self, _: &str) -> Result<(), DelegationErrorV1> {
+ Ok(())
+ }
+
+ fn allow_permission_once(&self, _: &Value) -> bool {
+ false
+ }
+}
+
+fn selector(current: &str, options: Value) -> Value {
+ json!({
+ "id":"model", "name":"Model", "type":"select",
+ "currentValue":current, "options":options,
+ })
+}
+
+fn plan_option() -> Value {
+ json!({"value":PLAN_MODEL,"name":"Frozen Plan"})
+}
+
+async fn run_fixture(
+ load: bool,
+ config_options: Value,
+ selection_reply: Option<Result<Value, Value>>,
+) -> (
+ Result<AcpRunOutcome, DelegationErrorV1>,
+ Vec<String>,
+ Vec<&'static str>,
+) {
+ let (client, server) = tokio::io::duplex(16_384);
+ let server = tokio::spawn(async move {
+ let (reader, mut writer) = tokio::io::split(server);
+ let mut lines = BufReader::new(reader).lines();
+ let mut methods = vec![];
+ while let Some(line) = lines.next_line().await.unwrap() {
+ let request: Value = serde_json::from_str(&line).unwrap();
+ let method = request["method"].as_str().unwrap();
+ methods.push(method.to_owned());
+ let result = match method {
+ "initialize" => Ok(json!({
+ "protocolVersion":1,"agentCapabilities":{"loadSession":true},
+ })),
+ "session/new" | "session/load" => {
+ assert_eq!(method == "session/load", load);
+ if load {
+ assert_eq!(request["params"]["sessionId"], "acp-a");
+ }
+ Ok(json!({
+ "sessionId":"acp-a", "_meta":{"agentSessionId":"native-a"},
+ "configOptions":config_options,
+ // A legacy claim is deliberately insufficient when the current
+ // selector is absent, malformed, or disagrees with this field.
+ "models":{"currentModelId":PLAN_MODEL,"availableModels":[]},
+ }))
+ }
+ "session/set_config_option" => {
+ assert_eq!(request["params"]["sessionId"], "acp-a");
+ assert_eq!(request["params"]["configId"], "model");
+ assert_eq!(request["params"]["value"], PLAN_MODEL);
+ selection_reply.clone().expect("unexpected model mutation")
+ }
+ "session/prompt" => Ok(json!({"stopReason":"end_turn"})),
+ _ => panic!("unexpected ACP request: {method}"),
+ };
+ let response = match result {
+ Ok(result) => json!({"jsonrpc":"2.0","id":request["id"],"result":result}),
+ Err(error) => json!({"jsonrpc":"2.0","id":request["id"],"error":error}),
+ };
+ writer
+ .write_all(format!("{response}\n").as_bytes())
+ .await
+ .unwrap();
+ }
+ methods
+ });
+ let mut input = super::tests::input();
+ input.expected_model = Some(PLAN_MODEL.to_owned());
+ if load {
+ input.session = AcpSessionStart::Load(AcpSessionBinding {
+ acp_session_id: "acp-a".into(),
+ native_session_id: Some("native-a".into()),
+ });
+ }
+ let journal = Arc::new(Journal::default());
+ let (reader, writer) = tokio::io::split(client);
+ let result = run_acp(reader, writer, input, journal.clone()).await;
+ let methods = server.await.unwrap();
+ let events = journal.0.lock().unwrap().clone();
+ (result, methods, events)
+}
+
+#[tokio::test]
+async fn frozen_model_already_selected_needs_no_mutation_for_new_or_continue() {
+ for load in [false, true] {
+ let (result, methods, events) =
+ run_fixture(load, json!([selector(PLAN_MODEL, json!([]))]), None).await;
+ assert!(result.is_ok());
+ assert_eq!(events, ["session", "send_intent"]);
+ assert_eq!(
+ methods,
+ [
+ "initialize",
+ if load { "session/load" } else { "session/new" },
+ "session/prompt",
+ ]
+ );
+ }
+}
+
+#[tokio::test]
+async fn user_or_resumed_model_is_corrected_to_frozen_plan_before_prompt() {
+ for load in [false, true] {
+ // Both current adapters use a flat list; ACP also permits grouped values.
+ for options in [
+ json!([plan_option()]),
+ json!([{"group":"plans","name":"Plans","options":[plan_option()]}]),
+ ] {
+ let (result, methods, events) = run_fixture(
+ load,
+ json!([selector("user-model", options)]),
+ Some(Ok(json!({
+ "configOptions":[selector(PLAN_MODEL, json!([plan_option()]))],
+ }))),
+ )
+ .await;
+ assert!(result.is_ok());
+ assert_eq!(events, ["session", "send_intent"]);
+ assert_eq!(
+ methods,
+ [
+ "initialize",
+ if load { "session/load" } else { "session/new" },
+ "session/set_config_option",
+ "session/prompt",
+ ]
+ );
+ }
+ }
+}
+
+#[tokio::test]
+async fn unavailable_or_ambiguous_frozen_model_never_prompts_or_starts_a_replacement_session() {
+ for load in [false, true] {
+ for options in [
+ Value::Null,
+ json!([]),
+ json!([selector(
+ "user-model",
+ json!([{"value":"default","name":"Default"}])
+ )]),
+ json!([{"id":"model","name":"Model","type":"boolean","currentValue":true}]),
+ json!([
+ selector(PLAN_MODEL, json!([plan_option()])),
+ selector("user-model", json!([plan_option()])),
+ ]),
+ ] {
+ let (result, methods, events) = run_fixture(load, options, None).await;
+ assert_eq!(result.err(), Some(DelegationErrorV1::CapabilityUnavailable));
+ assert_eq!(events, ["session"]);
+ assert_eq!(
+ methods,
+ [
+ "initialize",
+ if load { "session/load" } else { "session/new" }
+ ]
+ );
+ }
+ }
+}
+
+#[tokio::test]
+async fn rejected_or_unconfirmed_model_selection_never_prompts_for_new_or_continue() {
+ for load in [false, true] {
+ for selection_reply in [
+ Err(json!({"code":-32602,"message":"Model pin rejected"})),
+ Ok(json!({})),
+ Ok(json!({"configOptions":[]})),
+ Ok(json!({"configOptions":[selector("user-model", json!([plan_option()]))]})),
+ ] {
+ let (result, methods, events) = run_fixture(
+ load,
+ json!([selector("user-model", json!([plan_option()]))]),
+ Some(selection_reply),
+ )
+ .await;
+ assert_eq!(result.err(), Some(DelegationErrorV1::CapabilityUnavailable));
+ assert_eq!(events, ["session"]);
+ assert_eq!(
+ methods,
+ [
+ "initialize",
+ if load { "session/load" } else { "session/new" },
+ "session/set_config_option",
+ ]
+ );
+ }
+ }
+}
diff --git a/crates/daemon/src/delegation/acp/security_tests.rs b/crates/daemon/src/delegation/acp/security_tests.rs
index 126b78ed..2bb148fb 100644
--- a/crates/daemon/src/delegation/acp/security_tests.rs
+++ b/crates/daemon/src/delegation/acp/security_tests.rs
@@ -34,6 +34,7 @@ fn input() -> AcpRunInput {
identity_contract: AcpNativeIdentityContract::ExplicitResponseMetadata,
session_meta: Map::new(),
native_session_mode: None,
+ expected_model: None,
authentication: None,
deadline: Instant::now() + Duration::from_secs(3),
cancellation: CancellationToken::new(),
diff --git a/crates/daemon/src/delegation/acp/tests.rs b/crates/daemon/src/delegation/acp/tests.rs
index c19734df..2f2dcdcc 100644
--- a/crates/daemon/src/delegation/acp/tests.rs
+++ b/crates/daemon/src/delegation/acp/tests.rs
@@ -29,6 +29,7 @@ pub(super) fn input() -> AcpRunInput {
identity_contract: AcpNativeIdentityContract::ExplicitResponseMetadata,
session_meta: serde_json::Map::new(),
native_session_mode: None,
+ expected_model: None,
authentication: None,
deadline: tokio::time::Instant::now() + std::time::Duration::from_secs(2),
cancellation: tokio_util::sync::CancellationToken::new(),
diff --git a/crates/daemon/src/delegation/authorization_tests/mod.rs b/crates/daemon/src/delegation/authorization_tests/mod.rs
index 761c37f4..470a15dd 100644
--- a/crates/daemon/src/delegation/authorization_tests/mod.rs
+++ b/crates/daemon/src/delegation/authorization_tests/mod.rs
@@ -1,6 +1,6 @@
//! Real SQLite/Operation integration, with a narrow exact-version check fixture.
mod dispatcher_tests;
-mod fixture;
+pub(in crate::delegation) mod fixture;
use fixture::*;
use hiroute_application::delegation::{
admission::{DelegationAdmission, verify_bootstrap},
diff --git a/crates/daemon/src/delegation/executor.rs b/crates/daemon/src/delegation/executor.rs
index 4c3ee520..9eb5704d 100644
--- a/crates/daemon/src/delegation/executor.rs
+++ b/crates/daemon/src/delegation/executor.rs
@@ -445,6 +445,7 @@ impl DelegationRunExecutor {
let identity_contract = profile.identity_contract.clone();
let session_meta = profile.session_meta.clone();
let native_session_mode = Some(profile.native_session_mode().to_owned());
+ let expected_model = Some(profile.native_selected_model_id().to_owned());
let cwd = profile.cwd.clone();
let launch = WorkerLaunchRequest {
launch_nonce: run.launch_nonce.clone(),
@@ -461,6 +462,7 @@ impl DelegationRunExecutor {
identity_contract,
session_meta,
native_session_mode,
+ expected_model,
authentication: None,
deadline,
cancellation,
@@ -637,16 +639,7 @@ fn version_matches_task(
&& CanonicalDigest::of(work)
.map(|digest| digest == task.plan.harness_configuration_digest)
.unwrap_or(false)
- && matches!(
- (task.plan.harness, work.harness),
- (
- hiroute_domain::delegation::WorkerHarnessV1::CodexCli,
- hiroute_domain::delegation::WorkerHarnessV1::CodexCli
- ) | (
- hiroute_domain::delegation::WorkerHarnessV1::ClaudeCode,
- hiroute_domain::delegation::WorkerHarnessV1::ClaudeCode
- )
- )
+ && task.plan.harness == work.harness
}
fn credential_record(
diff --git a/crates/daemon/src/delegation/executor/resume.rs b/crates/daemon/src/delegation/executor/resume.rs
index d9914684..2e4c52f3 100644
--- a/crates/daemon/src/delegation/executor/resume.rs
+++ b/crates/daemon/src/delegation/executor/resume.rs
@@ -57,7 +57,11 @@ impl DelegationRunExecutor {
.as_ref()
.and_then(|session| session.native_session_id.as_deref())
.ok_or(DelegationErrorV1::ResumeUnavailable)?;
- let native_history = native_history(session_root, task.plan.harness, native_session_id)?;
+ // These are owned continuation materials. A borrowed Codex/Qoder binding is an exact-ID
+ // witness, not a rollout path or proof that the native client can still load its history.
+ // Body visibility/retention remains authoritative even while native history survives.
+ let continuation_materials =
+ native_history(session_root, task.plan.harness, native_session_id)?;
let now = now_ms()?;
let retention =
u64::try_from(RETENTION_MS).map_err(|_| DelegationErrorV1::StorageUnavailable)?;
@@ -120,7 +124,7 @@ impl DelegationRunExecutor {
&run.run_id,
until,
&task.body_refs,
- &native_history,
+ &continuation_materials,
);
if stored.is_err() {
let _ = self.versions.release(&run.workspace_id, &owner);
diff --git a/crates/daemon/src/delegation/installation.rs b/crates/daemon/src/delegation/installation.rs
index 38c5d55c..932051be 100644
--- a/crates/daemon/src/delegation/installation.rs
+++ b/crates/daemon/src/delegation/installation.rs
@@ -6,11 +6,13 @@ use hiroute_domain::delegation::{
DelegationErrorV1, DelegationNativeRootReadyV1, DelegationNativeRootStateV1,
DelegationNativeUseStateV1, DelegationRuntimePort, WorkerHarnessV1,
};
-use hiroute_domain::{CanonicalDigest, WorkspaceId};
+use hiroute_domain::{CanonicalDigest, WorkerDependencySelectionRecordV1, WorkspaceId};
use hiroute_integrations::agents::codex_private_worker_catalog;
use super::executor::{WorkerProfileInput, WorkerProfileSource};
-use super::profile::{CandidateWorkerProfile, ProfileInput, SessionRootUse, TaskSessionRoot};
+use super::profile::{
+ CandidateWorkerProfile, NativeWorkerContext, ProfileInput, SessionRootUse, TaskSessionRoot,
+};
#[path = "installation/availability.rs"]
mod availability;
@@ -27,11 +29,18 @@ pub(crate) use discovery::{
discover as discover_worker_dependencies, validate_persisted_installation, validate_selection,
};
+const WORKER_HARNESSES: [WorkerHarnessV1; 3] = [
+ WorkerHarnessV1::CodexCli,
+ WorkerHarnessV1::ClaudeCode,
+ WorkerHarnessV1::QoderCli,
+];
+
#[derive(Clone, Debug)]
pub struct WorkerInstallationConfig {
pub harness: WorkerHarnessV1,
- /// The ACP agent server. It may be a Node script only when `node_binary` is present.
- pub adapter: PathBuf,
+ /// Adapter ACP only; native ACP selects the CLI itself and leaves this absent.
+ /// An adapter may be a Node script only when `node_binary` is present.
+ pub adapter: Option<PathBuf>,
/// The native Harness executable selected by the user/installation owner.
pub harness_binary: PathBuf,
/// The explicitly selected Node runtime for a script adapter, if one is required.
@@ -46,7 +55,7 @@ impl WorkerInstallationConfig {
) -> Self {
Self {
harness: WorkerHarnessV1::CodexCli,
- adapter: adapter.into(),
+ adapter: Some(adapter.into()),
harness_binary: harness_binary.into(),
node_binary: Some(node_binary.into()),
}
@@ -59,16 +68,56 @@ impl WorkerInstallationConfig {
) -> Self {
Self {
harness: WorkerHarnessV1::ClaudeCode,
- adapter: adapter.into(),
+ adapter: Some(adapter.into()),
harness_binary: harness_binary.into(),
node_binary: Some(node_binary.into()),
}
}
+ pub fn qoder_native(harness_binary: impl Into<PathBuf>) -> Self {
+ Self {
+ harness: WorkerHarnessV1::QoderCli,
+ adapter: None,
+ harness_binary: harness_binary.into(),
+ node_binary: None,
+ }
+ }
+
+ pub fn from_record(
+ record: &WorkerDependencySelectionRecordV1,
+ ) -> Result<Self, DelegationErrorV1> {
+ record
+ .validated_launch()
+ .map_err(|_| DelegationErrorV1::DependenciesInvalid)?;
+ Ok(Self {
+ harness: record.harness,
+ adapter: record.adapter_path.as_ref().map(PathBuf::from),
+ harness_binary: PathBuf::from(&record.cli_path),
+ node_binary: record.node_path.as_ref().map(PathBuf::from),
+ })
+ }
+
+ fn selection_record(&self) -> Result<WorkerDependencySelectionRecordV1, DelegationErrorV1> {
+ let path = |path: &Path| {
+ path.to_str()
+ .map(str::to_owned)
+ .ok_or(DelegationErrorV1::DependenciesInvalid)
+ };
+ Ok(WorkerDependencySelectionRecordV1 {
+ harness: self.harness,
+ adapter_path: self.adapter.as_deref().map(path).transpose()?,
+ cli_path: path(&self.harness_binary)?,
+ node_path: self.node_binary.as_deref().map(path).transpose()?,
+ })
+ }
+
fn public_selection(&self) -> hiroute_application_api::WorkerDependencySelectionV1 {
hiroute_application_api::WorkerDependencySelectionV1 {
harness: self.harness,
- adapter_path: self.adapter.to_string_lossy().into_owned(),
+ adapter_path: self
+ .adapter
+ .as_ref()
+ .map(|path| path.to_string_lossy().into_owned()),
cli_path: self.harness_binary.to_string_lossy().into_owned(),
node_path: self
.node_binary
@@ -94,10 +143,20 @@ pub(crate) trait WorkerInstallationSelectionSource: Send + Sync {
pub(super) fn check_installation(
config: &WorkerInstallationConfig,
) -> Result<(), DelegationErrorV1> {
- check_entry(&config.adapter, config.node_binary.is_none())?;
- check_entry(&config.harness_binary, true)?;
- if let Some(node) = &config.node_binary {
- check_entry(node, true)?;
+ use hiroute_domain::delegation::WorkerLaunchFormV1;
+ let record = config.selection_record()?;
+ match record
+ .validated_launch()
+ .map_err(|_| DelegationErrorV1::DependenciesInvalid)?
+ {
+ WorkerLaunchFormV1::NativeAcp { cli } => check_entry(Path::new(cli), true)?,
+ WorkerLaunchFormV1::AdapterAcp { cli, adapter, node } => {
+ check_entry(Path::new(adapter), node.is_none())?;
+ check_entry(Path::new(cli), true)?;
+ if let Some(node) = node {
+ check_entry(Path::new(node), true)?;
+ }
+ }
}
Ok(())
}
@@ -225,6 +284,12 @@ impl WorkerProfileSource for ManagedWorkerProfileSource {
.selection(input.task.plan.harness)?
.ok_or(DelegationErrorV1::DependenciesMissing)?;
let installation = discovery::validate_persisted_installation(&selection.config)?;
+ if installation.harness == WorkerHarnessV1::QoderCli
+ && input.run.configuration.permission_policy
+ != hiroute_domain::delegation::WorkerPermissionPolicyV1::ApproveAll
+ {
+ return Err(DelegationErrorV1::CapabilityUnavailable);
+ }
let roots = WorkerProfileRoots::prepare(&self.storage_root)?;
let task = &input.task;
let run = &input.run;
@@ -293,7 +358,15 @@ impl WorkerProfileSource for ManagedWorkerProfileSource {
if native.root.state != DelegationNativeRootStateV1::Creating {
return Err(DelegationErrorV1::Conflict);
}
- let identity = match session.create_ownership_marker(&roots.sessions, &native.root) {
+ let identity = match (|| {
+ let context = NativeWorkerContext::from_environment(installation.harness)?;
+ session.bind_borrowed_context(
+ context.home(),
+ context.config_root(),
+ &input.workspace_path,
+ )?;
+ session.create_ownership_marker(&roots.sessions, &native.root)
+ })() {
Ok(identity) => identity,
Err(error) => {
let _ = self.runtime.mark_native_root_unknown(
@@ -337,6 +410,35 @@ impl WorkerProfileSource for ManagedWorkerProfileSource {
let private_root = roots
.runs
.join(run_root_name(&task.workspace_id, task, run)?);
+ let (native_context, workspace) = match session.borrowed_context()? {
+ Some(context) => {
+ if fs::canonicalize(&input.workspace_path)
+ .map_err(|_| DelegationErrorV1::ResumeUnavailable)?
+ != context.workspace
+ {
+ return Err(DelegationErrorV1::ResumeUnavailable);
+ }
+ if run.continued_from.is_some() {
+ let native_session_id = task
+ .session
+ .as_ref()
+ .and_then(|session| session.native_session_id.as_deref())
+ .ok_or(DelegationErrorV1::ResumeUnavailable)?;
+ session.verify_native_session(native_session_id)?;
+ }
+ (
+ NativeWorkerContext::borrowed(&context.home, &context.config_root)?,
+ context.workspace,
+ )
+ }
+ None if installation.harness == WorkerHarnessV1::QoderCli => {
+ return Err(DelegationErrorV1::ResumeUnavailable);
+ }
+ None => (
+ NativeWorkerContext::isolated(&private_root, session.path())?,
+ input.workspace_path.clone(),
+ ),
+ };
let admitted_at_ms =
accepted_run_admitted_at_ms(run.deadline_ms, run.execution.duration_ms)?;
let codex_catalog = if installation.harness == WorkerHarnessV1::CodexCli {
@@ -358,8 +460,18 @@ impl WorkerProfileSource for ManagedWorkerProfileSource {
{
return Err(DelegationErrorV1::CapabilityUnavailable);
}
+ let qoder_budget = (installation.harness == WorkerHarnessV1::QoderCli)
+ .then(|| {
+ hiroute_integrations::agents::qoder_plan_token_budget(
+ &input.compiled_plan.body.materialized,
+ )
+ })
+ .transpose()
+ .map_err(|_| DelegationErrorV1::CapabilityUnavailable)?;
CandidateWorkerProfile::build(ProfileInput {
- claude_context_window: if installation.harness == WorkerHarnessV1::ClaudeCode {
+ context_window_tokens: if let Some(budget) = qoder_budget {
+ Some(budget.context_window_tokens)
+ } else if installation.harness == WorkerHarnessV1::ClaudeCode {
Some(
input
.compiled_plan
@@ -371,13 +483,15 @@ impl WorkerProfileSource for ManagedWorkerProfileSource {
} else {
None
},
+ max_output_tokens: qoder_budget.map(|budget| budget.max_output_tokens),
harness: installation.harness,
- adapter: &installation.adapter,
+ adapter: installation.adapter.as_deref(),
harness_binary: &installation.harness_binary,
node_binary: installation.node_binary.as_deref(),
private_root: &private_root,
session_root: &session,
- workspace: &input.workspace_path,
+ native_context: &native_context,
+ workspace: &workspace,
alias: &task.plan.model_alias,
codex_catalog: codex_catalog.as_deref(),
native_effort: None,
diff --git a/crates/daemon/src/delegation/installation/availability.rs b/crates/daemon/src/delegation/installation/availability.rs
index 1475c21d..7de956eb 100644
--- a/crates/daemon/src/delegation/installation/availability.rs
+++ b/crates/daemon/src/delegation/installation/availability.rs
@@ -6,7 +6,7 @@ use hiroute_application_api::{
use hiroute_domain::delegation::WorkerHarnessV1;
use std::sync::Arc;
-use super::{WorkerInstallationSelectionSource, check_installation};
+use super::{WORKER_HARNESSES, WorkerInstallationSelectionSource, check_installation};
pub(crate) struct WorkerExecutorAvailabilityRegistry {
selections: Arc<dyn WorkerInstallationSelectionSource>,
@@ -42,55 +42,49 @@ impl WorkerExecutorAvailabilityRegistry {
pub(crate) fn runtime_unavailable() -> WorkerExecutorAvailabilityListV1 {
executor_list(
- [WorkerHarnessV1::CodexCli, WorkerHarnessV1::ClaudeCode]
+ WORKER_HARNESSES
.map(|harness| unavailable(harness, State::Unknown, Reason::RuntimeUnavailable)),
)
}
pub(crate) fn snapshot(&self) -> WorkerExecutorAvailabilityListV1 {
- executor_list(
- [WorkerHarnessV1::CodexCli, WorkerHarnessV1::ClaudeCode].map(|harness| {
- let selection = match self.selections.selection(harness) {
- Ok(selection) => selection,
- Err(_) => {
- return unavailable(
- harness,
- State::Unavailable,
- Reason::RuntimeUnavailable,
- );
- }
- };
- let Some(selection) = selection else {
- return unavailable(
- harness,
- State::Unavailable,
- Reason::InstallationNotConfigured,
- );
- };
- if check_installation(&selection.config).is_err() {
- return unavailable(harness, State::Unavailable, Reason::ArtifactUnavailable);
+ executor_list(WORKER_HARNESSES.map(|harness| {
+ let selection = match self.selections.selection(harness) {
+ Ok(selection) => selection,
+ Err(_) => {
+ return unavailable(harness, State::Unavailable, Reason::RuntimeUnavailable);
}
- let ready = WorkerExecutorCapabilityAvailabilityV1 {
- state: State::Ready,
- reason: None,
- };
- WorkerExecutorAvailabilityV1 {
+ };
+ let Some(selection) = selection else {
+ return unavailable(
harness,
- state: State::Ready,
- reason: None,
- start_approve_all: ready.clone(),
- cancel: ready,
- continue_session: WorkerExecutorCapabilityAvailabilityV1 {
- state: State::Unknown,
- reason: Some(Reason::CapabilityUnverified),
- },
- restricted_policy: WorkerExecutorCapabilityAvailabilityV1 {
- state: State::Unknown,
- reason: Some(Reason::RestrictedPolicyUnverified),
- },
- }
- }),
- )
+ State::Unavailable,
+ Reason::InstallationNotConfigured,
+ );
+ };
+ if check_installation(&selection.config).is_err() {
+ return unavailable(harness, State::Unavailable, Reason::ArtifactUnavailable);
+ }
+ let ready = WorkerExecutorCapabilityAvailabilityV1 {
+ state: State::Ready,
+ reason: None,
+ };
+ WorkerExecutorAvailabilityV1 {
+ harness,
+ state: State::Ready,
+ reason: None,
+ start_approve_all: ready.clone(),
+ cancel: ready,
+ continue_session: WorkerExecutorCapabilityAvailabilityV1 {
+ state: State::Unknown,
+ reason: Some(Reason::CapabilityUnverified),
+ },
+ restricted_policy: WorkerExecutorCapabilityAvailabilityV1 {
+ state: State::Unknown,
+ reason: Some(Reason::RestrictedPolicyUnverified),
+ },
+ }
+ }))
}
}
@@ -114,10 +108,12 @@ fn unavailable(
}
}
-fn executor_list(executors: [WorkerExecutorAvailabilityV1; 2]) -> WorkerExecutorAvailabilityListV1 {
+fn executor_list(
+ executors: impl IntoIterator<Item = WorkerExecutorAvailabilityV1>,
+) -> WorkerExecutorAvailabilityListV1 {
let list = WorkerExecutorAvailabilityListV1 {
schema: WORKER_EXECUTOR_AVAILABILITY_SCHEMA_V1.into(),
- executors: executors.into(),
+ executors: executors.into_iter().collect(),
};
debug_assert!(list.valid());
list
@@ -155,6 +151,33 @@ mod tests {
WorkerExecutorAvailabilityRegistry::new(Arc::new(StaticSelections(configurations)))
}
+ #[test]
+ fn native_qoder_readiness_requires_only_its_selected_cli_and_rejects_mixed_launch_forms() {
+ let root = tempfile::tempdir().unwrap();
+ let cli = root.path().join("qodercli");
+ fs::write(&cli, b"unexecuted native fixture").unwrap();
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ fs::set_permissions(&cli, fs::Permissions::from_mode(0o700)).unwrap();
+ }
+ let mut config = WorkerInstallationConfig::qoder_native(&cli);
+ let list = registry(vec![config.clone()]).snapshot();
+ let fact = list
+ .executors
+ .iter()
+ .find(|entry| entry.harness == WorkerHarnessV1::QoderCli)
+ .unwrap();
+ assert_eq!(fact.state, State::Ready);
+ assert_eq!(fact.continue_session.state, State::Unknown);
+ assert_eq!(fact.restricted_policy.state, State::Unknown);
+ config.adapter = Some(cli);
+ assert_eq!(
+ check_installation(&config),
+ Err(DelegationErrorV1::DependenciesInvalid)
+ );
+ }
+
#[test]
#[cfg(unix)]
fn worker_installation_accepts_every_diagnostic_version_without_running_it() {
@@ -176,7 +199,7 @@ mod tests {
fs::set_permissions(&binary, fs::Permissions::from_mode(0o700)).unwrap();
let config = WorkerInstallationConfig {
harness,
- adapter: binary.clone(),
+ adapter: Some(binary.clone()),
harness_binary: binary.clone(),
node_binary: None,
};
@@ -208,7 +231,7 @@ mod tests {
}
let config = WorkerInstallationConfig {
harness: WorkerHarnessV1::CodexCli,
- adapter: adapter.clone(),
+ adapter: Some(adapter.clone()),
harness_binary: adapter.clone(),
node_binary: None,
};
@@ -252,7 +275,7 @@ mod tests {
fs::set_permissions(&binary, fs::Permissions::from_mode(0o100)).unwrap();
let config = WorkerInstallationConfig {
harness: WorkerHarnessV1::ClaudeCode,
- adapter: binary.clone(),
+ adapter: Some(binary.clone()),
harness_binary: binary,
node_binary: None,
};
@@ -260,7 +283,7 @@ mod tests {
let fifo = root.path().join("fifo");
nix::unistd::mkfifo(&fifo, nix::sys::stat::Mode::S_IRWXU).unwrap();
let registry = registry(vec![WorkerInstallationConfig {
- adapter: fifo,
+ adapter: Some(fifo),
..config
}]);
assert_eq!(
diff --git a/crates/daemon/src/delegation/installation/discovery.rs b/crates/daemon/src/delegation/installation/discovery.rs
index ef054959..b89efc3f 100644
--- a/crates/daemon/src/delegation/installation/discovery.rs
+++ b/crates/daemon/src/delegation/installation/discovery.rs
@@ -12,7 +12,7 @@ use hiroute_application_api::{
};
use hiroute_domain::delegation::{DelegationErrorV1, WorkerHarnessV1};
-use super::{WorkerInstallationConfig, WorkerInstallationSelectionSource};
+use super::{WORKER_HARNESSES, WorkerInstallationConfig, WorkerInstallationSelectionSource};
const MAX_DIRECTORY_ENTRIES: usize = 256;
const MAX_CANDIDATES: usize = 64;
@@ -34,10 +34,9 @@ fn discover_with_environment(
if !request.valid() {
return Err(DelegationErrorV1::InvalidArguments);
}
- let harnesses = request.harness.map_or_else(
- || vec![WorkerHarnessV1::CodexCli, WorkerHarnessV1::ClaudeCode],
- |harness| vec![harness],
- );
+ let harnesses = request
+ .harness
+ .map_or_else(|| WORKER_HARNESSES.to_vec(), |harness| vec![harness]);
let mut selection_revisions = Vec::with_capacity(harnesses.len());
let mut selected = Vec::new();
let mut candidates = Vec::new();
@@ -57,9 +56,11 @@ fn discover_with_environment(
}
scan.add_path_candidates();
scan.add_common_candidates();
- scan.add_npm_prefix_candidates();
- scan.add_version_manager_candidates();
- scan.add_npx_candidates();
+ if harness != WorkerHarnessV1::QoderCli {
+ scan.add_npm_prefix_candidates();
+ scan.add_version_manager_candidates();
+ scan.add_npx_candidates();
+ }
scan.finish_hints(&mut install_hints);
candidates.extend(scan.candidates);
}
@@ -110,10 +111,11 @@ pub(crate) fn validate_selection(
if !request.valid() {
return Err(DelegationErrorV1::InvalidArguments);
}
- let adapter = normalize_required(
- Path::new(&request.adapter_path),
- request.node_path.is_none(),
- )?;
+ let adapter = request
+ .adapter_path
+ .as_deref()
+ .map(|path| normalize_required(Path::new(path), request.node_path.is_none()))
+ .transpose()?;
let cli = normalize_required(Path::new(&request.cli_path), true)?;
let node = request
.node_path
@@ -122,7 +124,7 @@ pub(crate) fn validate_selection(
.transpose()?;
Ok(WorkerDependenciesSelectRequestV1 {
harness: request.harness,
- adapter_path: path_string(adapter)?,
+ adapter_path: adapter.map(path_string).transpose()?,
cli_path: path_string(cli)?,
node_path: node.map(path_string).transpose()?,
expected_selection_revision: request.expected_selection_revision,
@@ -134,7 +136,10 @@ pub(crate) fn validate_persisted_installation(
) -> Result<WorkerInstallationConfig, DelegationErrorV1> {
let request = WorkerDependenciesSelectRequestV1 {
harness: selection.harness,
- adapter_path: selection.adapter.to_string_lossy().into_owned(),
+ adapter_path: selection
+ .adapter
+ .as_ref()
+ .map(|path| path.to_string_lossy().into_owned()),
cli_path: selection.harness_binary.to_string_lossy().into_owned(),
node_path: selection
.node_binary
@@ -151,7 +156,7 @@ pub(crate) fn validate_persisted_installation(
}
Ok(WorkerInstallationConfig {
harness: normalized.harness,
- adapter: PathBuf::from(normalized.adapter_path),
+ adapter: normalized.adapter_path.map(PathBuf::from),
harness_binary: PathBuf::from(normalized.cli_path),
node_binary: normalized.node_path.map(PathBuf::from),
})
@@ -181,13 +186,15 @@ impl HarnessScan {
}
fn add_selected(&mut self, config: &WorkerInstallationConfig) {
- self.add_explicit(
- WorkerDependencyComponentV1::Adapter,
- &config.adapter,
- WorkerDependencyCandidateSourceV1::Selected,
- config.node_binary.is_none(),
- true,
- );
+ if let Some(adapter) = &config.adapter {
+ self.add_explicit(
+ WorkerDependencyComponentV1::Adapter,
+ adapter,
+ WorkerDependencyCandidateSourceV1::Selected,
+ config.node_binary.is_none(),
+ true,
+ );
+ }
self.add_explicit(
WorkerDependencyComponentV1::Cli,
&config.harness_binary,
@@ -222,6 +229,9 @@ impl HarnessScan {
let mut directories = Vec::new();
if let Some(home) = self.environment.home.as_ref() {
directories.push(home.join(".local/bin"));
+ if self.harness == WorkerHarnessV1::QoderCli {
+ directories.push(home.join(".qoder/bin"));
+ }
}
directories.extend([PathBuf::from("/usr/local/bin"), PathBuf::from("/usr/bin")]);
#[cfg(target_os = "macos")]
@@ -232,6 +242,54 @@ impl HarnessScan {
}
self.add_bin_directory(&directory, WorkerDependencyCandidateSourceV1::Common);
}
+ if self.harness == WorkerHarnessV1::QoderCli {
+ self.add_qoder_standalone_versions();
+ }
+ }
+
+ fn add_qoder_standalone_versions(&mut self) {
+ let Some(home) = self.environment.home.as_ref() else {
+ return;
+ };
+ let entries = match fs::read_dir(home.join(".qoder/bin/qodercli")) {
+ Ok(entries) => entries,
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return,
+ Err(_) => {
+ self.incomplete = true;
+ return;
+ }
+ };
+ let mut paths = Vec::new();
+ for entry in entries {
+ if self.exhausted() {
+ return;
+ }
+ self.directory_entries += 1;
+ match entry {
+ Ok(entry)
+ if entry
+ .file_name()
+ .to_str()
+ .is_some_and(|name| name.starts_with("qodercli-")) =>
+ {
+ paths.push(entry.path())
+ }
+ Ok(_) => {}
+ Err(_) => self.incomplete = true,
+ }
+ }
+ paths.sort();
+ for path in paths {
+ if self.exhausted() {
+ return;
+ }
+ self.add_discovered(
+ WorkerDependencyComponentV1::Cli,
+ &path,
+ WorkerDependencyCandidateSourceV1::Common,
+ true,
+ );
+ }
}
fn add_npm_prefix_candidates(&mut self) {
@@ -298,6 +356,9 @@ impl HarnessScan {
}
fn add_npx_candidates(&mut self) {
+ let Some(package) = package_name(self.harness) else {
+ return;
+ };
let root = self
.environment
.npm_cache
@@ -337,20 +398,25 @@ impl HarnessScan {
return;
}
self.add_npm_package_root(
- &root.join("node_modules").join(package_name(self.harness)),
+ &root.join("node_modules").join(package),
WorkerDependencyCandidateSourceV1::NpxCache,
);
}
}
fn add_bin_directory(&mut self, directory: &Path, source: WorkerDependencyCandidateSourceV1) {
- let (cli, adapter) = names(self.harness);
- self.add_discovered(
- WorkerDependencyComponentV1::Cli,
- &directory.join(cli),
- source,
- true,
- );
+ let (cli_names, adapter) = names(self.harness);
+ for cli in cli_names {
+ self.add_discovered(
+ WorkerDependencyComponentV1::Cli,
+ &directory.join(cli),
+ source,
+ true,
+ );
+ }
+ let Some(adapter) = adapter else {
+ return;
+ };
self.add_discovered(
WorkerDependencyComponentV1::Adapter,
&directory.join(adapter),
@@ -366,9 +432,10 @@ impl HarnessScan {
}
fn add_npm_package(&mut self, prefix: &Path, source: WorkerDependencyCandidateSourceV1) {
- let package_root = prefix
- .join("lib/node_modules")
- .join(package_name(self.harness));
+ let Some(package) = package_name(self.harness) else {
+ return;
+ };
+ let package_root = prefix.join("lib/node_modules").join(package);
self.add_npm_package_root(&package_root, source);
}
@@ -377,8 +444,11 @@ impl HarnessScan {
package_root: &Path,
source: WorkerDependencyCandidateSourceV1,
) {
+ let Some(adapter) = names(self.harness).1 else {
+ return;
+ };
let package_json = package_root.join("package.json");
- let entry = match package_bin(&package_json, names(self.harness).1) {
+ let entry = match package_bin(&package_json, adapter) {
Ok(Some(entry)) => entry,
Ok(None) => return,
Err(()) => {
@@ -454,6 +524,11 @@ impl HarnessScan {
WorkerDependencyComponentV1::Adapter,
WorkerDependencyComponentV1::Node,
] {
+ if self.harness == WorkerHarnessV1::QoderCli
+ && component != WorkerDependencyComponentV1::Cli
+ {
+ continue;
+ }
if !self.candidates.iter().any(|candidate| {
candidate.component == component
&& candidate.state == WorkerDependencyCandidateStateV1::Found
@@ -470,7 +545,11 @@ impl HarnessScan {
if self.incomplete {
hints.push(WorkerDependencyInstallHintV1 {
harness: self.harness,
- component: WorkerDependencyComponentV1::Adapter,
+ component: if self.harness == WorkerHarnessV1::QoderCli {
+ WorkerDependencyComponentV1::Cli
+ } else {
+ WorkerDependencyComponentV1::Adapter
+ },
platform: platform().to_owned(),
command: None,
reason_code: "worker.dependencies.scan_incomplete".to_owned(),
@@ -587,17 +666,19 @@ fn package_bin(package_json: &Path, expected_bin: &str) -> Result<Option<PathBuf
Ok(Some(path.to_path_buf()))
}
-fn names(harness: WorkerHarnessV1) -> (&'static str, &'static str) {
+fn names(harness: WorkerHarnessV1) -> (&'static [&'static str], Option<&'static str>) {
match harness {
- WorkerHarnessV1::CodexCli => ("codex", "codex-acp"),
- WorkerHarnessV1::ClaudeCode => ("claude", "claude-agent-acp"),
+ WorkerHarnessV1::CodexCli => (&["codex"], Some("codex-acp")),
+ WorkerHarnessV1::ClaudeCode => (&["claude"], Some("claude-agent-acp")),
+ WorkerHarnessV1::QoderCli => (&["qoder", "qodercli"], None),
}
}
-fn package_name(harness: WorkerHarnessV1) -> &'static Path {
+fn package_name(harness: WorkerHarnessV1) -> Option<&'static Path> {
match harness {
- WorkerHarnessV1::CodexCli => Path::new("@agentclientprotocol/codex-acp"),
- WorkerHarnessV1::ClaudeCode => Path::new("@agentclientprotocol/claude-agent-acp"),
+ WorkerHarnessV1::CodexCli => Some(Path::new("@agentclientprotocol/codex-acp")),
+ WorkerHarnessV1::ClaudeCode => Some(Path::new("@agentclientprotocol/claude-agent-acp")),
+ WorkerHarnessV1::QoderCli => None,
}
}
diff --git a/crates/daemon/src/delegation/installation/discovery/tests.rs b/crates/daemon/src/delegation/installation/discovery/tests.rs
index ee2dd4e0..1f165d5c 100644
--- a/crates/daemon/src/delegation/installation/discovery/tests.rs
+++ b/crates/daemon/src/delegation/installation/discovery/tests.rs
@@ -28,6 +28,89 @@ fn make_file(path: &Path, mode: u32) {
}
}
+#[test]
+#[cfg(unix)]
+fn qoder_discovers_native_aliases_and_official_root_without_inventing_dependencies_or_replacing_selection()
+ {
+ let root = tempfile::tempdir().unwrap();
+ let home = root.path().join("home");
+ let bin = root.path().join("bin");
+ let cli = bin.join("qodercli");
+ make_file(&cli, 0o700);
+ let invoked = root.path().join("invoked");
+ fs::write(
+ &cli,
+ format!("#!/bin/sh\nprintf invoked > '{}'\n", invoked.display()),
+ )
+ .unwrap();
+ std::os::unix::fs::symlink(&cli, bin.join("qoder")).unwrap();
+ make_file(&bin.join("node"), 0o700);
+ make_file(&bin.join("codex-acp"), 0o700);
+ let official = home.join(".qoder/bin/qodercli/qodercli-1.2.3");
+ make_file(&official, 0o700);
+ let missing = root.path().join("explicitly-selected-but-missing");
+ let config = WorkerInstallationConfig::qoder_native(&missing);
+ let source = StaticSelection(Some(WorkerInstallationSelection {
+ config: config.clone(),
+ revision: 4,
+ }));
+ let view = discover_with_environment(
+ &source,
+ &WorkerDependenciesDiscoverRequestV1 {
+ harness: Some(WorkerHarnessV1::QoderCli),
+ },
+ &ScanEnvironment {
+ path: Some(std::env::join_paths([&bin]).unwrap()),
+ home: Some(home),
+ ..Default::default()
+ },
+ )
+ .unwrap();
+ assert_eq!(view.selected.len(), 1);
+ assert_eq!(view.selected[0].cli_path, missing.to_string_lossy());
+ assert_eq!(view.selected[0].adapter_path, None);
+ assert_eq!(view.selected[0].node_path, None);
+ assert!(
+ view.candidates
+ .iter()
+ .all(|entry| entry.component == WorkerDependencyComponentV1::Cli)
+ );
+ assert!(
+ view.install_hints
+ .iter()
+ .all(|hint| hint.component == WorkerDependencyComponentV1::Cli)
+ );
+ assert_eq!(
+ view.candidates
+ .iter()
+ .filter(|entry| entry.path == cli.to_string_lossy())
+ .count(),
+ 1
+ );
+ assert!(
+ view.candidates
+ .iter()
+ .any(|entry| entry.path == official.to_string_lossy()
+ && entry.state == WorkerDependencyCandidateStateV1::Found)
+ );
+ assert!(matches!(
+ validate_persisted_installation(&config),
+ Err(DelegationErrorV1::DependenciesMissing)
+ ));
+ let request = WorkerDependenciesSelectRequestV1 {
+ harness: WorkerHarnessV1::QoderCli,
+ cli_path: cli.to_string_lossy().into_owned(),
+ adapter_path: None,
+ node_path: None,
+ expected_selection_revision: 4,
+ };
+ assert_eq!(validate_selection(&request).unwrap(), request);
+ assert!(
+ !invoked.exists(),
+ "installation discovery and selection must not launch Qoder"
+ );
+}
+
#[test]
fn script_adapter_requires_readability_but_not_execute_permission() {
let root = tempfile::tempdir().unwrap();
@@ -47,7 +130,7 @@ fn script_adapter_requires_readability_but_not_execute_permission() {
}
let request = WorkerDependenciesSelectRequestV1 {
harness: WorkerHarnessV1::CodexCli,
- adapter_path: adapter.to_string_lossy().into_owned(),
+ adapter_path: Some(adapter.to_string_lossy().into_owned()),
cli_path: cli.to_string_lossy().into_owned(),
node_path: Some(node.to_string_lossy().into_owned()),
expected_selection_revision: 0,
diff --git a/crates/daemon/src/delegation/installation/installation_probe.rs b/crates/daemon/src/delegation/installation/installation_probe.rs
index 4808628b..13fcc69f 100644
--- a/crates/daemon/src/delegation/installation/installation_probe.rs
+++ b/crates/daemon/src/delegation/installation/installation_probe.rs
@@ -26,7 +26,8 @@ use crate::delegation::lifecycle::{self, WorkerRunJournal};
use crate::delegation::local_worker::LocalWorkerPlatform;
use crate::delegation::platform::WorkerLaunchRequest;
use crate::delegation::profile::{
- CandidateWorkerProfile, ProfileInput, SessionRootUse, TaskSessionRoot, test_codex_catalog,
+ CandidateWorkerProfile, NativeWorkerContext, ProfileInput, SessionRootUse, TaskSessionRoot,
+ test_codex_catalog,
};
const PROBE_MODEL: &str = "hiroute/0011223344556677";
@@ -99,7 +100,10 @@ fn run_installation_acceptance_inner(
}
check_installation(config)?;
checkpoint!(EntriesChecked);
- let adapter = &config.adapter;
+ let adapter = config
+ .adapter
+ .as_deref()
+ .ok_or(DelegationErrorV1::CapabilityUnavailable)?;
let harness = &config.harness_binary;
let node = config
.node_binary
@@ -253,6 +257,8 @@ fn harness_kind(harness: WorkerHarnessV1) -> HarnessKind {
match harness {
WorkerHarnessV1::CodexCli => HarnessKind::Codex,
WorkerHarnessV1::ClaudeCode => HarnessKind::Claude,
+ // This historical adapter-only, private-HOME probe is not Qoder acceptance.
+ WorkerHarnessV1::QoderCli => HarnessKind::Unknown,
}
}
@@ -291,13 +297,15 @@ fn build_profile(
};
let catalog = (worker == WorkerHarnessV1::CodexCli).then(|| test_codex_catalog(PROBE_MODEL));
CandidateWorkerProfile::build(ProfileInput {
- claude_context_window: None,
+ context_window_tokens: None,
+ max_output_tokens: None,
harness: worker,
- adapter,
+ adapter: Some(adapter),
harness_binary: harness,
node_binary: Some(node),
private_root,
session_root: session,
+ native_context: &NativeWorkerContext::isolated(private_root, session.path())?,
workspace,
alias: PROBE_MODEL,
codex_catalog: catalog.as_deref(),
@@ -373,6 +381,7 @@ fn run_normal(
let identity_contract = profile.identity_contract.clone();
let session_meta = profile.session_meta.clone();
let native_session_mode = Some(profile.native_session_mode().to_owned());
+ let expected_model = Some(profile.native_selected_model_id().to_owned());
let nonce = nonce.to_owned();
let outcome = block_on(async move {
let deadline = Instant::now() + PROBE_DEADLINE;
@@ -390,6 +399,7 @@ fn run_normal(
identity_contract,
session_meta,
native_session_mode,
+ expected_model,
authentication: None,
deadline,
cancellation: CancellationToken::new(),
@@ -435,6 +445,7 @@ fn run_cancel(
let identity_contract = profile.identity_contract.clone();
let session_meta = profile.session_meta.clone();
let native_session_mode = Some(profile.native_session_mode().to_owned());
+ let expected_model = Some(profile.native_selected_model_id().to_owned());
let nonce = nonce.to_owned();
let expected_request = server.begin_stall();
block_on(async move {
@@ -454,6 +465,7 @@ fn run_cancel(
identity_contract,
session_meta,
native_session_mode,
+ expected_model,
authentication: None,
deadline,
cancellation: cancellation.clone(),
diff --git a/crates/daemon/src/delegation/installation/probe_server.rs b/crates/daemon/src/delegation/installation/probe_server.rs
index ac6a8103..14d886ea 100644
--- a/crates/daemon/src/delegation/installation/probe_server.rs
+++ b/crates/daemon/src/delegation/installation/probe_server.rs
@@ -327,6 +327,7 @@ fn serve_probe_request(
let response = match endpoint.harness {
WorkerHarnessV1::CodexCli => responses_stream(endpoint.model),
WorkerHarnessV1::ClaudeCode => messages_stream(endpoint.model),
+ WorkerHarnessV1::QoderCli => return Err(DelegationErrorV1::CapabilityUnavailable),
};
write!(
stream,
diff --git a/crates/daemon/src/delegation/lifecycle.rs b/crates/daemon/src/delegation/lifecycle.rs
index 4a1605b6..77770fa3 100644
--- a/crates/daemon/src/delegation/lifecycle.rs
+++ b/crates/daemon/src/delegation/lifecycle.rs
@@ -2,7 +2,7 @@
use super::acp::{AcpRunInput, AcpRunJournal, AcpRunOutcome, run_acp_with_progress};
use super::finalization::DelegationFinalizationLease;
use super::platform::*;
-use super::profile::native_history;
+use super::profile::TaskSessionRoot;
use super::progress::{ProgressBatchWriter, ProgressCapture};
use hiroute_domain::delegation::DelegationErrorV1;
use std::fs;
@@ -16,6 +16,8 @@ const CLAUDE_HISTORY_FLUSH_WAIT: Duration = Duration::from_secs(2);
const CLAUDE_HISTORY_QUIET: Duration = Duration::from_millis(200);
const CLAUDE_HISTORY_POLL: Duration = Duration::from_millis(25);
+mod startup;
+
#[derive(Clone, Copy)]
enum HistoryBaseline {
New,
@@ -90,14 +92,13 @@ impl ClaudeHistoryCheckpoint {
}
fn claude_history_len(root: &std::path::Path, native_session_id: &str) -> Option<u64> {
- let relative = native_history(
+ let transcript = TaskSessionRoot::native_transcript_path(
root,
hiroute_domain::delegation::WorkerHarnessV1::ClaudeCode,
native_session_id,
)
- .ok()?
- .pop()?;
- fs::symlink_metadata(root.join(relative))
+ .ok()?;
+ fs::symlink_metadata(transcript)
.ok()
.filter(|metadata| metadata.is_file() && !metadata.file_type().is_symlink())
.map(|metadata| metadata.len())
@@ -191,6 +192,20 @@ pub(crate) async fn execute(
return Err(DelegationErrorV1::DeadlineExceeded);
}
let history_checkpoint = ClaudeHistoryCheckpoint::capture(&request.profile, &input);
+ let startup = match startup::StartupPermit::acquire(
+ request.profile.codex_initialization_root(),
+ input.deadline,
+ &input.cancellation,
+ )
+ .await
+ {
+ Ok(permit) => permit,
+ Err(error) => {
+ let _ = journal.execution_failed(error);
+ return Err(error);
+ }
+ };
+ // Waiting for another native initializer does not preserve stale launch authority.
journal.before_launch()?;
// Dropped launch futures must finitely release acquired resources in the platform backend.
let launch_nonce = request.launch_nonce.clone();
@@ -217,6 +232,9 @@ pub(crate) async fn execute(
}
}
};
+ if let Some(startup) = &startup {
+ startup.bind_process(&worker.identity);
+ }
let binding = if worker.identity.launch_nonce == launch_nonce {
journal.process_spawned(&worker.identity)
} else {
@@ -231,6 +249,10 @@ pub(crate) async fn execute(
}
Ok(()) => {
let acp_journal: Arc<dyn AcpRunJournal> = journal.clone();
+ let acp_journal = startup.as_ref().map_or_else(
+ || acp_journal.clone(),
+ |startup| startup.journal(acp_journal.clone()),
+ );
progress_capture = journal
.progress_writer()
.map(WorkerProgressWriter::into_inner)
@@ -331,6 +353,7 @@ pub async fn stop_owned(
if evidence.scope_stopped && !matches!(evidence.observation, WorkerObservation::Exited { .. }) {
return None;
}
+ startup::observe_stopped(identity, &evidence);
Some(evidence)
}
diff --git a/crates/daemon/src/delegation/lifecycle/startup.rs b/crates/daemon/src/delegation/lifecycle/startup.rs
new file mode 100644
index 00000000..7fa7337f
--- /dev/null
+++ b/crates/daemon/src/delegation/lifecycle/startup.rs
@@ -0,0 +1,151 @@
+//! In-memory startup ownership for a borrowed Codex root, never a task concurrency limit.
+use super::*;
+use crate::delegation::acp::AcpSessionBinding;
+use std::collections::BTreeMap;
+use std::path::Path;
+use std::sync::{Mutex, OnceLock};
+use tokio::sync::{Mutex as AsyncMutex, OwnedMutexGuard};
+use tokio_util::sync::CancellationToken;
+
+#[derive(Default)]
+struct Root {
+ starting: Arc<AsyncMutex<()>>,
+ // Set only while initialization lacks confirmation. A dropped/failed start cannot
+ // forget a possibly running native initializer; verified owned-stop clears it.
+ process: Mutex<Option<WorkerProcessIdentity>>,
+}
+
+#[derive(Default)]
+struct StartupRoots(Mutex<BTreeMap<PathBuf, Arc<Root>>>);
+
+fn lock<T>(value: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
+ value
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner())
+}
+
+fn roots() -> &'static StartupRoots {
+ static ROOTS: OnceLock<StartupRoots> = OnceLock::new();
+ ROOTS.get_or_init(StartupRoots::default)
+}
+
+impl StartupRoots {
+ async fn acquire(
+ &self,
+ path: &Path,
+ deadline: Instant,
+ cancellation: &CancellationToken,
+ ) -> Result<Arc<StartupPermit>, DelegationErrorV1> {
+ let root = {
+ let mut roots = lock(&self.0);
+ roots.retain(|_, root| Arc::strong_count(root) > 1 || lock(&root.process).is_some());
+ roots.entry(path.to_owned()).or_default().clone()
+ };
+ let held = tokio::select! {
+ biased;
+ _ = cancellation.cancelled() => return Err(DelegationErrorV1::Cancelled),
+ _ = tokio::time::sleep_until(deadline) => return Err(DelegationErrorV1::DeadlineExceeded),
+ held = root.starting.clone().lock_owned() => held,
+ };
+ if lock(&root.process).is_some() {
+ // No indefinite wait behind a previous uncertain initializer. The existing
+ // cancellation recovery path must stop that exact held process first.
+ return Err(DelegationErrorV1::Busy);
+ }
+ Ok(Arc::new(StartupPermit {
+ root,
+ held: Mutex::new(Some(held)),
+ }))
+ }
+
+ fn stopped(&self, identity: &WorkerProcessIdentity, evidence: &WorkerStopEvidence) {
+ if !evidence.scope_stopped
+ || evidence.residual_unknown
+ || !matches!(evidence.observation, WorkerObservation::Exited { .. })
+ {
+ return;
+ }
+ for root in lock(&self.0).values() {
+ let mut process = lock(&root.process);
+ if process.as_ref() == Some(identity) {
+ *process = None;
+ }
+ }
+ }
+}
+
+pub(super) struct StartupPermit {
+ root: Arc<Root>,
+ held: Mutex<Option<OwnedMutexGuard<()>>>,
+}
+
+impl StartupPermit {
+ pub(super) async fn acquire(
+ path: Option<&Path>,
+ deadline: Instant,
+ cancellation: &CancellationToken,
+ ) -> Result<Option<Arc<Self>>, DelegationErrorV1> {
+ match path {
+ Some(path) => roots()
+ .acquire(path, deadline, cancellation)
+ .await
+ .map(Some),
+ None => Ok(None),
+ }
+ }
+
+ pub(super) fn bind_process(&self, identity: &WorkerProcessIdentity) {
+ *lock(&self.root.process) = Some(identity.clone());
+ }
+
+ fn initialized(&self) {
+ let mut held = lock(&self.held);
+ if held.is_some() {
+ *lock(&self.root.process) = None;
+ // Release before session/new, session/load, model selection or any prompt.
+ // A repeated receipt from this run cannot release a later initializer.
+ held.take();
+ }
+ }
+
+ pub(super) fn journal(
+ self: &Arc<Self>,
+ inner: Arc<dyn AcpRunJournal>,
+ ) -> Arc<dyn AcpRunJournal> {
+ Arc::new(StartupJournal {
+ inner,
+ permit: self.clone(),
+ })
+ }
+}
+
+pub(super) fn observe_stopped(identity: &WorkerProcessIdentity, evidence: &WorkerStopEvidence) {
+ roots().stopped(identity, evidence);
+}
+
+struct StartupJournal {
+ inner: Arc<dyn AcpRunJournal>,
+ permit: Arc<StartupPermit>,
+}
+
+impl AcpRunJournal for StartupJournal {
+ fn initialized(&self) {
+ self.permit.initialized();
+ self.inner.initialized();
+ }
+ fn session_bound(&self, binding: &AcpSessionBinding) -> Result<(), DelegationErrorV1> {
+ self.inner.session_bound(binding)
+ }
+ fn before_prompt(&self) -> Result<(), DelegationErrorV1> {
+ self.inner.before_prompt()
+ }
+ fn text_update(&self, text: &str) -> Result<(), DelegationErrorV1> {
+ self.inner.text_update(text)
+ }
+ fn allow_permission_once(&self, request: &serde_json::Value) -> bool {
+ self.inner.allow_permission_once(request)
+ }
+}
+
+#[cfg(test)]
+mod tests;
diff --git a/crates/daemon/src/delegation/lifecycle/startup/tests.rs b/crates/daemon/src/delegation/lifecycle/startup/tests.rs
new file mode 100644
index 00000000..e7f2e723
--- /dev/null
+++ b/crates/daemon/src/delegation/lifecycle/startup/tests.rs
@@ -0,0 +1,116 @@
+use super::*;
+use std::future::{Future, poll_fn};
+use std::task::Poll;
+
+fn identity(nonce: &str) -> WorkerProcessIdentity {
+ WorkerProcessIdentity {
+ launch_nonce: nonce.into(),
+ handle_id: "held-process".into(),
+ creation_identity: "creation".into(),
+ }
+}
+
+async fn assert_pending<F: Future + Unpin>(future: &mut F) {
+ poll_fn(|cx| match std::pin::Pin::new(&mut *future).poll(cx) {
+ Poll::Pending => Poll::Ready(()),
+ Poll::Ready(_) => panic!("a second initializer bypassed the held root"),
+ })
+ .await;
+}
+
+#[tokio::test]
+async fn only_initialization_is_serialized_and_an_old_receipt_cannot_release_a_new_owner() {
+ let roots = StartupRoots::default();
+ let cancel = CancellationToken::new();
+ let deadline = Instant::now() + Duration::from_secs(5);
+ let root = Path::new("/same-native-root");
+ let first = roots.acquire(root, deadline, &cancel).await.unwrap();
+ first.bind_process(&identity("first"));
+ let mut second = Box::pin(roots.acquire(root, deadline, &cancel));
+ assert_pending(&mut second).await;
+ let unrelated = roots
+ .acquire(Path::new("/different-native-root"), deadline, &cancel)
+ .await
+ .unwrap();
+ drop(unrelated);
+ first.initialized();
+ let second = second.await.unwrap();
+ second.bind_process(&identity("second"));
+ first.initialized();
+ let mut third = Box::pin(roots.acquire(root, deadline, &cancel));
+ assert_pending(&mut third).await;
+ assert_eq!(*lock(&second.root.process), Some(identity("second")));
+ second.initialized();
+ assert!(third.await.is_ok());
+}
+
+#[tokio::test]
+async fn waiting_obeys_cancellation_and_deadline_without_discarding_the_active_initializer() {
+ let roots = StartupRoots::default();
+ let root = Path::new("/native-root");
+ let cancel = CancellationToken::new();
+ let deadline = Instant::now() + Duration::from_secs(5);
+ let owner = roots.acquire(root, deadline, &cancel).await.unwrap();
+ let waiting_cancel = CancellationToken::new();
+ let mut waiting = Box::pin(roots.acquire(root, deadline, &waiting_cancel));
+ assert_pending(&mut waiting).await;
+ waiting_cancel.cancel();
+ assert!(matches!(waiting.await, Err(DelegationErrorV1::Cancelled)));
+ assert!(matches!(
+ roots.acquire(root, Instant::now(), &cancel).await,
+ Err(DelegationErrorV1::DeadlineExceeded)
+ ));
+ // A start abandoned before spawn needs no residual identity or recovery operation.
+ drop(owner);
+ assert!(roots.acquire(root, deadline, &cancel).await.is_ok());
+}
+
+#[tokio::test]
+async fn uncertain_initialization_requires_verified_stop_of_the_exact_process() {
+ let roots = StartupRoots::default();
+ let root = Path::new("/native-root");
+ let cancel = CancellationToken::new();
+ let deadline = Instant::now() + Duration::from_secs(5);
+ let owner = roots.acquire(root, deadline, &cancel).await.unwrap();
+ let process = identity("first");
+ owner.bind_process(&process);
+ drop(owner);
+ let mut evidence = WorkerStopEvidence {
+ scope: WorkerStopScope::ProcessGroup,
+ observation: WorkerObservation::Exited { code: None },
+ scope_stopped: true,
+ residual_unknown: false,
+ };
+ for wrong in [
+ identity("another-launch"),
+ WorkerProcessIdentity {
+ handle_id: "another-held-object".into(),
+ ..process.clone()
+ },
+ WorkerProcessIdentity {
+ creation_identity: "reused-object".into(),
+ ..process.clone()
+ },
+ ] {
+ roots.stopped(&wrong, &evidence);
+ assert!(matches!(
+ roots.acquire(root, deadline, &cancel).await,
+ Err(DelegationErrorV1::Busy)
+ ));
+ }
+ evidence.residual_unknown = true;
+ roots.stopped(&process, &evidence);
+ evidence.residual_unknown = false;
+ evidence.scope_stopped = false;
+ roots.stopped(&process, &evidence);
+ evidence.scope_stopped = true;
+ evidence.observation = WorkerObservation::Running;
+ roots.stopped(&process, &evidence);
+ assert!(matches!(
+ roots.acquire(root, deadline, &cancel).await,
+ Err(DelegationErrorV1::Busy)
+ ));
+ evidence.observation = WorkerObservation::Exited { code: None };
+ roots.stopped(&process, &evidence);
+ assert!(roots.acquire(root, deadline, &cancel).await.is_ok());
+}
diff --git a/crates/daemon/src/delegation/lifecycle/tests.rs b/crates/daemon/src/delegation/lifecycle/tests.rs
index ee437aef..c83b5fdc 100644
--- a/crates/daemon/src/delegation/lifecycle/tests.rs
+++ b/crates/daemon/src/delegation/lifecycle/tests.rs
@@ -9,10 +9,13 @@ use std::sync::Mutex;
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio_util::sync::CancellationToken;
+mod startup;
+
#[derive(Default)]
struct Journal(
Mutex<Vec<&'static str>>,
Option<Arc<crate::delegation::finalization::DelegationFinalization>>,
+ std::sync::atomic::AtomicBool,
);
impl AcpRunJournal for Journal {
fn session_bound(&self, _: &AcpSessionBinding) -> Result<(), DelegationErrorV1> {
@@ -39,7 +42,11 @@ impl WorkerRunJournal for Journal {
fn before_launch(&self) -> Result<(), DelegationErrorV1> {
self.0.lock().unwrap().push("authorize");
- Ok(())
+ if self.2.load(std::sync::atomic::Ordering::SeqCst) {
+ Err(DelegationErrorV1::PermissionDenied)
+ } else {
+ Ok(())
+ }
}
fn process_spawned(&self, _: &WorkerProcessIdentity) -> Result<(), DelegationErrorV1> {
self.0.lock().unwrap().push("spawned");
@@ -171,6 +178,12 @@ impl WorkerPlatformPort for Fixture {
}
fn inputs() -> (WorkerLaunchRequest, AcpRunInput, tempfile::TempDir) {
+ inputs_in_context(None)
+}
+
+fn inputs_in_context(
+ borrowed_root: Option<&std::path::Path>,
+) -> (WorkerLaunchRequest, AcpRunInput, tempfile::TempDir) {
let fixture = tempfile::tempdir().unwrap();
#[cfg(unix)]
{
@@ -210,17 +223,28 @@ fn inputs() -> (WorkerLaunchRequest, AcpRunInput, tempfile::TempDir) {
duration_ms: 1000,
delegation_depth: 1,
};
+ let native_context = match borrowed_root {
+ Some(root) => {
+ crate::delegation::profile::NativeWorkerContext::borrowed(fixture.path(), root)
+ }
+ None => crate::delegation::profile::NativeWorkerContext::isolated(&private, session.path()),
+ }
+ .unwrap();
+ let catalog =
+ borrowed_root.map(|_| crate::delegation::profile::test_codex_catalog("fixed-alias"));
let profile = CandidateWorkerProfile::build(ProfileInput {
- claude_context_window: None,
+ context_window_tokens: None,
+ max_output_tokens: None,
harness: WorkerHarnessV1::CodexCli,
- adapter: &adapter,
+ adapter: Some(&adapter),
harness_binary: &harness,
node_binary: None,
private_root: &private,
session_root: &session,
+ native_context: &native_context,
workspace: &cwd,
alias: "fixed-alias",
- codex_catalog: None,
+ codex_catalog: catalog.as_deref(),
native_effort: None,
gateway: "127.0.0.1:10001".parse().unwrap(),
permit: &permit,
@@ -237,6 +261,7 @@ fn inputs() -> (WorkerLaunchRequest, AcpRunInput, tempfile::TempDir) {
identity_contract: profile.identity_contract.clone(),
session_meta: profile.session_meta.clone(),
native_session_mode: Some(profile.native_session_mode().to_owned()),
+ expected_model: None,
authentication: None,
deadline: Instant::now() + Duration::from_secs(1),
cancellation: CancellationToken::new(),
@@ -398,7 +423,11 @@ async fn spawn_stdio_acp_result_and_owned_cleanup_need_no_helper_handshake() {
#[tokio::test]
async fn terminal_publication_lease_survives_until_the_executor_receives_the_result() {
let finalization = Arc::new(crate::delegation::finalization::DelegationFinalization::default());
- let journal = Arc::new(Journal(Mutex::default(), Some(Arc::clone(&finalization))));
+ let journal = Arc::new(Journal(
+ Mutex::default(),
+ Some(Arc::clone(&finalization)),
+ Default::default(),
+ ));
let backend = Fixture {
journal: Arc::clone(&journal),
methods: Arc::default(),
@@ -460,6 +489,62 @@ async fn claude_history_checkpoint_observes_new_and_appended_stable_transcripts(
}
}
+#[tokio::test]
+async fn borrowed_claude_checkpoint_observes_native_file_instead_of_owned_binding() {
+ let storage = tempfile::tempdir().unwrap();
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ fs::set_permissions(storage.path(), fs::Permissions::from_mode(0o700)).unwrap();
+ }
+ let workspace = storage.path().join("workspace");
+ let home = storage.path().join("daily-home");
+ let config = home.join("native-config");
+ fs::create_dir_all(&config).unwrap();
+ fs::create_dir(&workspace).unwrap();
+ let session = TaskSessionRoot::prepare(
+ storage.path(),
+ &hiroute_domain::WorkspaceId::parse("workspace").unwrap(),
+ "root",
+ "task",
+ WorkerHarnessV1::ClaudeCode,
+ SessionRootUse::New,
+ )
+ .unwrap();
+ session
+ .bind_borrowed_context(&home, &config, &workspace)
+ .unwrap();
+ let project = fs::canonicalize(workspace)
+ .unwrap()
+ .to_str()
+ .unwrap()
+ .replace(|ch: char| !ch.is_ascii_alphanumeric(), "-");
+ let id = "71a2b020-312e-49cd-b084-924cbb3642ad";
+ let history = config
+ .join("projects")
+ .join(project)
+ .join(format!("{id}.jsonl"));
+ fs::create_dir_all(history.parent().unwrap()).unwrap();
+ fs::write(&history, b"old\n").unwrap();
+ crate::delegation::profile::native_history(session.path(), WorkerHarnessV1::ClaudeCode, id)
+ .unwrap();
+ assert_eq!(claude_history_len(session.path(), id), Some(4));
+ let checkpoint = ClaudeHistoryCheckpoint {
+ root: session.path().to_owned(),
+ baseline: HistoryBaseline::Existing(4),
+ };
+ let writer = tokio::spawn(async move {
+ tokio::time::sleep(Duration::from_millis(40)).await;
+ use std::io::Write;
+ let mut file = fs::OpenOptions::new().append(true).open(history).unwrap();
+ file.write_all(b"new\n").unwrap();
+ file.sync_all().unwrap();
+ });
+ assert!(checkpoint.wait_until_settled(Some(id)).await);
+ writer.await.unwrap();
+ assert_eq!(claude_history_len(session.path(), id), Some(8));
+}
+
#[tokio::test]
async fn prompt_disconnect_never_respawns_or_replays_and_cleanup_is_not_completion() {
let journal = Arc::new(Journal::default());
diff --git a/crates/daemon/src/delegation/lifecycle/tests/startup.rs b/crates/daemon/src/delegation/lifecycle/tests/startup.rs
new file mode 100644
index 00000000..166e5782
--- /dev/null
+++ b/crates/daemon/src/delegation/lifecycle/tests/startup.rs
@@ -0,0 +1,413 @@
+//! Product boundary regressions: shared-root startup, not serialized native tasks.
+use super::*;
+use std::sync::atomic::{AtomicBool, Ordering};
+use tokio::sync::{Semaphore, mpsc};
+
+struct StartupFixture {
+ events: mpsc::UnboundedSender<String>,
+ initialize: Semaphore,
+ sessions: Semaphore,
+ stop: Semaphore,
+ protocol_version: u32,
+ unknown_stop: AtomicBool,
+}
+
+impl StartupFixture {
+ fn new() -> (Arc<Self>, mpsc::UnboundedReceiver<String>) {
+ let (events, receiver) = mpsc::unbounded_channel();
+ (
+ Arc::new(Self {
+ events,
+ initialize: Semaphore::new(0),
+ sessions: Semaphore::new(0),
+ stop: Semaphore::new(0),
+ protocol_version: 1,
+ unknown_stop: AtomicBool::new(false),
+ }),
+ receiver,
+ )
+ }
+}
+
+#[async_trait::async_trait]
+impl WorkerPlatformPort for Arc<StartupFixture> {
+ fn capabilities(
+ &self,
+ _: &CandidateWorkerProfile,
+ ) -> Result<WorkerPlatformCapabilities, DelegationErrorV1> {
+ Ok(WorkerPlatformCapabilities {
+ can_start: true,
+ can_stop: true,
+ })
+ }
+
+ async fn launch(&self, request: WorkerLaunchRequest) -> Result<ReadyWorker, DelegationErrorV1> {
+ self.events.send("spawn".into()).unwrap();
+ let (client, server) = tokio::io::duplex(8192);
+ let fixture = self.clone();
+ tokio::spawn(async move {
+ let (r, mut w) = tokio::io::split(server);
+ let mut lines = BufReader::new(r).lines();
+ while let Ok(Some(line)) = lines.next_line().await {
+ let request: serde_json::Value = serde_json::from_str(&line).unwrap();
+ let method = request["method"].as_str().unwrap();
+ fixture.events.send(method.into()).unwrap();
+ let result = match method {
+ "initialize" => {
+ fixture.initialize.acquire().await.unwrap().forget();
+ serde_json::json!({"protocolVersion":fixture.protocol_version,"agentCapabilities":{"loadSession":true}})
+ }
+ "session/new" | "session/load" => {
+ fixture.sessions.acquire().await.unwrap().forget();
+ serde_json::json!({"sessionId":"native-session"})
+ }
+ "session/prompt" => serde_json::json!({"stopReason":"end_turn"}),
+ "session/cancel" => continue,
+ _ => panic!("unexpected fixture method {method}"),
+ };
+ let response =
+ serde_json::json!({"jsonrpc":"2.0","id":request["id"],"result":result});
+ if w.write_all(format!("{response}\n").as_bytes())
+ .await
+ .is_err()
+ {
+ break;
+ }
+ }
+ });
+ let (stdout, stdin) = tokio::io::split(client);
+ Ok(ReadyWorker {
+ identity: WorkerProcessIdentity {
+ launch_nonce: request.launch_nonce,
+ handle_id: "held-initializer".into(),
+ creation_identity: "creation".into(),
+ },
+ stdin: Box::pin(stdin),
+ stdout: Box::pin(stdout),
+ })
+ }
+
+ async fn observe(
+ &self,
+ _: &WorkerProcessIdentity,
+ ) -> Result<WorkerObservation, DelegationErrorV1> {
+ Ok(WorkerObservation::Unknown)
+ }
+
+ async fn terminate(
+ &self,
+ _: &WorkerProcessIdentity,
+ _: u64,
+ ) -> Result<WorkerStopEvidence, DelegationErrorV1> {
+ self.events.send("stop".into()).unwrap();
+ self.stop.acquire().await.unwrap().forget();
+ if self.unknown_stop.load(Ordering::SeqCst) {
+ return Err(DelegationErrorV1::CapabilityUnavailable);
+ }
+ Ok(WorkerStopEvidence {
+ scope: WorkerStopScope::ProcessGroup,
+ observation: WorkerObservation::Exited { code: None },
+ scope_stopped: true,
+ residual_unknown: false,
+ })
+ }
+}
+
+async fn next(events: &mut mpsc::UnboundedReceiver<String>, expected: &str) {
+ assert_eq!(
+ timeout(Duration::from_secs(2), events.recv())
+ .await
+ .unwrap()
+ .as_deref(),
+ Some(expected)
+ );
+}
+
+fn borrowed(
+ root: &std::path::Path,
+ nonce: &str,
+) -> (WorkerLaunchRequest, AcpRunInput, tempfile::TempDir) {
+ let (mut request, mut input, fixture) = inputs_in_context(Some(root));
+ request.launch_nonce = nonce.into();
+ input.deadline = Instant::now() + Duration::from_secs(5);
+ input.native_session_mode = None;
+ (request, input, fixture)
+}
+
+#[tokio::test]
+async fn shared_codex_startup_releases_before_new_or_load_and_does_not_serialize_tasks() {
+ for load in [false, true] {
+ let root = tempfile::tempdir().unwrap();
+ let (first_request, mut first_input, _first_dir) = borrowed(root.path(), "first");
+ let (second_request, mut second_input, _second_dir) = borrowed(root.path(), "second");
+ if load {
+ let binding = AcpSessionBinding {
+ acp_session_id: "native-session".into(),
+ native_session_id: Some("native-session".into()),
+ };
+ first_input.session = AcpSessionStart::Load(binding.clone());
+ second_input.session = AcpSessionStart::Load(binding);
+ }
+ let (first, mut first_events) = StartupFixture::new();
+ let (second, mut second_events) = StartupFixture::new();
+ let controller = async {
+ next(&mut first_events, "spawn").await;
+ next(&mut first_events, "initialize").await;
+ // Both execute futures are polled, yet the second must not spawn before confirmation.
+ assert!(
+ timeout(Duration::from_millis(20), second_events.recv())
+ .await
+ .is_err()
+ );
+ first.initialize.add_permits(1);
+ let method = if load { "session/load" } else { "session/new" };
+ next(&mut first_events, method).await;
+ next(&mut second_events, "spawn").await;
+ next(&mut second_events, "initialize").await;
+ second.initialize.add_permits(1);
+ next(&mut second_events, method).await;
+ // Neither native session has answered New/Load; both starts already passed the gate.
+ first.sessions.add_permits(1);
+ second.sessions.add_permits(1);
+ first.stop.add_permits(1);
+ second.stop.add_permits(1);
+ };
+ let (first_result, second_result, ()) = tokio::join!(biased;
+ execute(&first, first_request, first_input, Arc::new(Journal::default())),
+ execute(&second, second_request, second_input, Arc::new(Journal::default())),
+ controller,
+ );
+ assert!(first_result.unwrap().execution.is_ok());
+ assert!(second_result.unwrap().execution.is_ok());
+ next(&mut first_events, "session/prompt").await;
+ next(&mut second_events, "session/prompt").await;
+ }
+}
+
+#[tokio::test]
+async fn incompatible_initialize_holds_the_root_until_owned_stop_then_allows_another_start() {
+ let root = tempfile::tempdir().unwrap();
+ let (first_request, first_input, _first_dir) = borrowed(root.path(), "incompatible");
+ let (second_request, second_input, _second_dir) = borrowed(root.path(), "next");
+ let (mut first, mut first_events) = StartupFixture::new();
+ Arc::get_mut(&mut first).unwrap().protocol_version = 2;
+ let (second, mut second_events) = StartupFixture::new();
+ let controller = async {
+ next(&mut first_events, "spawn").await;
+ next(&mut first_events, "initialize").await;
+ first.initialize.add_permits(1);
+ next(&mut first_events, "stop").await;
+ assert!(
+ timeout(Duration::from_millis(20), second_events.recv())
+ .await
+ .is_err()
+ );
+ first.stop.add_permits(1);
+ next(&mut second_events, "spawn").await;
+ next(&mut second_events, "initialize").await;
+ second.initialize.add_permits(1);
+ second.sessions.add_permits(1);
+ second.stop.add_permits(1);
+ };
+ let (first_result, second_result, ()) = tokio::join!(biased;
+ execute(&first, first_request, first_input, Arc::new(Journal::default())),
+ execute(&second, second_request, second_input, Arc::new(Journal::default())),
+ controller,
+ );
+ assert!(matches!(
+ first_result.unwrap().execution,
+ Err(DelegationErrorV1::CapabilityUnavailable)
+ ));
+ assert!(second_result.unwrap().execution.is_ok());
+}
+
+#[tokio::test]
+async fn failed_initializer_with_unknown_stop_blocks_until_the_existing_stop_path_verifies_it() {
+ let root = tempfile::tempdir().unwrap();
+ let (request, input, _dir) = borrowed(root.path(), "uncertain");
+ let (mut platform, mut events) = StartupFixture::new();
+ Arc::get_mut(&mut platform).unwrap().protocol_version = 2;
+ platform.unknown_stop.store(true, Ordering::SeqCst);
+ platform.initialize.add_permits(1);
+ platform.stop.add_permits(1);
+ let failed = execute(&platform, request, input, Arc::new(Journal::default()))
+ .await
+ .unwrap();
+ assert!(failed.stop.is_none());
+ for expected in ["spawn", "initialize", "stop"] {
+ next(&mut events, expected).await;
+ }
+ let (request, input, _dir) = borrowed(root.path(), "blocked");
+ assert!(matches!(
+ execute(&platform, request, input, Arc::new(Journal::default())).await,
+ Err(DelegationErrorV1::Busy)
+ ));
+ assert!(
+ events.try_recv().is_err(),
+ "a blocked initializer must not spawn"
+ );
+ platform.unknown_stop.store(false, Ordering::SeqCst);
+ platform.stop.add_permits(1);
+ assert!(
+ stop_owned(&platform, &failed.identity)
+ .await
+ .unwrap()
+ .scope_stopped
+ );
+ let (request, input, _dir) = borrowed(root.path(), "recovered");
+ let (platform, _events) = StartupFixture::new();
+ platform.initialize.add_permits(1);
+ platform.sessions.add_permits(1);
+ platform.stop.add_permits(1);
+ assert!(
+ execute(&platform, request, input, Arc::new(Journal::default()))
+ .await
+ .unwrap()
+ .execution
+ .is_ok()
+ );
+}
+
+#[tokio::test]
+async fn queued_starts_obey_cancel_deadline_and_recheck_authority_before_spawn() {
+ use std::future::{Future, poll_fn};
+ use std::task::Poll;
+ for case in ["cancel", "deadline", "revoke"] {
+ let root = tempfile::tempdir().unwrap();
+ let cancel = CancellationToken::new();
+ let held = super::super::startup::StartupPermit::acquire(
+ Some(root.path()),
+ Instant::now() + Duration::from_secs(5),
+ &cancel,
+ )
+ .await
+ .unwrap()
+ .unwrap();
+ let (request, mut input, _dir) = borrowed(root.path(), case);
+ if case == "deadline" {
+ input.deadline = Instant::now() + Duration::from_millis(50);
+ }
+ let cancellation = input.cancellation.clone();
+ let journal = Arc::new(Journal::default());
+ let (platform, mut events) = StartupFixture::new();
+ let mut execution = Box::pin(execute(&platform, request, input, journal.clone()));
+ poll_fn(|cx| match execution.as_mut().poll(cx) {
+ Poll::Pending => Poll::Ready(()),
+ Poll::Ready(_) => panic!("queued start unexpectedly completed"),
+ })
+ .await;
+ assert!(
+ journal.0.lock().unwrap().is_empty(),
+ "authority must be checked after waiting"
+ );
+ let expected = match case {
+ "cancel" => {
+ cancellation.cancel();
+ DelegationErrorV1::Cancelled
+ }
+ "deadline" => DelegationErrorV1::DeadlineExceeded,
+ "revoke" => {
+ journal.2.store(true, Ordering::SeqCst);
+ drop(held);
+ DelegationErrorV1::PermissionDenied
+ }
+ _ => unreachable!(),
+ };
+ assert!(matches!(execution.await, Err(error) if error == expected));
+ assert!(events.try_recv().is_err(), "rejected start must not spawn");
+ if case == "revoke" {
+ assert_eq!(*journal.0.lock().unwrap(), ["authorize"]);
+ }
+ }
+}
+
+#[tokio::test]
+async fn repeated_durable_cancel_recovers_the_failed_initializers_root_without_respawning() {
+ use crate::delegation::authorization_tests::fixture::sample;
+ use crate::delegation::dispatcher::{
+ CancellationDispatchState, DelegationCancellationDispatcher,
+ };
+ use hiroute_domain::OperationId;
+ use hiroute_local_storage::LocalStorageSet;
+ let root = tempfile::tempdir().unwrap();
+ let stores = LocalStorageSet::open_for_daemon_startup(root.path().join("store")).unwrap();
+ let run = stores
+ .runtime()
+ .accept(&sample("task", "run", "workspace-root"))
+ .unwrap();
+ let run = stores
+ .runtime()
+ .checkpoint(
+ &run.workspace_id,
+ &run.run_id,
+ run.progress.revision,
+ "preparing",
+ &DelegationCheckpointV1::Progress {
+ event: RunEventV1::Preparing,
+ },
+ )
+ .unwrap();
+ let process = WorkerProcessIdentity {
+ launch_nonce: run.launch_nonce.clone(),
+ handle_id: "held-initializer".into(),
+ creation_identity: "creation".into(),
+ };
+ stores
+ .runtime()
+ .checkpoint(
+ &run.workspace_id,
+ &run.run_id,
+ run.progress.revision,
+ "bound",
+ &DelegationCheckpointV1::ProcessSpawned {
+ binding: process.clone(),
+ },
+ )
+ .unwrap();
+ let cancel = CancellationToken::new();
+ let deadline = Instant::now() + Duration::from_secs(5);
+ let owner = super::super::startup::StartupPermit::acquire(Some(root.path()), deadline, &cancel)
+ .await
+ .unwrap()
+ .unwrap();
+ owner.bind_process(&process);
+ drop(owner);
+ let operation = OperationId::parse("op_00112233445566778899aabbccddeeff").unwrap();
+ let dispatcher = DelegationCancellationDispatcher::default();
+ let (platform, mut events) = StartupFixture::new();
+ for unknown in [true, false] {
+ // Public worker_cancel also wakes this dispatcher on an idempotent receipt replay.
+ stores
+ .runtime()
+ .request_cancel(&run.workspace_id, &run.run_id, &operation, "user")
+ .unwrap();
+ platform.unknown_stop.store(unknown, Ordering::SeqCst);
+ platform.stop.add_permits(1);
+ let result = dispatcher
+ .dispatch_pending(stores.runtime(), &run.workspace_id, &platform)
+ .await
+ .unwrap();
+ assert_eq!(result.len(), 1);
+ assert_eq!(
+ result[0].state,
+ if unknown {
+ CancellationDispatchState::ResidualUnknown
+ } else {
+ CancellationDispatchState::Stopped
+ }
+ );
+ next(&mut events, "stop").await;
+ assert!(
+ events.try_recv().is_err(),
+ "recovery must never spawn, initialize or prompt"
+ );
+ let acquired =
+ super::super::startup::StartupPermit::acquire(Some(root.path()), deadline, &cancel)
+ .await;
+ if unknown {
+ assert!(matches!(acquired, Err(DelegationErrorV1::Busy)));
+ } else {
+ assert!(acquired.is_ok());
+ }
+ }
+}
diff --git a/crates/daemon/src/delegation/local_worker/README.md b/crates/daemon/src/delegation/local_worker/README.md
index 5f6ffc60..92502909 100644
--- a/crates/daemon/src/delegation/local_worker/README.md
+++ b/crates/daemon/src/delegation/local_worker/README.md
@@ -1,50 +1,41 @@
-# MVP-18 local Worker launcher
+# Local Worker launcher
-Implements the MVP-20 consumer `WorkerPlatformPort`. It owns OS child objects,
+Implements the daemon consumer `WorkerPlatformPort`. It owns OS child objects,
stdio, and explicitly requested temporary materials. It does not interpret ACP,
permissions, Harness configuration, Plan, tokens, or sessions.
-## Branch convergence
-
-The consumer slice is from exactly
-`7dddd8a1149de53645bcc538728a74e72fd05064`:
-
-- `delegation/platform.rs` is imported unchanged.
-- `delegation/profile/mod.rs` imports the existing profile builder without its
- unrelated tests. No profile behavior is changed.
-- `delegation/acp/mod.rs` contains only the existing identity-contract enum,
- without the ACP transport/driver or unused imports.
-- `domain/delegation/mod.rs` imports the permit/intent/error types and existing
- authorization methods required to compile that builder, plus the existing
- `DelegationProcessBindingV1`; unrelated progress/records/tests are excluded.
-- `domain/delegation/process.rs` is unchanged.
-
-These are branch-local consumer dependencies, not a second platform API. The
-coordinator replaces their exports with the final consumer tree at convergence.
-Shared intent: export `delegation::local_worker`, enable Tokio `process`, add the
-existing workspace Rustix dependency to daemon on Unix, use the already locked
-`same-file=1.0.6` safe directory handle for root identity on both OSes, and converge Cargo.lock.
-
-The additional fixed materials slice is exactly
-`95ee7f4b1c55c77d9e38bcb78a662d1306dbf2ce`. Its profile builder/materials module
-and required `valid_delegation_id` helper are imported unchanged (excluding
-unrelated profile tests). TaskSessionRoot preparation/history inventory remain
-20's code and responsibility; local_worker only consumes their output.
+## Production ownership
+
+The daemon's [profile builder](../profile/mod.rs) prepares the candidate;
+[execution](../executor.rs) drives the lifecycle through
+[`WorkerPlatformPort`](../platform.rs). This module consumes the prepared
+materials and session root, owns process/stdio handles, and cleans up only its own
+private root. Harness discovery, ACP interpretation, authorization and session
+history remain in their respective sibling modules.
`launch` directly consumes `CandidateWorkerProfile.materials` and `session_root`.
There is no preparation registry, path template, or alternative launch API.
The external session root must already exist and must not equal or nest with the
-new private root. Materials may contain only directories and an empty file list.
+new private root. Materials may contain explicitly rendered directories and opaque files, within
+the entry-count and content-size limits in [materials.rs](materials.rs). Paths are
+relative to the owned root and parent directories must be explicit; the launcher
+does not interpret file contents or infer additional paths.
The launcher never derives ownership from HOME/CODEX_HOME/CLAUDE_CONFIG_DIR.
The launcher checks the explicit executable path and basic executability without
reading program contents or verifying pins. Installation discovery and Harness
profile rendering remain with the selection path.
-On Unix each child starts a fresh process group. Safe `waitid(NOWAIT)` observes
-without reaping the group leader; the retained leader protects group identity
-through signalling, including root-first exit. After reaping, group identifiers
-are used only for read-only absence checks, never another destructive signal.
-A stopped group does not prove no deliberately detached process exists. Windows
+On Unix each child starts a fresh process group. Stop sends TERM once, reserves a
+one-second native cleanup window, then uses KILL on that same owned group. Native
+Harnesses use this window to reclaim ordinary tools in separate process groups;
+turn cancellation alone may keep background terminals alive. Safe `waitid(NOWAIT)`
+observes without reaping the group leader; the retained leader protects group
+identity throughout both phases, including an adapter exiting before its Harness.
+A caller whose budget expires retains ownership and can continue the same stop.
+After reaping, group identifiers are used only for read-only absence checks, never
+another destructive signal. Neither the KILL fallback nor a stopped original group
+proves arbitrary detached processes are gone. Real native cancellation scenarios
+must verify actual tool side effects stop while a neighboring run continues. Windows
uses a held child only: root scope remains insufficient proof of ordinary child
chain cancellation until native Windows validation and any required mechanism.
@@ -54,3 +45,11 @@ real Harness/ACP or CLI/Desktop wiring; those remain consumer/integration checks
Cleanup keeps an open directory identity handle, verifies the current root is the
same object, and rejects symlink/reparse replacement before deleting its own root.
This avoids authorizing deletion solely from a stale path/inode number.
+
+## Representative checks
+
+[Platform scenarios](../../../tests/local_worker_platform.rs) cover process-group
+stop and cleanup ownership. The [Worker product journey](../../../../../tools/product-e2e/tests/worker_delegation.rs)
+and [read/continue journey](../../../../../tools/product-e2e/tests/worker_read.rs)
+exercise the broader consumer path. Record the actual platform and proof level;
+an OS probe cannot establish real Agent compatibility.
diff --git a/crates/daemon/src/delegation/local_worker/materials.rs b/crates/daemon/src/delegation/local_worker/materials.rs
index 86868f0d..95752896 100644
--- a/crates/daemon/src/delegation/local_worker/materials.rs
+++ b/crates/daemon/src/delegation/local_worker/materials.rs
@@ -131,7 +131,9 @@ pub(super) fn prepare(
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
- options.mode(0o600);
+ // The profile may provide a token-free native launcher. Only that explicitly
+ // declared material is executable; ordinary configuration stays private data.
+ options.mode(if file.executable { 0o700 } else { 0o600 });
}
let mut output = options
.open(owned.path.join(file.relative_path))
diff --git a/crates/daemon/src/delegation/local_worker/process.rs b/crates/daemon/src/delegation/local_worker/process.rs
index 6fa50468..4d600f2c 100644
--- a/crates/daemon/src/delegation/local_worker/process.rs
+++ b/crates/daemon/src/delegation/local_worker/process.rs
@@ -1,5 +1,7 @@
use super::super::platform::{WorkerObservation as Observation, WorkerStopScope as Scope};
use std::io;
+#[cfg(unix)]
+use std::time::{Duration, Instant};
use tokio::process::{Child, Command};
/// Never expose a numeric process identifier as an operation capability.
@@ -8,6 +10,8 @@ pub(super) struct Process {
reaped: Option<Observation>,
#[cfg(unix)]
group: rustix::process::Pid,
+ #[cfg(unix)]
+ graceful_stop_started: Option<Instant>,
stop_sent: bool,
}
@@ -30,6 +34,8 @@ impl Process {
reaped: None,
#[cfg(unix)]
group,
+ #[cfg(unix)]
+ graceful_stop_started: None,
stop_sent: false,
})
}
@@ -89,21 +95,22 @@ impl Process {
}
#[cfg(unix)]
{
- // Validate the still-owned child before any group signal. After reaping, no
- // signal ever uses this number again, even if another process reused it.
- let observation = self.observe();
- if self.reaped.is_some() || observation == Observation::Unknown {
- return Err(io::Error::other("process ownership unavailable"));
+ // Native Harnesses own tools in separate process groups. A turn interrupt
+ // may deliberately keep those tools alive; TERM lets the Harness release them.
+ // Keep the leader unreaped throughout this window even if the adapter exits
+ // first: a remaining Harness may still be draining its own child resources.
+ if self.graceful_stop_started.is_none() {
+ self.signal_group(rustix::process::Signal::TERM)?;
+ self.graceful_stop_started = Some(Instant::now());
+ return Ok(());
}
- match rustix::process::kill_process_group(self.group, rustix::process::Signal::KILL) {
- Ok(()) | Err(rustix::io::Errno::SRCH) => {}
- Err(rustix::io::Errno::PERM)
- if matches!(observation, Observation::Exited { .. }) => {}
- Err(error) => return Err(error.into()),
+ if self
+ .graceful_stop_started
+ .is_some_and(|started| started.elapsed() < Duration::from_secs(1))
+ {
+ return Ok(());
}
- // Darwin returns EPERM when only an exited/unreaped leader remains. Only
- // for an observed exit may we proceed to reap and check group absence. A
- // still-present/inaccessible group remains unknown; EPERM is never success.
+ self.signal_group(rustix::process::Signal::KILL)?;
}
#[cfg(not(unix))]
{
@@ -115,6 +122,25 @@ impl Process {
Ok(())
}
+ #[cfg(unix)]
+ fn signal_group(&mut self, signal: rustix::process::Signal) -> io::Result<()> {
+ // Validate the still-owned child before any group signal. After reaping, no
+ // signal ever uses this number again, even if another process reused it.
+ let observation = self.observe();
+ if self.reaped.is_some() || observation == Observation::Unknown {
+ return Err(io::Error::other("process ownership unavailable"));
+ }
+ match rustix::process::kill_process_group(self.group, signal) {
+ Ok(()) | Err(rustix::io::Errno::SRCH) => {}
+ Err(rustix::io::Errno::PERM) if matches!(observation, Observation::Exited { .. }) => {}
+ Err(error) => return Err(error.into()),
+ }
+ // Darwin returns EPERM when only an exited/unreaped leader remains. Only
+ // for an observed exit may we proceed to reap and check group absence. A
+ // still-present/inaccessible group remains unknown; EPERM is never success.
+ Ok(())
+ }
+
pub(super) fn stopped(&mut self) -> bool {
if !self.stop_sent {
return false;
@@ -148,5 +174,9 @@ impl Drop for Process {
fn drop(&mut self) {
// Last resort only; never reported as successful cleanup.
let _ = self.request_stop();
+ #[cfg(unix)]
+ if !self.stop_sent {
+ let _ = self.signal_group(rustix::process::Signal::KILL);
+ }
}
}
diff --git a/crates/daemon/src/delegation/profile/README.md b/crates/daemon/src/delegation/profile/README.md
new file mode 100644
index 00000000..0a04fd6c
--- /dev/null
+++ b/crates/daemon/src/delegation/profile/README.md
@@ -0,0 +1,174 @@
+# Worker native context and profile
+
+[Worker lifecycle](../local_worker/README.md) · [Worker context map](../../../../../docs/code-map/worker-context.md)
+
+The [installation source](../installation.rs) resolves the selected executable and
+builds a profile for an admitted run. [NativeWorkerContext](native_context.rs)
+reads only the effective instance `HOME` and the selected Harness's config-root
+variable. It respects isolated Pilot/test instances and never searches for another
+user's home from an executable path. The child receives a fresh explicit
+environment; preserving command search paths does not import upstream credentials.
+
+## State and ownership
+
+New tasks bind their effective home, native config root and canonical workspace
+once in the task-owned metadata directory. Continue reads that descriptor instead
+of resolving today's environment. Only Codex/Claude accept the registered legacy
+private-root path when the descriptor is absent; Qoder requires it. A damaged
+descriptor must fail rather than fall back.
+`TaskSessionRoot` still owns HiRoute metadata and the frozen Codex alias catalog.
+The borrowed native config/history tree is never a launcher material or cleanup
+target. History binding and retention belong to [materials](materials.rs) and the
+existing delegation lifecycle, not these renderers.
+
+The [profile builder](mod.rs) projects the admitted permission policy, supplies
+explicit context and temporary paths, and combines one Harness renderer with the
+validated native or adapter launch form. Tests and the older adapter-only loopback
+installation probe explicitly request isolated contexts. They never silently use
+the developer's HOME. Qoder requires the borrowed context; that older probe does
+not establish its login or execution capability.
+
+The shared validated launch form rejects Qoder adapter/Node fields and missing
+Codex/Claude adapters. Qoder discovery checks metadata for both `qoder` and
+`qodercli` names and the official standalone directory. It never runs the
+discovered CLI or replaces a missing explicit selection with another candidate.
+
+## Native launch contracts
+
+- [Codex](codex.rs) uses a task-specific provider key so a user's ordinary provider
+ table cannot accidentally contribute extra routing/auth fields through native
+ table merging. The private per-run executable launcher passes the same managed
+ settings used by `CODEX_CONFIG` as native `-c` overrides before `app-server`
+ starts. This covers the adapter's early `account/read` and model-catalog lookup.
+ Only the environment contains the run token; startup arguments and files refer
+ to its variable name. Continue reuses the task's provider key/catalog and obtains
+ a fresh launcher/token. The current launcher supports Unix; other platforms fail
+ explicitly rather than executing a POSIX script as a native program.
+- [Claude](claude.rs) loads user/project/local setting sources and exposes `Skill`
+ in the default approve-all tool set. Its selected Node runs a private
+ [adapter bootstrap](claude_adapter_bootstrap.mjs) before importing the selected
+ JavaScript adapter. The bootstrap prevents managed settings from changing or
+ deleting the host's routing, credential, context, CLI and runtime-loader
+ environment values; protected absent provider credentials stay absent too.
+ Ordinary settings variables remain available. This guard belongs only to the
+ adapter process: it does not use `NODE_OPTIONS` or install a child-process
+ preload, and it is not a sandbox for arbitrary JavaScript.
+ Native host-managed provider protection, a custom model option and explicit
+ session model maintain the selected route after the native CLI starts. Restricted
+ profiles retain their existing tool sets. `strictMcpConfig` with an empty explicit
+ MCP map suppresses ambient MCP; `disableAllHooks` suppresses user/project/plugin
+ hooks without disabling plugin skills. Native managed-policy hooks and adapter
+ callbacks remain separate. These options are not a claim that every extension
+ is available or universally disabled.
+- [Qoder](qoder.rs) starts the selected native CLI with `--acp`, explicit
+ `--config-dir` and user/project/local resource sources. It consumes the single
+ [shared Qoder renderer](../../../../integrations/src/agents/qoder.rs) for a
+ token-free per-run settings file. The task-specific provider prefix belongs
+ only to the native selected model ID; Plan, run authorization and Gateway retain
+ the raw alias. New/Load use the shared typed ACP model confirmation before prompt.
+ Default `yolo` permission applies to the explicit Read/Write/Edit/Bash/Grep/Glob/Skill
+ tool set. Native Agent and other unproven model-using tools are not enabled;
+ ApproveReads/DenyAll fail before launch rather than upgrading permission.
+ Explicit empty strict MCP configuration and disabled hooks preserve that boundary
+ without excluding user and project skills. The overlay disables native updates,
+ periodic history cleanup and plan-driven model switching, and fixes supported
+ model purposes to the frozen alias. Actual auxiliary routing needs native wire
+ evidence; the presence of these settings is not that evidence.
+
+Qoder's [budget projection](../../../../integrations/src/agents/qoder_budget.rs)
+uses the frozen Plan's existing effective context policy, including total and
+reasoning reservations, and the smallest exact output bound across all active
+candidates and protocols. The shared renderer writes both `contextWindow` and
+`maxOutputTokens` into the native provider model entry. Qoder 1.1.65 uses this
+catalogue output value for both request limits and compaction reservation; its
+ACP path does not apply the CLI `--max-output-tokens` flag as a substitute.
+Unknown, zero, unrepresentable or nonpositive effective compaction budgets fail
+before native launch. A positive threshold does not promise every skill or
+prompt fits. The independent collaboration probe uses its own synthetic 2048
+output budget without claiming a Worker Plan context. Existing Codex/Claude
+budget projections are unchanged.
+
+Read the [budget contracts](../../../../integrations/src/agents/qoder_budget_tests.rs)
+for mixed-route minima, total/reasoning reservations and exact rejection edges;
+the [Qoder profile test](tests/qoder.rs) checks the rendered New/Continue materials.
+The real Qoder core journey separately verifies 32768-context/4096-output native
+skill execution and exact Continue through the public Worker entry.
+
+Qoder retains only the task-owned context descriptor and exact native-session
+binding in HiRoute metadata. Its native history is opaque: Continue requests that
+exact ACP session ID and fails if the native client cannot load it. There is no
+Qoder private-root legacy reader, transcript scanner or shared-history deletion.
+The native client must already be logged in under the selected context; HiRoute
+does not copy authentication or inherit an ambient personal access token.
+
+Borrowed Claude supplies only the Gateway IP as `NO_PROXY` and `no_proxy` in both
+the adapter environment and the native flag settings. These two non-secret values
+bypass user-configured proxies for the local model route; other native tool proxy
+settings remain available. The bootstrap rejects conflicting managed proxy/TLS
+environment writes before ACP starts: managed policy outranks flag settings and
+the native CLI would read it again, so silently ignoring that write is insufficient.
+Compatible managed bypass values are allowed. Rejection diagnostics contain no
+setting values or credentials. This is a boundary for the local HTTP Gateway,
+not general transport management for native tools.
+
+Borrowed Claude execution requires an explicitly selected Node runtime and a
+JavaScript ACP adapter entry. An executable/shebang adapter with no saved Node
+selection can still be discovered and selected under the existing installation
+contract, but this capability fails with `CapabilityUnavailable` before starting
+the unguarded adapter. Select a Node runtime alongside that adapter in the Worker
+installation configuration. HiRoute does not guess a runtime from PATH or inspect
+the adapter's program text. Existing isolated tasks/probes retain their direct
+adapter launch behavior.
+
+At a borrowed Claude launch, the [runtime capability check](claude_runtime.rs)
+executes only the selected CLI's bounded `--version` with the selected command
+search path and no HOME, native config, or run credential. This narrowly requires
+the known Claude 2.x host-managed-provider capability (2.1.231 or later); it is not
+an installation readiness probe or a compatibility guarantee. An unsupported,
+unknown, failed or timed-out response rejects this launch before model execution.
+
+Native client effort preferences may still affect client-side behavior. They are
+not the authority for the frozen Plan's upstream reasoning settings: AgentPlan
+routing projects the frozen candidate configuration at the Gateway. This change
+does not introduce a new effort policy.
+
+Context discovery, skill discovery/invocation, model access, native session
+restoration and process startup are separate capabilities. This module does not
+add ecosystem scanning/import, general Agent launch, a new execution backend or a
+plugin framework. ACP model/session verification remains in [ACP](../acp/mod.rs),
+and the OS launcher owns executable material permissions and process cleanup.
+
+## Representative product contracts
+
+[Profile tests](tests.rs) cover token-free startup configuration, literal argument
+passing for quoted paths, preserved daily settings, task catalog/provider reuse,
+fresh run credentials, and Claude skills without widening restricted tools.
+[Context tests](native_context.rs) cover explicit native roots, Pilot HOME and
+rejection of unusable selectors. Existing isolated-root tests retain legacy
+history/material lifetime assertions.
+
+[Qoder profile tests](tests/qoder.rs) cover single-CLI launch, user/project sources,
+tool boundaries, exact selected ID, fresh credentials and token-free materials.
+[Discovery](../installation/discovery/tests.rs) and
+[availability](../installation/availability.rs) test metadata-only single-CLI
+selection without replacing an unavailable explicit choice. Native identity and
+borrowed-binding tests cover Qoder alongside the existing exact-ID contracts;
+they do not establish real login, history flush or auxiliary-model routing.
+
+Run `node --test crates/daemon/src/delegation/profile/claude_adapter_bootstrap.test.mjs`
+with the repository's Node version for the bootstrap boundary. The tests execute
+the production bootstrap with a synthetic settings-writing adapter, prove the
+unguarded regression, check child environment delivery without a propagated guard,
+reject managed transport conflicts, and verify that rejected startup diagnostics
+do not expose the runtime credential.
+
+These tests do not prove a real installed adapter discovers or invokes skills.
+Start with the [native context journey](../../../../../tools/product-e2e/tests/worker_native_context.rs)
+and its [acceptance guide](../../../../../tools/product-e2e/tests/WORKER_NATIVE_CONTEXT.md).
+The existing Worker scenarios under [product-e2e](../../../../../tools/product-e2e/tests/worker_delegation.rs)
+and [Worker read/Continue](../../../../../tools/product-e2e/tests/worker_read.rs)
+must exercise the selected installation on Linux and macOS, including two runs,
+frozen routing, exact Continue and hidden-content rejection. Native history may
+remain physically present after HiRoute hides its own content. A real Claude run
+with conflicting user proxy settings must also complete with no proxy-trap
+requests; bootstrap fixtures alone do not establish native flag-layer precedence.
diff --git a/crates/daemon/src/delegation/profile/capabilities.rs b/crates/daemon/src/delegation/profile/capabilities.rs
index d8449efb..9f20896e 100644
--- a/crates/daemon/src/delegation/profile/capabilities.rs
+++ b/crates/daemon/src/delegation/profile/capabilities.rs
@@ -3,14 +3,21 @@ use super::*;
pub(super) fn identity_contract(
input: &ProfileInput<'_>,
) -> Result<AcpNativeIdentityContract, DelegationErrorV1> {
- // Codex's advertised read-only ACP mode can still select workspaceWrite internally.
- if input.harness == WorkerHarnessV1::CodexCli
- && input.permission_policy != WorkerPermissionPolicyV1::ApproveAll
+ if input.harness == WorkerHarnessV1::QoderCli && !input.native_context.is_borrowed() {
+ return Err(DelegationErrorV1::CapabilityUnavailable);
+ }
+ // Codex's read-only ACP mode can select workspaceWrite internally. Qoder's restricted
+ // modes have no proven permission contract; neither client may silently upgrade them.
+ if matches!(
+ input.harness,
+ WorkerHarnessV1::CodexCli | WorkerHarnessV1::QoderCli
+ ) && input.permission_policy != WorkerPermissionPolicyV1::ApproveAll
{
return Err(DelegationErrorV1::CapabilityUnavailable);
}
Ok(match input.harness {
WorkerHarnessV1::CodexCli => AcpNativeIdentityContract::CodexThreadV1,
WorkerHarnessV1::ClaudeCode => AcpNativeIdentityContract::ClaudeSessionV1,
+ WorkerHarnessV1::QoderCli => AcpNativeIdentityContract::QoderSessionV1,
})
}
diff --git a/crates/daemon/src/delegation/profile/capability_tests.rs b/crates/daemon/src/delegation/profile/capability_tests.rs
index 7caf42c3..1b880e18 100644
--- a/crates/daemon/src/delegation/profile/capability_tests.rs
+++ b/crates/daemon/src/delegation/profile/capability_tests.rs
@@ -27,7 +27,7 @@ fn missing_worker_dependencies_leave_normal_gateway_publication_available() {
for harness in [WorkerHarnessV1::CodexCli, WorkerHarnessV1::ClaudeCode] {
let config = crate::delegation::installation::WorkerInstallationConfig {
harness,
- adapter: PathBuf::from("/missing-worker-adapter"),
+ adapter: Some(PathBuf::from("/missing-worker-adapter")),
harness_binary: PathBuf::from("/missing-worker-harness"),
node_binary: None,
};
diff --git a/crates/daemon/src/delegation/profile/claude.rs b/crates/daemon/src/delegation/profile/claude.rs
new file mode 100644
index 00000000..2a9188d4
--- /dev/null
+++ b/crates/daemon/src/delegation/profile/claude.rs
@@ -0,0 +1,97 @@
+//! Claude reuses native settings while the host owns the managed model route.
+use super::*;
+
+pub(super) fn render(
+ input: &ProfileInput<'_>,
+ projected_tools: &[WorkerToolV1],
+) -> Result<RenderedHarnessProfile, DelegationErrorV1> {
+ let mut rendered = RenderedHarnessProfile {
+ native_model_id: input.alias.to_owned(),
+ ..Default::default()
+ };
+ if let Some(window) = input.context_window_tokens {
+ let values = hiroute_domain::claude_context_environment(window)
+ .ok_or(DelegationErrorV1::CapabilityUnavailable)?;
+ for (key, value) in values {
+ rendered.env.insert(key, Zeroizing::new(value));
+ }
+ }
+ for (key, value) in [
+ ("CLAUDE_CODE_EXECUTABLE", path_string(input.harness_binary)?),
+ (
+ "CLAUDE_CONFIG_DIR",
+ path_string(input.native_context.config_root())?,
+ ),
+ ("CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC", "1".into()),
+ ("CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST", "1".into()),
+ ("ANTHROPIC_BASE_URL", format!("http://{}", input.gateway)),
+ ("ANTHROPIC_AUTH_TOKEN", secret_string(&input.token)?),
+ ("ANTHROPIC_MODEL", input.alias.into()),
+ ("ANTHROPIC_CUSTOM_MODEL_OPTION", input.alias.into()),
+ ] {
+ rendered.env.insert(key.into(), Zeroizing::new(value));
+ }
+ let mut tools = Vec::new();
+ for tool in projected_tools {
+ match tool {
+ WorkerToolV1::Read => tools.extend(["Read", "Glob", "Grep"]),
+ WorkerToolV1::Edit => tools.extend(["Edit", "Write"]),
+ WorkerToolV1::Shell => tools.push("Bash"),
+ }
+ }
+ if input.permission_policy == WorkerPermissionPolicyV1::ApproveAll {
+ tools.extend(["WebSearch", "WebFetch"]);
+ if input.native_context.is_borrowed() {
+ tools.push("Skill");
+ }
+ }
+ let setting_sources = if input.native_context.is_borrowed() {
+ vec!["user", "project", "local"]
+ } else {
+ vec![]
+ };
+ let mut options = json!({
+ "settingSources": setting_sources, "model": input.alias, "tools": tools,
+ "disallowedTools": ["Agent", "Task", "AskUserQuestion"],
+ "settings": {"apiKeyHelper": ""},
+ });
+ if input.native_context.is_borrowed() {
+ // The native flag layer must bypass user-configured proxies for this Gateway.
+ // Keep other proxy settings available to native tools; never put a token here.
+ let gateway_host = input.gateway.ip().to_string();
+ for key in ["NO_PROXY", "no_proxy"] {
+ rendered
+ .env
+ .insert(key.into(), Zeroizing::new(gateway_host.clone()));
+ }
+ options["settings"]["env"] = json!({
+ "NO_PROXY": gateway_host,
+ "no_proxy": gateway_host,
+ });
+ let bootstrap = PathBuf::from("claude-adapter-bootstrap.mjs");
+ rendered.files.push(RunMaterialFile {
+ relative_path: bootstrap.clone(),
+ contents: Zeroizing::new(include_bytes!("claude_adapter_bootstrap.mjs").to_vec()),
+ executable: false,
+ });
+ rendered.adapter_bootstrap = Some(bootstrap);
+ // Reusing skills does not expand this profile to ambient MCP or native user hooks.
+ // Plugin skills remain discoverable; managed-policy hooks are controlled natively.
+ options["strictMcpConfig"] = json!(true);
+ options["mcpServers"] = json!({});
+ options["settings"]["disableAllHooks"] = json!(true);
+ } else {
+ options["mcpServers"] = json!({});
+ options["plugins"] = json!([]);
+ options["hooks"] = json!({});
+ }
+ if let Some(effort) = input.native_effort {
+ options["effort"] = json!(effort);
+ }
+ // Omitted injection options do not disable native MCP, plugins or hooks. Discovery and
+ // permission behavior remain separate native capabilities, verified through real runs.
+ rendered
+ .session_meta
+ .insert("claudeCode".into(), json!({"options": options}));
+ Ok(rendered)
+}
diff --git a/crates/daemon/src/delegation/profile/claude_adapter_bootstrap.mjs b/crates/daemon/src/delegation/profile/claude_adapter_bootstrap.mjs
new file mode 100644
index 00000000..9131fa4c
--- /dev/null
+++ b/crates/daemon/src/delegation/profile/claude_adapter_bootstrap.mjs
@@ -0,0 +1,84 @@
+// This bootstrap runs only in the selected Claude ACP adapter process. It is not a
+// preload and does not propagate a JavaScript guard to the native CLI or its tools.
+import { isAbsolute } from "node:path";
+import { pathToFileURL } from "node:url";
+
+const fixedNames = new Set([
+ "HOME", "PATH", "PWD", "TMPDIR", "TMP", "TEMP",
+ "CLAUDE_CONFIG_DIR", "CLAUDE_CODE_EXECUTABLE",
+ "CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST",
+ "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC",
+ "CLAUDE_CODE_AUTO_COMPACT_WINDOW", "CLAUDE_CODE_MAX_CONTEXT_TOKENS",
+ "NODE_OPTIONS", "NODE_PATH", "BUN_OPTIONS",
+ "LD_PRELOAD", "LD_LIBRARY_PATH", "DYLD_INSERT_LIBRARIES", "DYLD_LIBRARY_PATH",
+]);
+
+const transportNames = new Set([
+ "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY",
+ "http_proxy", "https_proxy", "all_proxy", "no_proxy",
+ "NODE_EXTRA_CA_CERTS", "NODE_TLS_REJECT_UNAUTHORIZED", "NODE_USE_ENV_PROXY",
+ "NODE_USE_SYSTEM_CA", "SSL_CERT_FILE", "SSL_CERT_DIR",
+ "CURL_CA_BUNDLE", "REQUESTS_CA_BUNDLE",
+ "CLAUDE_CODE_CLIENT_CERT", "CLAUDE_CODE_CLIENT_KEY",
+ "CLAUDE_CODE_CLIENT_KEY_PASSPHRASE", "CLAUDE_CODE_CERT_STORE",
+]);
+
+class ManagedTransportConflict extends Error {}
+
+function checkTransportWrite(target, key, value) {
+ // Managed policy outranks the native flag layer and is read again by the CLI.
+ // Swallowing a conflicting adapter write would leave that later bypass intact.
+ if (transportNames.has(key) && target[key] !== value) {
+ throw new ManagedTransportConflict();
+ }
+}
+
+function hostControlled(name) {
+ return typeof name === "string" && (
+ fixedNames.has(name)
+ || transportNames.has(name)
+ || name.startsWith("ANTHROPIC_")
+ || name.startsWith("CLAUDE_CODE_USE_")
+ || name.startsWith("CLAUDE_CODE_OAUTH_")
+ || name.startsWith("CLAUDE_CODE_API_KEY")
+ );
+}
+
+// Protect absent keys too: managed settings must not introduce another credential,
+// provider backend or runtime loader. Other settings env values remain native inputs.
+const guardedEnvironment = new Proxy(process.env, {
+ set(target, key, value) {
+ if (transportNames.has(key)) checkTransportWrite(target, key, String(value));
+ return hostControlled(key) || Reflect.set(target, key, value);
+ },
+ deleteProperty(target, key) {
+ checkTransportWrite(target, key, undefined);
+ return hostControlled(key) || Reflect.deleteProperty(target, key);
+ },
+ defineProperty(target, key, descriptor) {
+ if (transportNames.has(key)) {
+ if (!("value" in descriptor)) throw new ManagedTransportConflict();
+ checkTransportWrite(target, key, String(descriptor.value));
+ }
+ return hostControlled(key) || Reflect.defineProperty(target, key, descriptor);
+ },
+});
+Object.defineProperty(process, "env", {
+ value: guardedEnvironment,
+ writable: false,
+ configurable: false,
+ enumerable: true,
+});
+
+try {
+ const adapter = process.argv[2];
+ if (!adapter || !isAbsolute(adapter)) throw new Error("invalid adapter entry");
+ process.argv = [process.argv[0], adapter, ...process.argv.slice(3)];
+ await import(pathToFileURL(adapter).href);
+} catch (error) {
+ // Never echo an adapter error, environment value, or credential in this diagnostic.
+ process.stderr.write(error instanceof ManagedTransportConflict
+ ? "HiRoute Claude managed transport settings conflict\n"
+ : "HiRoute Claude adapter bootstrap failed\n");
+ process.exitCode = 1;
+}
diff --git a/crates/daemon/src/delegation/profile/claude_adapter_bootstrap.test.mjs b/crates/daemon/src/delegation/profile/claude_adapter_bootstrap.test.mjs
new file mode 100644
index 00000000..5f307eb9
--- /dev/null
+++ b/crates/daemon/src/delegation/profile/claude_adapter_bootstrap.test.mjs
@@ -0,0 +1,164 @@
+import assert from "node:assert/strict";
+import { spawnSync } from "node:child_process";
+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { fileURLToPath } from "node:url";
+import test from "node:test";
+
+const bootstrap = fileURLToPath(new URL("./claude_adapter_bootstrap.mjs", import.meta.url));
+const runtimeCredential = "synthetic-runtime-only-value";
+
+function runAdapter(source, { guarded = true } = {}) {
+ const root = mkdtempSync(join(tmpdir(), "hiroute-claude-bootstrap-"));
+ try {
+ const adapter = join(root, "selected adapter's entry.mjs");
+ writeFileSync(adapter, source);
+ return spawnSync(process.execPath, guarded ? [bootstrap, adapter] : [adapter], {
+ encoding: "utf8",
+ timeout: 5_000,
+ env: {
+ HOME: root, PATH: "/selected/runtime:/usr/bin:/bin", TMPDIR: root,
+ CLAUDE_CONFIG_DIR: join(root, "native-context"),
+ CLAUDE_CODE_EXECUTABLE: "/selected/native-cli",
+ CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST: "1",
+ CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1",
+ ANTHROPIC_BASE_URL: "http://127.0.0.1:45678",
+ ANTHROPIC_AUTH_TOKEN: runtimeCredential,
+ ANTHROPIC_MODEL: "frozen-alias",
+ ANTHROPIC_CUSTOM_MODEL_OPTION: "frozen-alias",
+ NO_PROXY: "127.0.0.1", no_proxy: "127.0.0.1",
+ },
+ });
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+}
+
+function flags(result) {
+ assert.equal(result.status, 0, "adapter fixture must complete");
+ assert.equal(result.stderr, "", "adapter fixture must not emit diagnostics");
+ assert.ok(!result.stdout.includes(runtimeCredential), "credential must not enter output");
+ return JSON.parse(result.stdout);
+}
+
+const managedSettingsFixture = `
+import { spawnSync } from 'node:child_process';
+const controlled = Object.keys(process.env).filter(key => !['NO_PROXY', 'no_proxy'].includes(key));
+const before = Object.fromEntries(controlled.map(key => [key, process.env[key]]));
+const missing = [
+ 'ANTHROPIC_API_KEY', 'ANTHROPIC_DEFAULT_HAIKU_MODEL', 'CLAUDE_CODE_USE_BEDROCK',
+ 'CLAUDE_CODE_USE_VERTEX', 'CLAUDE_CODE_USE_FOUNDRY', 'CLAUDE_CODE_OAUTH_TOKEN',
+ 'CLAUDE_CODE_API_KEY_HELPER_TTL_MS', 'NODE_OPTIONS', 'NODE_PATH', 'LD_PRELOAD',
+];
+for (const key of [...controlled, ...missing]) {
+ process.env[key] = 'managed-replacement';
+ Object.assign(process.env, { [key]: 'assigned-replacement' });
+ delete process.env[key];
+ Object.defineProperty(process.env, key, {
+ value: 'defined-replacement', configurable: true, enumerable: true, writable: true,
+ });
+}
+process.env.SKILL_FIXTURE_SETTING = 'native-setting-kept';
+const child = spawnSync(process.execPath, ['-e', [
+ "const before = process.env.ANTHROPIC_MODEL === 'frozen-alias' && process.env.CLAUDE_CODE_EXECUTABLE === '/selected/native-cli' && process.env.CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST === '1' && !process.env.NODE_OPTIONS && !process.env.NODE_PATH",
+ "process.env.ANTHROPIC_MODEL = 'child-local-value'",
+ "process.stdout.write(JSON.stringify({before, unguarded: process.env.ANTHROPIC_MODEL === 'child-local-value'}))",
+].join(';')], { encoding: 'utf8' });
+const inherited = child.status === 0 ? JSON.parse(child.stdout) : {};
+process.stdout.write(JSON.stringify({
+ controlledPreserved: controlled.every(key => process.env[key] === before[key]),
+ absentPreserved: missing.every(key => !(key in process.env)),
+ ordinarySettingKept: process.env.SKILL_FIXTURE_SETTING === 'native-setting-kept',
+ childReceivedManagedValues: inherited.before === true,
+ guardNotPropagated: inherited.unguarded === true,
+ selectedEntryPreserved: process.argv[1].endsWith("selected adapter's entry.mjs"),
+}));
+`;
+
+test("managed settings cannot replace routing, context, selected CLI or absent provider credentials", () => {
+ const observed = flags(runAdapter(managedSettingsFixture));
+ assert.ok(Object.values(observed).every(value => value === true), "every managed boundary must hold");
+});
+
+test("the same settings fixture exposes the regression without the production bootstrap", () => {
+ const observed = flags(runAdapter(managedSettingsFixture, { guarded: false }));
+ assert.equal(observed.controlledPreserved, false);
+ assert.equal(observed.absentPreserved, false);
+ assert.equal(observed.childReceivedManagedValues, false);
+});
+
+test("replacing process.env fails before the adapter can continue and emits no credential", () => {
+ const result = runAdapter(`
+ process.env = { ...process.env, ANTHROPIC_BASE_URL: 'https://unmanaged.invalid' };
+ process.stdout.write('adapter-continued');
+ `);
+ assert.equal(result.status, 1);
+ assert.equal(result.stdout, "");
+ assert.equal(result.stderr, "HiRoute Claude adapter bootstrap failed\n");
+ assert.ok(!result.stderr.includes(runtimeCredential));
+});
+
+test("ordinary native settings remain writable and an import failure is sanitized", () => {
+ const result = runAdapter(`
+ process.env.NATIVE_SKILL_RESOURCE = 'enabled';
+ if (process.env.NATIVE_SKILL_RESOURCE !== 'enabled') throw new Error('setting missing');
+ throw new Error(process.env.ANTHROPIC_AUTH_TOKEN);
+ `);
+ assert.equal(result.status, 1);
+ assert.equal(result.stdout, "");
+ assert.equal(result.stderr, "HiRoute Claude adapter bootstrap failed\n");
+ assert.ok(!result.stderr.includes(runtimeCredential));
+});
+
+function assertTransportConflict(result) {
+ assert.equal(result.status, 1, "a managed transport conflict must reject startup");
+ assert.equal(result.stdout, "", "a conflicting adapter must not continue");
+ assert.equal(result.stderr, "HiRoute Claude managed transport settings conflict\n");
+ assert.ok(!result.stderr.includes(runtimeCredential));
+}
+
+test("managed proxy and TLS injections fail before the native CLI can reread policy", () => {
+ for (const key of [
+ "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY",
+ "http_proxy", "https_proxy", "all_proxy", "no_proxy",
+ "NODE_EXTRA_CA_CERTS", "NODE_TLS_REJECT_UNAUTHORIZED", "NODE_USE_ENV_PROXY",
+ "NODE_USE_SYSTEM_CA", "SSL_CERT_FILE", "SSL_CERT_DIR",
+ "CURL_CA_BUNDLE", "REQUESTS_CA_BUNDLE",
+ "CLAUDE_CODE_CLIENT_CERT", "CLAUDE_CODE_CLIENT_KEY",
+ "CLAUDE_CODE_CLIENT_KEY_PASSPHRASE", "CLAUDE_CODE_CERT_STORE",
+ ]) {
+ assertTransportConflict(runAdapter(`
+ process.env[${JSON.stringify(key)}] = process.env.ANTHROPIC_AUTH_TOKEN;
+ process.stdout.write('adapter-continued');
+ `));
+ }
+});
+
+test("managed transport cannot delete, assign or redefine the Gateway proxy bypass", () => {
+ for (const mutation of [
+ "delete process.env.NO_PROXY",
+ "Object.assign(process.env, { no_proxy: 'unmanaged.invalid' })",
+ "Object.defineProperty(process.env, 'NO_PROXY', { value: 'unmanaged.invalid', configurable: true, enumerable: true, writable: true })",
+ "Object.defineProperty(process.env, 'NO_PROXY', { get() { return 'unmanaged.invalid'; }, configurable: true })",
+ ]) {
+ assertTransportConflict(runAdapter(`${mutation}; process.stdout.write('adapter-continued');`));
+ }
+});
+
+test("compatible managed bypass values reach the native child without a propagated guard", () => {
+ const result = runAdapter(`
+ import { spawnSync } from 'node:child_process';
+ process.env.NO_PROXY = '127.0.0.1';
+ Object.assign(process.env, { no_proxy: '127.0.0.1' });
+ delete process.env.HTTP_PROXY;
+ const child = spawnSync(process.execPath, ['-e', [
+ "const bypass = process.env.NO_PROXY === '127.0.0.1' && process.env.no_proxy === '127.0.0.1'",
+ "process.env.HTTP_PROXY = 'http://native-tool-proxy.invalid'",
+ "process.stdout.write(JSON.stringify({bypass, toolProxyWritable: process.env.HTTP_PROXY === 'http://native-tool-proxy.invalid'}))",
+ ].join(';')], { encoding: 'utf8' });
+ if (child.status !== 0) throw new Error('child failed');
+ process.stdout.write(child.stdout);
+ `);
+ assert.deepEqual(flags(result), { bypass: true, toolProxyWritable: true });
+});
diff --git a/crates/daemon/src/delegation/profile/claude_runtime.rs b/crates/daemon/src/delegation/profile/claude_runtime.rs
new file mode 100644
index 00000000..641ff752
--- /dev/null
+++ b/crates/daemon/src/delegation/profile/claude_runtime.rs
@@ -0,0 +1,239 @@
+//! Admission for borrowing Claude settings requires the native host-managed provider flag.
+//! Older CLIs silently ignore that flag, so ACP success cannot prove routing ownership.
+//! This metadata check is only for a selected borrowed Worker launch, never discovery/probing.
+use hiroute_domain::delegation::DelegationErrorV1;
+use std::path::Path;
+use std::time::Duration;
+
+const VERSION_TIMEOUT: Duration = Duration::from_secs(2);
+#[cfg(unix)]
+const OUTPUT_LIMIT: usize = 4096;
+
+pub(super) fn require_host_managed_provider(
+ binary: &Path,
+ search_path: &str,
+) -> Result<(), DelegationErrorV1> {
+ require_version(binary, search_path, VERSION_TIMEOUT)
+}
+
+fn require_version(
+ binary: &Path,
+ search_path: &str,
+ timeout: Duration,
+) -> Result<(), DelegationErrorV1> {
+ let output = bounded_version(binary, search_path, timeout)?;
+ if supports_host_managed_provider(&output) {
+ Ok(())
+ } else {
+ Err(DelegationErrorV1::CapabilityUnavailable)
+ }
+}
+
+fn supports_host_managed_provider(output: &[u8]) -> bool {
+ let Some(version) = std::str::from_utf8(output)
+ .ok()
+ .and_then(|text| text.trim().strip_suffix(" (Claude Code)"))
+ else {
+ return false;
+ };
+ let version = version.strip_prefix("claude ").unwrap_or(version);
+ let mut parts = version.split('.');
+ let mut number = || {
+ let part = parts.next()?;
+ if part.is_empty()
+ || !part.bytes().all(|byte| byte.is_ascii_digit())
+ || (part.len() > 1 && part.starts_with('0'))
+ {
+ return None;
+ }
+ part.parse::<u32>().ok()
+ };
+ let Some((major, minor, patch)) = number()
+ .zip(number())
+ .zip(number())
+ .map(|((major, minor), patch)| (major, minor, patch))
+ else {
+ return false;
+ };
+ parts.next().is_none() && major == 2 && (minor, patch) >= (1, 231)
+}
+
+#[cfg(unix)]
+fn bounded_version(
+ binary: &Path,
+ search_path: &str,
+ timeout: Duration,
+) -> Result<Vec<u8>, DelegationErrorV1> {
+ use nix::fcntl::{FcntlArg, OFlag, fcntl};
+ use std::io::Read;
+ use std::os::unix::process::CommandExt;
+ use std::process::{Command, Stdio};
+ use std::time::Instant;
+
+ if !binary.is_absolute() || search_path.is_empty() {
+ return Err(DelegationErrorV1::CapabilityUnavailable);
+ }
+ let started = Instant::now();
+ let mut command = Command::new(binary);
+ command
+ .arg("--version")
+ .env_clear()
+ .env("PATH", search_path)
+ .stdin(Stdio::null())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::null())
+ .process_group(0);
+ let child = spawn_version_command(|| command.spawn(), started, timeout)?;
+ let mut child = VersionChild {
+ child,
+ signals_closed: false,
+ };
+ let result = (|| {
+ let mut stdout = child
+ .child
+ .stdout
+ .take()
+ .ok_or(DelegationErrorV1::CapabilityUnavailable)?;
+ let flags = fcntl(&stdout, FcntlArg::F_GETFL)
+ .map_err(|_| DelegationErrorV1::CapabilityUnavailable)?;
+ fcntl(
+ &stdout,
+ FcntlArg::F_SETFL(OFlag::from_bits_retain(flags) | OFlag::O_NONBLOCK),
+ )
+ .map_err(|_| DelegationErrorV1::CapabilityUnavailable)?;
+ let mut output = Vec::new();
+ let mut buffer = [0; 1024];
+ loop {
+ if started.elapsed() >= timeout {
+ return Err(DelegationErrorV1::CapabilityUnavailable);
+ }
+ // Observe exit without reaping: the leader must reserve its PID/PGID
+ // until cleanup has stopped the group, including surviving descendants.
+ let status = observe_version_child(&child)?;
+ loop {
+ if started.elapsed() >= timeout {
+ return Err(DelegationErrorV1::CapabilityUnavailable);
+ }
+ match stdout.read(&mut buffer) {
+ Ok(0) => break,
+ Ok(count) => {
+ if output.len() + count > OUTPUT_LIMIT {
+ return Err(DelegationErrorV1::CapabilityUnavailable);
+ }
+ output.extend_from_slice(&buffer[..count]);
+ }
+ Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => break,
+ Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue,
+ Err(_) => return Err(DelegationErrorV1::CapabilityUnavailable),
+ }
+ }
+ if let Some(success) = status {
+ return if success {
+ Ok(output)
+ } else {
+ Err(DelegationErrorV1::CapabilityUnavailable)
+ };
+ }
+ std::thread::sleep(Duration::from_millis(5));
+ }
+ })();
+ stop_version_child(&mut child)?;
+ result
+}
+
+#[cfg(unix)]
+fn spawn_version_command(
+ mut launch: impl FnMut() -> std::io::Result<std::process::Child>,
+ started: std::time::Instant,
+ timeout: Duration,
+) -> Result<std::process::Child, DelegationErrorV1> {
+ // ETXTBSY means exec did not begin: an installer or concurrent fork may still
+ // hold a writer for the selected executable. Match the native discovery probe's
+ // bounded launch retry, without retrying a running CLI or an Agent task.
+ let retry_budget = timeout.min(Duration::from_millis(100));
+ loop {
+ if started.elapsed() >= timeout {
+ return Err(DelegationErrorV1::CapabilityUnavailable);
+ }
+ match launch() {
+ Ok(child) => return Ok(child),
+ Err(error) if error.raw_os_error() == Some(nix::errno::Errno::ETXTBSY as i32) => {
+ let remaining = retry_budget.saturating_sub(started.elapsed());
+ if remaining.is_zero() {
+ return Err(DelegationErrorV1::CapabilityUnavailable);
+ }
+ std::thread::sleep(remaining.min(Duration::from_millis(5)));
+ if started.elapsed() >= retry_budget {
+ return Err(DelegationErrorV1::CapabilityUnavailable);
+ }
+ }
+ Err(_) => return Err(DelegationErrorV1::CapabilityUnavailable),
+ }
+ }
+}
+
+#[cfg(unix)]
+struct VersionChild {
+ child: std::process::Child,
+ signals_closed: bool,
+}
+
+#[cfg(unix)]
+fn observe_version_child(child: &VersionChild) -> Result<Option<bool>, DelegationErrorV1> {
+ use rustix::process::{Pid, WaitId, WaitIdOptions, waitid};
+
+ if child.signals_closed {
+ return Err(DelegationErrorV1::CapabilityUnavailable);
+ }
+ waitid(
+ WaitId::Pid(Pid::from_child(&child.child)),
+ WaitIdOptions::EXITED | WaitIdOptions::NOHANG | WaitIdOptions::NOWAIT,
+ )
+ .map(|status| status.map(|status| status.exit_status() == Some(0)))
+ .map_err(|_| DelegationErrorV1::CapabilityUnavailable)
+}
+
+#[cfg(unix)]
+fn stop_version_child(child: &mut VersionChild) -> Result<(), DelegationErrorV1> {
+ use rustix::io::Errno;
+ use rustix::process::{Pid, Signal, kill_process_group, test_kill_process_group};
+
+ // Validate ownership immediately before signalling. WNOWAIT keeps even an exited
+ // leader reserved, so the group number cannot belong to an unrelated new process.
+ // An already reaped/unknown child fails here, without any numeric PID operation.
+ let exited = observe_version_child(child)?.is_some();
+ let group = Pid::from_child(&child.child);
+ let group_stop = kill_process_group(group, Signal::KILL);
+ if !exited && child.child.kill().is_err() && observe_version_child(child)?.is_none() {
+ return Err(DelegationErrorV1::CapabilityUnavailable);
+ }
+ child.signals_closed = true;
+ child
+ .child
+ .wait()
+ .map_err(|_| DelegationErrorV1::CapabilityUnavailable)?;
+ // No mutating PID operation is allowed after wait. Darwin can report EPERM for
+ // a group containing only its exited leader; verify absence read-only after reap.
+ match group_stop {
+ Ok(()) | Err(Errno::SRCH) => Ok(()),
+ Err(Errno::PERM)
+ if exited && matches!(test_kill_process_group(group), Err(Errno::SRCH)) =>
+ {
+ Ok(())
+ }
+ Err(_) => Err(DelegationErrorV1::CapabilityUnavailable),
+ }
+}
+
+#[cfg(not(unix))]
+fn bounded_version(
+ _binary: &Path,
+ _search_path: &str,
+ _timeout: Duration,
+) -> Result<Vec<u8>, DelegationErrorV1> {
+ Err(DelegationErrorV1::CapabilityUnavailable)
+}
+
+#[cfg(test)]
+#[path = "claude_runtime_tests.rs"]
+mod tests;
diff --git a/crates/daemon/src/delegation/profile/claude_runtime_tests.rs b/crates/daemon/src/delegation/profile/claude_runtime_tests.rs
new file mode 100644
index 00000000..f3c628bc
--- /dev/null
+++ b/crates/daemon/src/delegation/profile/claude_runtime_tests.rs
@@ -0,0 +1,230 @@
+use super::*;
+
+#[test]
+fn only_known_claude_release_format_and_supported_major_can_borrow_provider_settings() {
+ for version in [
+ "2.1.231 (Claude Code)\n",
+ "claude 2.1.232 (Claude Code)\n",
+ "2.2.0 (Claude Code)",
+ ] {
+ assert!(
+ supports_host_managed_provider(version.as_bytes()),
+ "{version}"
+ );
+ }
+ for version in [
+ "2.1.230 (Claude Code)",
+ "2.0.999 (Claude Code)",
+ "1.9.999 (Claude Code)",
+ "3.0.0 (Claude Code)",
+ "2.1.231",
+ "unknown 2.1.231 (Claude Code)",
+ "2.1.231-beta (Claude Code)",
+ "2.1.231+local (Claude Code)",
+ "2.01.231 (Claude Code)",
+ "2.1.231.1 (Claude Code)",
+ "2.1.999999999999999999999 (Claude Code)",
+ "2.1.231 (Claude Code)\nwarning: partial startup",
+ "",
+ ] {
+ assert!(
+ !supports_host_managed_provider(version.as_bytes()),
+ "{version}"
+ );
+ }
+ assert!(!supports_host_managed_provider(&[255]));
+}
+
+#[cfg(unix)]
+mod process {
+ use super::*;
+ use std::os::unix::fs::PermissionsExt;
+ use std::path::PathBuf;
+ use std::process::Command;
+ use std::time::Instant;
+
+ fn executable(root: &Path, body: &str) -> PathBuf {
+ let path = root.join("selected-claude");
+ std::fs::write(&path, format!("#!/bin/sh\n{body}\n")).unwrap();
+ std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o700)).unwrap();
+ path
+ }
+
+ #[test]
+ fn selected_cli_runs_only_version_without_inherited_context_or_secrets() {
+ let root = tempfile::tempdir().unwrap();
+ let binary = executable(
+ root.path(),
+ r#"test "$#" -eq 1 && test "$1" = '--version' || exit 2
+test -z "$HOME$CODEX_HOME$CLAUDE_CONFIG_DIR$ANTHROPIC_AUTH_TOKEN$HIROUTE_RUN_TOKEN" || exit 3
+test "$PATH" = '/selected/node:/usr/bin:/bin' || exit 4
+printf '2.1.231 (Claude Code)\n'"#,
+ );
+ assert_eq!(
+ require_host_managed_provider(&binary, "/selected/node:/usr/bin:/bin"),
+ Ok(())
+ );
+ }
+
+ #[test]
+ fn old_failed_missing_or_oversized_cli_metadata_cannot_authorize_borrowing() {
+ for body in [
+ "printf '2.1.230 (Claude Code)\\n'",
+ "printf '2.1.231 (Claude Code)\\n'; exit 7",
+ "printf '2.1.231 (Claude Code)\\n' >&2",
+ "while :; do printf 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'; done",
+ ] {
+ let root = tempfile::tempdir().unwrap();
+ let binary = executable(root.path(), body);
+ assert_eq!(
+ require_host_managed_provider(&binary, "/usr/bin:/bin"),
+ Err(DelegationErrorV1::CapabilityUnavailable)
+ );
+ }
+ let root = tempfile::tempdir().unwrap();
+ assert_eq!(
+ require_host_managed_provider(&root.path().join("missing"), "/usr/bin:/bin"),
+ Err(DelegationErrorV1::CapabilityUnavailable)
+ );
+ }
+
+ #[test]
+ #[cfg(target_os = "linux")]
+ fn transient_executable_writer_retries_metadata_without_executing_it_twice() {
+ use std::process::Stdio;
+
+ let root = tempfile::tempdir().unwrap();
+ let binary = executable(
+ root.path(),
+ r#"printf 'launched\n' >> "$0.started"
+printf '2.1.231 (Claude Code)\n'"#,
+ );
+ let mut writer = Some(
+ std::fs::OpenOptions::new()
+ .write(true)
+ .open(&binary)
+ .unwrap(),
+ );
+ let mut command = Command::new(&binary);
+ command.arg("--version").stdout(Stdio::piped());
+ let mut attempts = 0;
+ let mut first_error = None;
+ let child = spawn_version_command(
+ || {
+ attempts += 1;
+ let result = command.spawn();
+ if attempts == 1 {
+ first_error = result.as_ref().err().and_then(|error| error.raw_os_error());
+ // Release after a real kernel ETXTBSY, with no timer/thread race.
+ drop(writer.take());
+ }
+ result
+ },
+ Instant::now(),
+ Duration::from_secs(1),
+ )
+ .unwrap();
+ let output = child.wait_with_output().unwrap();
+ assert_eq!(first_error, Some(nix::errno::Errno::ETXTBSY as i32));
+ assert!(attempts >= 2);
+ assert!(output.status.success());
+ assert!(supports_host_managed_provider(&output.stdout));
+ assert_eq!(
+ std::fs::read_to_string(root.path().join("selected-claude.started")).unwrap(),
+ "launched\n"
+ );
+ }
+
+ #[test]
+ #[cfg(target_os = "linux")]
+ fn persistent_executable_writer_stays_bounded_and_never_runs_metadata() {
+ let root = tempfile::tempdir().unwrap();
+ let binary = executable(
+ root.path(),
+ r#"printf 'launched\n' > "$0.started"
+printf '2.1.231 (Claude Code)\n'"#,
+ );
+ let writer = std::fs::OpenOptions::new()
+ .write(true)
+ .open(&binary)
+ .unwrap();
+ let started = Instant::now();
+ assert_eq!(
+ require_version(&binary, "/usr/bin:/bin", Duration::from_secs(1)),
+ Err(DelegationErrorV1::CapabilityUnavailable)
+ );
+ assert!(started.elapsed() < Duration::from_secs(1));
+ assert!(!root.path().join("selected-claude.started").exists());
+ drop(writer);
+ }
+
+ #[test]
+ fn timeout_stops_owned_descendants_without_stopping_unrelated_processes() {
+ let root = tempfile::tempdir().unwrap();
+ let binary = executable(
+ root.path(),
+ r#"(printf 'started' > "$0.child-started"; sleep 0.8; printf 'survived' > "$0.child-survived") &
+wait"#,
+ );
+ let mut unrelated = Command::new("/bin/sleep").arg("10").spawn().unwrap();
+ let started = Instant::now();
+ let result = require_version(&binary, "/usr/bin:/bin", Duration::from_millis(300));
+ let elapsed = started.elapsed();
+ let unrelated_running = unrelated.try_wait().unwrap().is_none();
+ let _ = unrelated.kill();
+ let _ = unrelated.wait();
+ std::thread::sleep(Duration::from_millis(1000));
+ assert_eq!(result, Err(DelegationErrorV1::CapabilityUnavailable));
+ assert!(elapsed < Duration::from_secs(2));
+ assert!(unrelated_running);
+ assert!(root.path().join("selected-claude.child-started").exists());
+ assert!(!root.path().join("selected-claude.child-survived").exists());
+ }
+
+ #[test]
+ fn exit_observation_keeps_the_child_owned_until_group_cleanup() {
+ use std::os::unix::process::CommandExt;
+
+ let root = tempfile::tempdir().unwrap();
+ let binary = executable(root.path(), "exit 0");
+ let mut child = VersionChild {
+ child: Command::new(binary).process_group(0).spawn().unwrap(),
+ signals_closed: false,
+ };
+ let started = Instant::now();
+ while observe_version_child(&child).unwrap().is_none() {
+ assert!(started.elapsed() < Duration::from_secs(2));
+ std::thread::sleep(Duration::from_millis(5));
+ }
+ // A destructive wait would lose child ownership here. Repeat the OS observation
+ // before cleanup to prove the exited leader still reserves its PID and PGID.
+ assert_eq!(observe_version_child(&child), Ok(Some(true)));
+ assert_eq!(stop_version_child(&mut child), Ok(()));
+ assert!(child.child.try_wait().unwrap().unwrap().success());
+ // The already-reaped handle must not authorize any subsequent group signal.
+ assert_eq!(
+ stop_version_child(&mut child),
+ Err(DelegationErrorV1::CapabilityUnavailable)
+ );
+ }
+
+ #[test]
+ fn successful_leader_exit_still_stops_descendants_holding_stdout() {
+ let root = tempfile::tempdir().unwrap();
+ let binary = executable(
+ root.path(),
+ r#"(printf 'started' > "$0.child-started"; sleep 0.8; printf 'survived' > "$0.child-survived") &
+while test ! -f "$0.child-started"; do sleep 0.01; done
+printf '2.1.231 (Claude Code)\n'
+exit 0"#,
+ );
+ let started = Instant::now();
+ let result = require_version(&binary, "/usr/bin:/bin", Duration::from_secs(2));
+ let elapsed = started.elapsed();
+ std::thread::sleep(Duration::from_millis(1000));
+ assert_eq!(result, Ok(()));
+ assert!(elapsed < Duration::from_secs(2));
+ assert!(root.path().join("selected-claude.child-started").exists());
+ assert!(!root.path().join("selected-claude.child-survived").exists());
+ }
+}
diff --git a/crates/daemon/src/delegation/profile/codex.rs b/crates/daemon/src/delegation/profile/codex.rs
new file mode 100644
index 00000000..c32bf95a
--- /dev/null
+++ b/crates/daemon/src/delegation/profile/codex.rs
@@ -0,0 +1,150 @@
+//! Codex startup and session overrides come from the same managed configuration.
+use super::*;
+use hiroute_domain::CanonicalDigest;
+
+pub(super) fn render(
+ input: &ProfileInput<'_>,
+ tools: &[WorkerToolV1],
+ network: WorkerNetworkV1,
+ native_session_mode: &str,
+) -> Result<RenderedHarnessProfile, DelegationErrorV1> {
+ let catalog_path = input
+ .codex_catalog
+ .map(|catalog| {
+ input
+ .session_root
+ .prepare_codex_catalog(input.alias, catalog)
+ })
+ .transpose()?;
+ let borrowed = input.native_context.is_borrowed();
+ if borrowed && catalog_path.is_none() {
+ return Err(DelegationErrorV1::CapabilityUnavailable);
+ }
+ let provider = if borrowed {
+ let digest = CanonicalDigest::of(&(
+ "hiroute-worker-provider-v1",
+ path_string(input.session_root.path())?,
+ ))
+ .map_err(|_| DelegationErrorV1::InvalidArguments)?;
+ format!(
+ "hiroute_worker_{}",
+ digest.as_str().trim_start_matches("sha256:")
+ )
+ } else {
+ input
+ .session_root
+ .prepare_codex_provider(input.gateway, catalog_path.as_deref())?;
+ "hiroute".into()
+ };
+ let (approval_policy, sandbox_mode) = match input.permission_policy {
+ WorkerPermissionPolicyV1::ApproveAll => ("never", "danger-full-access"),
+ WorkerPermissionPolicyV1::ApproveReads | WorkerPermissionPolicyV1::DenyAll => {
+ ("on-request", "read-only")
+ }
+ };
+ let mut config = json!({
+ "model": input.alias,
+ "model_provider": provider,
+ "approval_policy": approval_policy,
+ "sandbox_mode": sandbox_mode,
+ "model_providers": {&provider: {
+ "name": "HiRoute managed run",
+ "base_url": format!("http://{}/v1", input.gateway),
+ "wire_api": "responses", "supports_websockets": false,
+ "env_key": "HIROUTE_RUN_TOKEN", "requires_openai_auth": false
+ }},
+ "features": {"multi_agent": false, "shell_tool": tools.contains(&WorkerToolV1::Shell)},
+ "web_search": if network == WorkerNetworkV1::Allowed { "live" } else { "disabled" },
+ "sandbox_workspace_write": {"network_access": network == WorkerNetworkV1::Allowed},
+ });
+ if let Some(effort) = input.native_effort {
+ config["model_reasoning_effort"] = json!(effort);
+ }
+ if let Some(path) = catalog_path {
+ config["model_catalog_json"] = json!(path_string(&path)?);
+ }
+ let mut rendered = RenderedHarnessProfile {
+ native_model_id: input.alias.to_owned(),
+ ..Default::default()
+ };
+ let codex_path = if borrowed {
+ // codex-acp starts CODEX_PATH with only `app-server`. Session CODEX_CONFIG is
+ // applied after account/read, so the launcher must install these flags first.
+ if !cfg!(unix) {
+ return Err(DelegationErrorV1::CapabilityUnavailable);
+ }
+ let relative_path = PathBuf::from("codex-worker-launcher");
+ rendered.files.push(RunMaterialFile {
+ relative_path: relative_path.clone(),
+ contents: Zeroizing::new(render_launcher(input.harness_binary, &config)?.into_bytes()),
+ executable: true,
+ });
+ input.private_root.join(relative_path)
+ } else {
+ input.harness_binary.to_owned()
+ };
+ for (key, value) in [
+ ("CODEX_CONFIG", config.to_string()),
+ ("INITIAL_AGENT_MODE", native_session_mode.into()),
+ ("MODEL_PROVIDER", provider),
+ ("CODEX_PATH", path_string(&codex_path)?),
+ (
+ "CODEX_HOME",
+ path_string(input.native_context.config_root())?,
+ ),
+ ("HIROUTE_RUN_TOKEN", secret_string(&input.token)?),
+ ] {
+ rendered.env.insert(key.into(), Zeroizing::new(value));
+ }
+ Ok(rendered)
+}
+
+pub(super) fn render_launcher(binary: &Path, config: &Value) -> Result<String, DelegationErrorV1> {
+ let mut overrides = Vec::new();
+ collect_overrides("", config, &mut overrides)?;
+ let mut script = format!("#!/bin/sh\nexec {}", shell_quote(&path_string(binary)?));
+ for value in overrides {
+ script.push_str(&format!(" \\\n -c {}", shell_quote(&value)));
+ }
+ script.push_str(" \\\n \"$@\"\n");
+ Ok(script)
+}
+
+/// The managed object contains only nested tables and scalar strings/bools/numbers.
+/// Flatten it into native dotted TOML overrides without reading or rewriting user config.
+fn collect_overrides(
+ prefix: &str,
+ value: &Value,
+ output: &mut Vec<String>,
+) -> Result<(), DelegationErrorV1> {
+ match value {
+ Value::Object(table) => {
+ for (key, value) in table {
+ // Native CLI override keys split on dots; they are not TOML key syntax.
+ // All managed keys, including the generated provider name, use this alphabet.
+ if key.is_empty()
+ || !key
+ .bytes()
+ .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_')
+ {
+ return Err(DelegationErrorV1::InvalidArguments);
+ }
+ let path = if prefix.is_empty() {
+ key.clone()
+ } else {
+ format!("{prefix}.{key}")
+ };
+ collect_overrides(&path, value, output)?;
+ }
+ }
+ Value::String(_) | Value::Bool(_) | Value::Number(_) if !prefix.is_empty() => {
+ output.push(format!("{prefix}={value}"));
+ }
+ _ => return Err(DelegationErrorV1::InvalidArguments),
+ }
+ Ok(())
+}
+
+fn shell_quote(value: &str) -> String {
+ format!("'{}'", value.replace('\'', "'\"'\"'"))
+}
diff --git a/crates/daemon/src/delegation/profile/materials.rs b/crates/daemon/src/delegation/profile/materials.rs
index 67f0ac16..5327c881 100644
--- a/crates/daemon/src/delegation/profile/materials.rs
+++ b/crates/daemon/src/delegation/profile/materials.rs
@@ -1,4 +1,4 @@
-//! Explicit run materials and a task-owned native storage reference. No launcher cleanup here.
+//! Explicit run materials and task-owned metadata. Borrowed native roots are never owned here.
use super::*;
use hiroute_domain::delegation::{
DELEGATION_NATIVE_ROOT_MARKER_FILE_V1, DelegationNativeFilesystemIdentityV1,
@@ -8,6 +8,10 @@ use hiroute_domain::{CanonicalDigest, WorkspaceId};
use std::fs;
use std::path::Component;
+#[path = "native_history.rs"]
+mod history;
+pub use history::BorrowedNativeContext;
+
/// Paths relative to a NEW private_root. The launcher creates/protects only this collection
/// and its root. It must reject existing roots, traversal, links and unknown ownership.
/// Do not derive additional directories or cleanup targets by inspecting env/session_meta.
@@ -16,10 +20,12 @@ pub struct RunMaterials {
pub files: Vec<RunMaterialFile>,
}
-/// Already rendered by 20; no template substitutions, executable permissions or secret logs.
+/// Already rendered by 20; the launcher applies 0700 to executables and 0600 to other files.
+/// No template substitutions or secret logs are allowed during materialization.
pub struct RunMaterialFile {
pub relative_path: PathBuf,
pub contents: Zeroizing<Vec<u8>>,
+ pub executable: bool,
}
/// Prepared by 20, never created or removed by 18. No run token is stored by this helper.
@@ -28,6 +34,7 @@ pub struct TaskSessionRoot {
path: PathBuf,
harness: WorkerHarnessV1,
workspace_root_identity: String,
+ newly_created: bool,
}
pub enum SessionRootUse<'a> {
@@ -65,6 +72,7 @@ impl TaskSessionRoot {
]))
.map_err(|_| DelegationErrorV1::InvalidArguments)?;
let path = base.join(digest.as_str().trim_start_matches("sha256:"));
+ let newly_created = matches!(usage, SessionRootUse::New);
match usage {
SessionRootUse::New => {
let mut builder = fs::DirBuilder::new();
@@ -86,6 +94,7 @@ impl TaskSessionRoot {
for relative in required_history {
check_history(&path, relative)?;
}
+ history::verify_continuation_materials(&path, harness, required_history)?;
}
}
let actual = checked_directory(&path)?;
@@ -96,6 +105,7 @@ impl TaskSessionRoot {
path: actual,
harness,
workspace_root_identity: workspace_root_identity.to_owned(),
+ newly_created,
})
}
@@ -349,14 +359,30 @@ impl TaskSessionRoot {
}
}
-/// Resolve the one adapter-owned append-only transcript for an exact native session. The
-/// relative result is suitable both for continuation retention and for the lifecycle's bounded
-/// post-turn flush observation; neither caller may infer a path from an unverified identifier.
+/// Retain exact continuation evidence beneath the task-owned root. Borrowed clients retain an
+/// immutable session binding, not a claim that their external history is HiRoute-owned. Claude
+/// additionally requires its precise transcript; Codex session/load checks native availability.
pub(crate) fn native_history(
root: &Path,
harness: WorkerHarnessV1,
native_session_id: &str,
) -> Result<Vec<String>, DelegationErrorV1> {
+ if history::read_context(root, harness)?.is_some() {
+ return history::retain_borrowed_session(root, harness, native_session_id);
+ }
+ legacy_native_history(root, harness, native_session_id)
+}
+
+/// Registered recovery reader for pre-native-context tasks with private native storage.
+fn legacy_native_history(
+ root: &Path,
+ harness: WorkerHarnessV1,
+ native_session_id: &str,
+) -> Result<Vec<String>, DelegationErrorV1> {
+ // Qoder has only the borrowed-context contract, never a private legacy reader.
+ if harness == WorkerHarnessV1::QoderCli {
+ return Err(DelegationErrorV1::ResumeUnavailable);
+ }
if native_session_id.is_empty()
|| native_session_id.len() > 256
|| native_session_id
@@ -380,6 +406,7 @@ pub(crate) fn native_history(
let durable_root = root.join(match harness {
WorkerHarnessV1::CodexCli => "sessions",
WorkerHarnessV1::ClaudeCode => "projects",
+ WorkerHarnessV1::QoderCli => return Err(DelegationErrorV1::ResumeUnavailable),
});
let metadata =
fs::symlink_metadata(&durable_root).map_err(|_| DelegationErrorV1::ResumeUnavailable)?;
@@ -420,6 +447,7 @@ pub(crate) fn native_history(
let matches_session = match harness {
WorkerHarnessV1::CodexCli => file_name.ends_with(&codex_suffix),
WorkerHarnessV1::ClaudeCode => file_name == claude_name,
+ WorkerHarnessV1::QoderCli => return Err(DelegationErrorV1::ResumeUnavailable),
};
if !matches_session {
continue;
diff --git a/crates/daemon/src/delegation/profile/mod.rs b/crates/daemon/src/delegation/profile/mod.rs
index 075d41af..ebfbe1a3 100644
--- a/crates/daemon/src/delegation/profile/mod.rs
+++ b/crates/daemon/src/delegation/profile/mod.rs
@@ -3,8 +3,9 @@
use super::acp::AcpNativeIdentityContract;
use hiroute_domain::ProtectedSecret;
use hiroute_domain::delegation::{
- DelegationErrorV1, WorkerExecutionIntentV1, WorkerHarnessV1, WorkerNetworkV1,
- WorkerPermissionPolicyV1, WorkerToolV1, WorkspaceAccessV1, WorkspaceExecutionPermitV1,
+ DelegationErrorV1, WorkerExecutionIntentV1, WorkerHarnessV1, WorkerLaunchFormV1,
+ WorkerNetworkV1, WorkerPermissionPolicyV1, WorkerToolV1, WorkspaceAccessV1,
+ WorkspaceExecutionPermitV1,
};
use serde_json::{Map, Value, json};
use std::collections::BTreeMap;
@@ -13,22 +14,33 @@ use std::path::{Path, PathBuf};
use zeroize::Zeroizing;
mod capabilities;
+mod claude;
+mod claude_runtime;
+mod codex;
+mod native_context;
+mod qoder;
+pub use native_context::NativeWorkerContext;
mod materials;
pub(crate) use materials::native_history;
-pub use materials::{RunMaterialFile, RunMaterials, SessionRootUse, TaskSessionRoot};
+pub use materials::{
+ BorrowedNativeContext, RunMaterialFile, RunMaterials, SessionRootUse, TaskSessionRoot,
+};
pub struct ProfileInput<'a> {
- pub claude_context_window: Option<u64>,
+ pub context_window_tokens: Option<u64>,
+ /// Qoder's frozen catalogue output upper bound; other Harness renderers are unchanged.
+ pub max_output_tokens: Option<u64>,
pub harness: WorkerHarnessV1,
- pub adapter: &'a Path,
+ pub adapter: Option<&'a Path>,
pub harness_binary: &'a Path,
pub node_binary: Option<&'a Path>,
pub private_root: &'a Path,
pub session_root: &'a TaskSessionRoot,
+ pub native_context: &'a NativeWorkerContext,
pub workspace: &'a Path,
pub alias: &'a str,
- /// One alias entry derived from the exact frozen Plan for this private Codex target.
+ /// One alias entry derived from the exact frozen Plan, stored in the owned task root.
pub codex_catalog: Option<&'a [u8]>,
pub native_effort: Option<&'a str>,
pub gateway: SocketAddr,
@@ -55,6 +67,8 @@ pub struct CandidateWorkerProfile {
tools: Vec<WorkerToolV1>,
permission_policy: WorkerPermissionPolicyV1,
native_session_mode: String,
+ native_selected_model_id: String,
+ codex_initialization_root: Option<PathBuf>,
}
pub use super::platform::WorkerPlatformCapabilities;
@@ -67,14 +81,18 @@ impl CandidateWorkerProfile {
input.permit.generation,
)?;
let identity_contract = capabilities::identity_contract(&input)?;
- if ![
- input.adapter,
- input.harness_binary,
- input.private_root,
- input.workspace,
- ]
- .iter()
- .all(|p| p.is_absolute())
+ let selection = hiroute_domain::WorkerDependencySelectionRecordV1 {
+ harness: input.harness,
+ adapter_path: input.adapter.map(path_string).transpose()?,
+ cli_path: path_string(input.harness_binary)?,
+ node_path: input.node_binary.map(path_string).transpose()?,
+ };
+ let launch = selection
+ .validated_launch()
+ .map_err(|_| DelegationErrorV1::InvalidArguments)?;
+ if ![input.harness_binary, input.private_root, input.workspace]
+ .iter()
+ .all(|p| p.is_absolute())
|| input.node_binary.is_some_and(|p| !p.is_absolute())
|| !input.gateway.is_ipv4()
|| input.gateway.ip().is_unspecified()
@@ -89,11 +107,7 @@ impl CandidateWorkerProfile {
{
return Err(DelegationErrorV1::InvalidArguments);
}
- let token = std::str::from_utf8(input.token.expose())
- .map_err(|_| DelegationErrorV1::InvalidArguments)?;
- if token.len() > 4096 || !token.bytes().all(|b| b.is_ascii_graphic()) {
- return Err(DelegationErrorV1::InvalidArguments);
- }
+ secret_str(&input.token)?;
input
.session_root
.check_binding(input.harness, &input.execution.root_identity)?;
@@ -115,7 +129,24 @@ impl CandidateWorkerProfile {
),
};
let private_root = materials::checked_run_root(input.private_root, input.session_root)?;
- let origin = format!("http://{}", input.gateway);
+ if input.native_context.is_borrowed() {
+ if input.native_context.home().starts_with(&private_root)
+ || input
+ .native_context
+ .config_root()
+ .starts_with(&private_root)
+ || input
+ .native_context
+ .config_root()
+ .starts_with(input.session_root.path())
+ {
+ return Err(DelegationErrorV1::InvalidArguments);
+ }
+ } else if input.native_context.home() != private_root.join("home")
+ || input.native_context.config_root() != input.session_root.path()
+ {
+ return Err(DelegationErrorV1::InvalidArguments);
+ }
let native_session_mode = match (input.harness, input.permission_policy) {
(WorkerHarnessV1::CodexCli, WorkerPermissionPolicyV1::ApproveAll) => {
"agent-full-access"
@@ -125,11 +156,13 @@ impl CandidateWorkerProfile {
"bypassPermissions"
}
(WorkerHarnessV1::ClaudeCode, _) => "default",
+ (WorkerHarnessV1::QoderCli, WorkerPermissionPolicyV1::ApproveAll) => "yolo",
+ (WorkerHarnessV1::QoderCli, _) => return Err(DelegationErrorV1::CapabilityUnavailable),
};
let mut env = BTreeMap::new();
// This is a new child environment, never merged with std::env::vars().
// Tool discovery is not authentication. Keep an explicit command search
- // path while leaving ambient model credentials and configuration behind.
+ // path while leaving ambient model credentials behind. Native context selectors are explicit.
env.insert(
"PATH".into(),
Zeroizing::new(worker_path(
@@ -140,129 +173,48 @@ impl CandidateWorkerProfile {
);
env.insert(
"HOME".into(),
- Zeroizing::new(path_string(&private_root.join("home"))?),
+ Zeroizing::new(path_string(input.native_context.home())?),
);
env.insert(
"TMPDIR".into(),
Zeroizing::new(path_string(&private_root.join("tmp"))?),
);
- let mut session_meta = Map::new();
- match input.harness {
+ if input.harness == WorkerHarnessV1::ClaudeCode && input.native_context.is_borrowed() {
+ // Only the explicitly selected Node can establish the adapter environment guard.
+ // An executable adapter discovered without a runtime remains discoverable, but
+ // cannot silently start with unguarded borrowed settings.
+ input
+ .node_binary
+ .ok_or(DelegationErrorV1::CapabilityUnavailable)?;
+ claude_runtime::require_host_managed_provider(
+ input.harness_binary,
+ env["PATH"].as_str(),
+ )?;
+ }
+ let rendered = match input.harness {
WorkerHarnessV1::CodexCli => {
- let catalog_path = input
- .codex_catalog
- .map(|catalog| {
- input
- .session_root
- .prepare_codex_catalog(input.alias, catalog)
- })
- .transpose()?;
- input
- .session_root
- .prepare_codex_provider(input.gateway, catalog_path.as_deref())?;
- let (approval_policy, sandbox_mode) = match input.permission_policy {
- WorkerPermissionPolicyV1::ApproveAll => ("never", "danger-full-access"),
- WorkerPermissionPolicyV1::ApproveReads | WorkerPermissionPolicyV1::DenyAll => {
- ("on-request", "read-only")
- }
- };
- let mut config = json!({
- "model":input.alias, "model_provider":"hiroute", "approval_policy":approval_policy,
- "sandbox_mode":sandbox_mode,
- "model_providers":{"hiroute":{
- "name":"HiRoute managed run", "base_url":format!("{origin}/v1"),
- "wire_api":"responses", "supports_websockets":false,
- "env_key":"HIROUTE_RUN_TOKEN", "requires_openai_auth":false
- }},
- "features":{"multi_agent":false,"shell_tool":projected_tools.contains(&WorkerToolV1::Shell)},
- "web_search": if network == WorkerNetworkV1::Allowed { "live" } else { "disabled" },
- "mcp_servers":{},
- "sandbox_workspace_write":{"network_access":network == WorkerNetworkV1::Allowed},
- });
- if let Some(effort) = input.native_effort {
- config["model_reasoning_effort"] = json!(effort);
- }
- if let Some(path) = catalog_path {
- config["model_catalog_json"] = json!(path_string(&path)?);
- }
- env.insert("CODEX_CONFIG".into(), Zeroizing::new(config.to_string()));
- // codex-acp owns a per-turn AgentMode that overrides the app-server defaults.
- // Seed that exact native mode and verify it again over ACP before the prompt.
- env.insert(
- "INITIAL_AGENT_MODE".into(),
- Zeroizing::new(native_session_mode.into()),
- );
- env.insert("MODEL_PROVIDER".into(), Zeroizing::new("hiroute".into()));
- env.insert(
- "CODEX_PATH".into(),
- Zeroizing::new(path_string(input.harness_binary)?),
- );
- env.insert(
- "CODEX_HOME".into(),
- Zeroizing::new(path_string(input.session_root.path())?),
- );
- env.insert("HIROUTE_RUN_TOKEN".into(), Zeroizing::new(token.to_owned()));
+ codex::render(&input, &projected_tools, network, native_session_mode)?
}
- WorkerHarnessV1::ClaudeCode => {
- if let Some(window) = input.claude_context_window {
- let values = hiroute_domain::claude_context_environment(window)
- .ok_or(DelegationErrorV1::CapabilityUnavailable)?;
- for (key, value) in values {
- env.insert(key, Zeroizing::new(value));
- }
- }
- env.insert(
- "CLAUDE_CODE_EXECUTABLE".into(),
- Zeroizing::new(path_string(input.harness_binary)?),
- );
- env.insert(
- "CLAUDE_CONFIG_DIR".into(),
- Zeroizing::new(path_string(input.session_root.path())?),
- );
- // Claude Code may otherwise contact update, telemetry, and error-reporting
- // endpoints independently of the selected model provider. A managed Worker
- // process is allowed to reach its HiRoute Gateway (and projected tools may
- // separately have network access), but ambient product traffic must stay off.
- env.insert(
- "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC".into(),
- Zeroizing::new("1".into()),
- );
- env.insert("ANTHROPIC_BASE_URL".into(), Zeroizing::new(origin));
- env.insert(
- "ANTHROPIC_AUTH_TOKEN".into(),
- Zeroizing::new(token.to_owned()),
- );
- env.insert(
- "ANTHROPIC_MODEL".into(),
- Zeroizing::new(input.alias.to_owned()),
- );
- let mut tools = vec![];
- for tool in &projected_tools {
- match tool {
- WorkerToolV1::Read => tools.extend(["Read", "Glob", "Grep"]),
- WorkerToolV1::Edit => tools.extend(["Edit", "Write"]),
- WorkerToolV1::Shell => tools.push("Bash"),
- }
- }
- if input.permission_policy == WorkerPermissionPolicyV1::ApproveAll {
- tools.extend(["WebSearch", "WebFetch"]);
- }
- let mut options = json!({
- "settingSources":[], "model":input.alias, "tools":tools,
- "disallowedTools":["Agent","Task","AskUserQuestion"],
- "mcpServers":{}, "plugins":[], "hooks":{},
- "settings":{"apiKeyHelper":""},
- });
- if let Some(effort) = input.native_effort {
- options["effort"] = json!(effort);
+ WorkerHarnessV1::ClaudeCode => claude::render(&input, &projected_tools)?,
+ WorkerHarnessV1::QoderCli => qoder::render(&input, &private_root)?,
+ };
+ env.extend(rendered.env);
+ let (executable, args) = match launch {
+ WorkerLaunchFormV1::NativeAcp { cli } => (PathBuf::from(cli), rendered.native_args),
+ WorkerLaunchFormV1::AdapterAcp { adapter, node, .. } => {
+ if let Some(bootstrap) = rendered.adapter_bootstrap {
+ (
+ PathBuf::from(node.ok_or(DelegationErrorV1::CapabilityUnavailable)?),
+ vec![private_root.join(bootstrap), PathBuf::from(adapter)],
+ )
+ } else {
+ node.map_or_else(
+ || (PathBuf::from(adapter), vec![]),
+ |node| (PathBuf::from(node), vec![PathBuf::from(adapter)]),
+ )
}
- session_meta.insert("claudeCode".into(), json!({"options":options}));
}
- }
- let (executable, args) = input.node_binary.map_or_else(
- || (input.adapter.to_owned(), vec![]),
- |node| (node.to_owned(), vec![input.adapter.to_owned()]),
- );
+ };
Ok(Self {
executable,
args,
@@ -270,17 +222,25 @@ impl CandidateWorkerProfile {
private_root,
session_root: input.session_root.path().to_owned(),
materials: RunMaterials {
- directories: vec!["home".into(), "tmp".into()],
- files: vec![],
+ directories: if input.native_context.is_borrowed() {
+ vec!["tmp".into()]
+ } else {
+ vec!["home".into(), "tmp".into()]
+ },
+ files: rendered.files,
},
env,
- session_meta,
+ session_meta: rendered.session_meta,
identity_contract,
access,
network,
tools: projected_tools,
permission_policy: input.permission_policy,
native_session_mode: native_session_mode.to_owned(),
+ native_selected_model_id: rendered.native_model_id,
+ codex_initialization_root: (input.harness == WorkerHarnessV1::CodexCli
+ && input.native_context.is_borrowed())
+ .then(|| input.native_context.config_root().to_owned()),
})
}
@@ -299,6 +259,17 @@ impl CandidateWorkerProfile {
&self.native_session_mode
}
+ /// The exact native selector ID. Plan/Gateway authorization still uses the raw alias.
+ pub fn native_selected_model_id(&self) -> &str {
+ &self.native_selected_model_id
+ }
+
+ /// The installation owner has already bound the canonical effective native root.
+ /// Never derive this coordination key from cwd, a model alias, or mutable child env.
+ pub(crate) fn codex_initialization_root(&self) -> Option<&Path> {
+ self.codex_initialization_root.as_deref()
+ }
+
/// Compatibility check for callers that require a native Harness profile. Restricted
/// policies are Harness configuration, not a different process-confinement capability.
pub fn require_native_mode(&self) -> Result<(), DelegationErrorV1> {
@@ -348,6 +319,29 @@ pub(crate) fn test_codex_catalog(alias: &str) -> Vec<u8> {
.unwrap()
}
+#[derive(Default)]
+struct RenderedHarnessProfile {
+ env: BTreeMap<String, Zeroizing<String>>,
+ session_meta: Map<String, Value>,
+ files: Vec<RunMaterialFile>,
+ adapter_bootstrap: Option<PathBuf>,
+ native_args: Vec<PathBuf>,
+ native_model_id: String,
+}
+
+fn secret_str(secret: &ProtectedSecret) -> Result<&str, DelegationErrorV1> {
+ let value =
+ std::str::from_utf8(secret.expose()).map_err(|_| DelegationErrorV1::InvalidArguments)?;
+ if value.len() > 4096 || !value.bytes().all(|b| b.is_ascii_graphic()) {
+ return Err(DelegationErrorV1::InvalidArguments);
+ }
+ Ok(value)
+}
+
+fn secret_string(secret: &ProtectedSecret) -> Result<String, DelegationErrorV1> {
+ secret_str(secret).map(str::to_owned)
+}
+
fn path_string(path: &Path) -> Result<String, DelegationErrorV1> {
path.to_str()
.filter(|s| !s.contains(['\n', '\r', '\0']))
@@ -358,10 +352,10 @@ fn path_string(path: &Path) -> Result<String, DelegationErrorV1> {
fn worker_path(
harness: &Path,
node: Option<&Path>,
- adapter: &Path,
+ adapter: Option<&Path>,
) -> Result<String, DelegationErrorV1> {
let mut paths = Vec::new();
- for executable in [node, Some(harness), Some(adapter)].into_iter().flatten() {
+ for executable in [node, Some(harness), adapter].into_iter().flatten() {
if let Some(parent) = executable.parent() {
paths.push(parent.to_owned());
}
diff --git a/crates/daemon/src/delegation/profile/native_context.rs b/crates/daemon/src/delegation/profile/native_context.rs
new file mode 100644
index 00000000..a05e2d0f
--- /dev/null
+++ b/crates/daemon/src/delegation/profile/native_context.rs
@@ -0,0 +1,134 @@
+//! The instance's native context is borrowed; it is never a cleanup target.
+use super::{DelegationErrorV1, Path, PathBuf, WorkerHarnessV1, path_string};
+use std::ffi::OsString;
+
+#[derive(Clone, Debug, Eq, PartialEq)]
+pub struct NativeWorkerContext {
+ home: PathBuf,
+ config_root: PathBuf,
+ borrowed: bool,
+}
+
+impl NativeWorkerContext {
+ /// Resolve only context selectors, never credentials or the entire service environment.
+ /// An explicit Pilot/test HOME is the effective user context, not a hint to search elsewhere.
+ pub fn from_environment(harness: WorkerHarnessV1) -> Result<Self, DelegationErrorV1> {
+ Self::from_lookup(harness, |name| std::env::var_os(name))
+ }
+
+ fn from_lookup(
+ harness: WorkerHarnessV1,
+ lookup: impl Fn(&str) -> Option<OsString>,
+ ) -> Result<Self, DelegationErrorV1> {
+ let home = lookup("HOME")
+ .map(PathBuf::from)
+ .ok_or(DelegationErrorV1::CapabilityUnavailable)?;
+ let (variable, default) = match harness {
+ WorkerHarnessV1::CodexCli => ("CODEX_HOME", ".codex"),
+ WorkerHarnessV1::ClaudeCode => ("CLAUDE_CONFIG_DIR", ".claude"),
+ WorkerHarnessV1::QoderCli => {
+ let selected = lookup("QODER_CONFIG_DIR").map(PathBuf::from);
+ let context = hiroute_integrations::agents::QoderNativeContext::from_selected(
+ &home,
+ selected.as_deref(),
+ )
+ .map_err(|_| DelegationErrorV1::InvalidArguments)?;
+ return Self::borrowed(&context.home, &context.config_root);
+ }
+ };
+ let config_root = lookup(variable)
+ .map(PathBuf::from)
+ .unwrap_or_else(|| home.join(default));
+ Self::borrowed(&home, &config_root)
+ }
+
+ /// Reconstruct an already bound context without consulting today's environment on Continue.
+ pub fn borrowed(home: &Path, config_root: &Path) -> Result<Self, DelegationErrorV1> {
+ Self::new(home.to_owned(), config_root.to_owned(), true)
+ }
+
+ /// Explicit legacy/probe context. Its directories remain owned by the existing material path.
+ pub fn isolated(private_root: &Path, session_root: &Path) -> Result<Self, DelegationErrorV1> {
+ Self::new(private_root.join("home"), session_root.to_owned(), false)
+ }
+
+ fn new(home: PathBuf, config_root: PathBuf, borrowed: bool) -> Result<Self, DelegationErrorV1> {
+ for path in [&home, &config_root] {
+ if !path.is_absolute()
+ || path
+ .components()
+ .any(|part| part == std::path::Component::ParentDir)
+ {
+ return Err(DelegationErrorV1::InvalidArguments);
+ }
+ path_string(path)?;
+ }
+ Ok(Self {
+ home,
+ config_root,
+ borrowed,
+ })
+ }
+
+ pub fn home(&self) -> &Path {
+ &self.home
+ }
+
+ pub fn config_root(&self) -> &Path {
+ &self.config_root
+ }
+
+ pub fn is_borrowed(&self) -> bool {
+ self.borrowed
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn instance_home_and_explicit_native_roots_are_respected_without_reading_other_env() {
+ for (harness, variable, default) in [
+ (WorkerHarnessV1::CodexCli, "CODEX_HOME", ".codex"),
+ (WorkerHarnessV1::ClaudeCode, "CLAUDE_CONFIG_DIR", ".claude"),
+ (WorkerHarnessV1::QoderCli, "QODER_CONFIG_DIR", ".qoder"),
+ ] {
+ let lookup = |name: &str| match name {
+ "HOME" => Some(OsString::from("/isolated-pilot")),
+ key if key == variable => Some(OsString::from("/explicit-native-root")),
+ unexpected => panic!("unexpected ambient environment read: {unexpected}"),
+ };
+ let explicit = NativeWorkerContext::from_lookup(harness, lookup).unwrap();
+ assert_eq!(explicit.home(), Path::new("/isolated-pilot"));
+ assert_eq!(explicit.config_root(), Path::new("/explicit-native-root"));
+ assert!(explicit.is_borrowed());
+ let fallback = NativeWorkerContext::from_lookup(harness, |name| {
+ (name == "HOME").then(|| OsString::from("/isolated-pilot"))
+ })
+ .unwrap();
+ assert_eq!(
+ fallback.config_root(),
+ Path::new("/isolated-pilot").join(default)
+ );
+ }
+ }
+
+ #[test]
+ fn missing_or_invalid_context_does_not_fall_back_to_another_users_home() {
+ assert_eq!(
+ NativeWorkerContext::from_lookup(WorkerHarnessV1::CodexCli, |_| None),
+ Err(DelegationErrorV1::CapabilityUnavailable)
+ );
+ for invalid in ["", "relative", "/root/../elsewhere", "/root\nother"] {
+ assert_eq!(
+ NativeWorkerContext::borrowed(Path::new(invalid), Path::new("/native")),
+ Err(DelegationErrorV1::InvalidArguments)
+ );
+ assert_eq!(
+ NativeWorkerContext::borrowed(Path::new("/instance"), Path::new(invalid)),
+ Err(DelegationErrorV1::InvalidArguments)
+ );
+ }
+ }
+}
diff --git a/crates/daemon/src/delegation/profile/native_history.rs b/crates/daemon/src/delegation/profile/native_history.rs
new file mode 100644
index 00000000..16881741
--- /dev/null
+++ b/crates/daemon/src/delegation/profile/native_history.rs
@@ -0,0 +1,376 @@
+//! A task owns its context descriptor and continuation binding, never the borrowed client root.
+//! Native transcripts remain opaque. Only Claude's exact file is inspected for flush/readiness;
+//! Codex/Qoder availability is established by exact session/load, not a shared-history scan.
+use super::*;
+use serde::{Deserialize, Serialize, de::DeserializeOwned};
+use std::io::{Read, Write};
+use unicode_normalization::UnicodeNormalization;
+
+const CONTEXT_FILE: &str = "borrowed-native-context.json";
+const SESSION_FILE: &str = "native-session-binding.json";
+const METADATA_LIMIT: u64 = 32 * 1024;
+
+/// The original context selected for a task. These paths convey no cleanup ownership.
+#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct BorrowedNativeContext {
+ pub home: PathBuf,
+ pub config_root: PathBuf,
+ pub workspace: PathBuf,
+}
+
+#[derive(Eq, PartialEq, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub(super) struct ContextDescriptor {
+ version: u32,
+ harness: WorkerHarnessV1,
+ context: BorrowedNativeContext,
+}
+
+#[derive(Eq, PartialEq, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+struct SessionBinding {
+ version: u32,
+ context_digest: CanonicalDigest,
+ native_session_id: String,
+}
+
+impl TaskSessionRoot {
+ /// Bind a new task once. Continuing an old private task never implicitly migrates it.
+ pub fn bind_borrowed_context(
+ &self,
+ home: &Path,
+ config_root: &Path,
+ workspace: &Path,
+ ) -> Result<(), DelegationErrorV1> {
+ if !self.newly_created {
+ return Err(DelegationErrorV1::Conflict);
+ }
+ let context = BorrowedNativeContext {
+ home: canonical_context_path(home, false)?,
+ config_root: canonical_context_path(config_root, true)?,
+ workspace: canonical_context_path(workspace, false)?,
+ };
+ if context.config_root.starts_with(&self.path) {
+ return Err(DelegationErrorV1::InvalidArguments);
+ }
+ write_owned_json(
+ &self.path,
+ CONTEXT_FILE,
+ &ContextDescriptor {
+ version: 1,
+ harness: self.harness,
+ context,
+ },
+ )
+ }
+
+ /// Only Codex/Claude accept a missing descriptor as the registered legacy private-root
+ /// format. Malformed, replaced or mismatched metadata never selects a recovery reader.
+ pub fn borrowed_context(&self) -> Result<Option<BorrowedNativeContext>, DelegationErrorV1> {
+ read_context(&self.path, self.harness).map(|value| value.map(|value| value.context))
+ }
+
+ /// Match the task's persisted ACP identity before attempting Continue. For borrowed Codex/Qoder,
+ /// this proves only the retained binding: session/load must still confirm native history.
+ pub fn verify_native_session(&self, native_session_id: &str) -> Result<(), DelegationErrorV1> {
+ match read_context(&self.path, self.harness)? {
+ Some(context) => {
+ let binding = read_binding(&self.path, &context)?;
+ if binding.native_session_id != native_session_id {
+ return Err(DelegationErrorV1::ResumeUnavailable);
+ }
+ verify_borrowed_history(&context, native_session_id)
+ }
+ None => legacy_native_history(&self.path, self.harness, native_session_id).map(|_| ()),
+ }
+ }
+
+ /// Locate an actual transcript for lifecycle observation. A Codex/Qoder borrowed binding
+ /// is deliberately not returned as a transcript; its contents say nothing about disk flush.
+ pub(crate) fn native_transcript_path(
+ root: &Path,
+ harness: WorkerHarnessV1,
+ native_session_id: &str,
+ ) -> Result<PathBuf, DelegationErrorV1> {
+ if let Some(context) = read_context(root, harness)? {
+ return claude_transcript(&context, native_session_id);
+ }
+ legacy_native_history(root, harness, native_session_id)?
+ .pop()
+ .map(|relative| root.join(relative))
+ .ok_or(DelegationErrorV1::ResumeUnavailable)
+ }
+}
+
+pub(super) fn read_context(
+ root: &Path,
+ harness: WorkerHarnessV1,
+) -> Result<Option<ContextDescriptor>, DelegationErrorV1> {
+ checked_directory(root).map_err(|_| DelegationErrorV1::ResumeUnavailable)?;
+ match fs::symlink_metadata(root.join(CONTEXT_FILE)) {
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
+ return match fs::symlink_metadata(root.join(SESSION_FILE)) {
+ Err(error)
+ if error.kind() == std::io::ErrorKind::NotFound
+ && harness != WorkerHarnessV1::QoderCli =>
+ {
+ Ok(None)
+ }
+ _ => Err(DelegationErrorV1::ResumeUnavailable),
+ };
+ }
+ Err(_) => return Err(DelegationErrorV1::ResumeUnavailable),
+ Ok(_) => {}
+ }
+ let descriptor: ContextDescriptor = read_owned_json(root, CONTEXT_FILE)?;
+ if descriptor.version != 1 || descriptor.harness != harness {
+ return Err(DelegationErrorV1::ResumeUnavailable);
+ }
+ let context = &descriptor.context;
+ for (path, missing) in [
+ (&context.home, false),
+ (&context.config_root, true),
+ (&context.workspace, false),
+ ] {
+ if canonical_context_path(path, missing)
+ .map_err(|_| DelegationErrorV1::ResumeUnavailable)?
+ != *path
+ {
+ return Err(DelegationErrorV1::ResumeUnavailable);
+ }
+ }
+ if context.config_root.starts_with(root) {
+ return Err(DelegationErrorV1::ResumeUnavailable);
+ }
+ Ok(Some(descriptor))
+}
+
+pub(super) fn retain_borrowed_session(
+ root: &Path,
+ harness: WorkerHarnessV1,
+ native_session_id: &str,
+) -> Result<Vec<String>, DelegationErrorV1> {
+ let context = read_context(root, harness)?.ok_or(DelegationErrorV1::ResumeUnavailable)?;
+ verify_borrowed_history(&context, native_session_id)?;
+ write_owned_json(
+ root,
+ SESSION_FILE,
+ &SessionBinding {
+ version: 1,
+ context_digest: context_digest(&context)?,
+ native_session_id: native_session_id.to_owned(),
+ },
+ )?;
+ Ok(vec![SESSION_FILE.to_owned()])
+}
+
+pub(super) fn verify_continuation_materials(
+ root: &Path,
+ harness: WorkerHarnessV1,
+ required: &[PathBuf],
+) -> Result<(), DelegationErrorV1> {
+ if let Some(context) = read_context(root, harness)? {
+ if required != [PathBuf::from(SESSION_FILE)] {
+ return Err(DelegationErrorV1::ResumeUnavailable);
+ }
+ let binding = read_binding(root, &context)?;
+ verify_borrowed_history(&context, &binding.native_session_id)?;
+ }
+ Ok(())
+}
+
+fn read_binding(
+ root: &Path,
+ context: &ContextDescriptor,
+) -> Result<SessionBinding, DelegationErrorV1> {
+ let binding: SessionBinding = read_owned_json(root, SESSION_FILE)?;
+ if binding.version != 1 || binding.context_digest != context_digest(context)? {
+ return Err(DelegationErrorV1::ResumeUnavailable);
+ }
+ validate_session_id(&binding.native_session_id)?;
+ Ok(binding)
+}
+
+fn context_digest(context: &ContextDescriptor) -> Result<CanonicalDigest, DelegationErrorV1> {
+ CanonicalDigest::of(context).map_err(|_| DelegationErrorV1::ResumeUnavailable)
+}
+
+fn verify_borrowed_history(
+ context: &ContextDescriptor,
+ native_session_id: &str,
+) -> Result<(), DelegationErrorV1> {
+ validate_session_id(native_session_id)?;
+ if context.harness == WorkerHarnessV1::ClaudeCode {
+ claude_transcript(context, native_session_id)?;
+ }
+ Ok(())
+}
+
+fn claude_transcript(
+ descriptor: &ContextDescriptor,
+ native_session_id: &str,
+) -> Result<PathBuf, DelegationErrorV1> {
+ validate_session_id(native_session_id)?;
+ if descriptor.harness != WorkerHarnessV1::ClaudeCode {
+ return Err(DelegationErrorV1::ResumeUnavailable);
+ }
+ let context = &descriptor.context;
+ let relative = PathBuf::from("projects")
+ .join(claude_workspace_key(&context.workspace)?)
+ .join(format!("{native_session_id}.jsonl"));
+ // This checks only the exact path's components, never siblings or the shared root's mode.
+ check_history(&context.config_root, &relative)?;
+ Ok(context.config_root.join(relative))
+}
+
+fn validate_session_id(id: &str) -> Result<(), DelegationErrorV1> {
+ if id.is_empty()
+ || id.len() > 256
+ || id
+ .chars()
+ .any(|ch| ch.is_control() || matches!(ch, '/' | '\\' | ':'))
+ {
+ return Err(DelegationErrorV1::ResumeUnavailable);
+ }
+ Ok(())
+}
+
+/// Claude Code 2.1.231 and SDK 0.3.215 encode NFC cwd using JavaScript UTF-16 code units.
+/// The 200-character key limit and signed 32-bit hash also apply to non-BMP workspace names.
+fn claude_workspace_key(workspace: &Path) -> Result<String, DelegationErrorV1> {
+ let text = workspace
+ .to_str()
+ .ok_or(DelegationErrorV1::ResumeUnavailable)?;
+ let normalized: String = text.nfc().collect();
+ let mut hash = 0_i32;
+ let mut key = String::new();
+ for unit in normalized.encode_utf16() {
+ hash = hash.wrapping_mul(31).wrapping_add(i32::from(unit));
+ key.push(if unit <= 127 && (unit as u8).is_ascii_alphanumeric() {
+ char::from(unit as u8)
+ } else {
+ '-'
+ });
+ }
+ if key.len() > 200 {
+ key.truncate(200);
+ key.push('-');
+ key.push_str(&base36(hash.unsigned_abs()));
+ }
+ Ok(key)
+}
+
+fn base36(mut value: u32) -> String {
+ let mut digits = Vec::new();
+ loop {
+ digits.push(char::from(
+ b"0123456789abcdefghijklmnopqrstuvwxyz"[(value % 36) as usize],
+ ));
+ value /= 36;
+ if value == 0 {
+ return digits.into_iter().rev().collect();
+ }
+ }
+}
+
+fn canonical_context_path(path: &Path, allow_missing: bool) -> Result<PathBuf, DelegationErrorV1> {
+ if !path.is_absolute()
+ || path
+ .to_str()
+ .is_none_or(|path| path.contains(['\0', '\r', '\n']))
+ || path
+ .components()
+ .any(|part| matches!(part, Component::ParentDir))
+ {
+ return Err(DelegationErrorV1::InvalidArguments);
+ }
+ match fs::canonicalize(path) {
+ Ok(path) if path.is_dir() => Ok(path),
+ Err(error) if allow_missing && error.kind() == std::io::ErrorKind::NotFound => {
+ // Clients may create a default config root on their first run. Resolve its existing
+ // prefix without creating, chmodding, copying or adopting anything in the user root.
+ let parent = path.parent().ok_or(DelegationErrorV1::InvalidArguments)?;
+ let name = path
+ .file_name()
+ .ok_or(DelegationErrorV1::InvalidArguments)?;
+ Ok(canonical_context_path(parent, true)?.join(name))
+ }
+ _ => Err(DelegationErrorV1::ResumeUnavailable),
+ }
+}
+
+fn read_owned_json<T: DeserializeOwned>(root: &Path, name: &str) -> Result<T, DelegationErrorV1> {
+ let path = root.join(name);
+ let path_metadata =
+ fs::symlink_metadata(&path).map_err(|_| DelegationErrorV1::ResumeUnavailable)?;
+ if linked(&path_metadata) || !path_metadata.is_file() || path_metadata.len() > METADATA_LIMIT {
+ return Err(DelegationErrorV1::ResumeUnavailable);
+ }
+ let file = open_marker(&path)?;
+ let metadata = file
+ .metadata()
+ .map_err(|_| DelegationErrorV1::ResumeUnavailable)?;
+ if !metadata.is_file() || metadata.len() > METADATA_LIMIT {
+ return Err(DelegationErrorV1::ResumeUnavailable);
+ }
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::MetadataExt;
+ if metadata.uid() != nix::unistd::geteuid().as_raw()
+ || metadata.mode() & 0o077 != 0
+ || metadata.nlink() != 1
+ {
+ return Err(DelegationErrorV1::ResumeUnavailable);
+ }
+ }
+ let mut bytes = Vec::new();
+ file.take(METADATA_LIMIT + 1)
+ .read_to_end(&mut bytes)
+ .map_err(|_| DelegationErrorV1::ResumeUnavailable)?;
+ if bytes.len() as u64 > METADATA_LIMIT {
+ return Err(DelegationErrorV1::ResumeUnavailable);
+ }
+ serde_json::from_slice(&bytes).map_err(|_| DelegationErrorV1::ResumeUnavailable)
+}
+
+fn write_owned_json<T: Serialize + DeserializeOwned + PartialEq>(
+ root: &Path,
+ name: &str,
+ value: &T,
+) -> Result<(), DelegationErrorV1> {
+ checked_directory(root)?;
+ let bytes = serde_json::to_vec(value).map_err(|_| DelegationErrorV1::StorageUnavailable)?;
+ if bytes.len() as u64 > METADATA_LIMIT {
+ return Err(DelegationErrorV1::InvalidArguments);
+ }
+ let mut options = fs::OpenOptions::new();
+ options.write(true).create_new(true);
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::OpenOptionsExt;
+ options.mode(0o600);
+ }
+ match options.open(root.join(name)) {
+ Ok(mut file) => {
+ file.write_all(&bytes)
+ .and_then(|()| file.sync_all())
+ .map_err(|_| DelegationErrorV1::StorageUnavailable)?;
+ fs::File::open(root)
+ .and_then(|directory| directory.sync_all())
+ .map_err(|_| DelegationErrorV1::StorageUnavailable)
+ }
+ Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
+ if read_owned_json::<T>(root, name)? == *value {
+ Ok(())
+ } else {
+ Err(DelegationErrorV1::Conflict)
+ }
+ }
+ Err(_) => Err(DelegationErrorV1::StorageUnavailable),
+ }
+}
+
+#[cfg(test)]
+#[path = "native_history_tests.rs"]
+mod tests;
diff --git a/crates/daemon/src/delegation/profile/native_history_tests.rs b/crates/daemon/src/delegation/profile/native_history_tests.rs
new file mode 100644
index 00000000..2020cafb
--- /dev/null
+++ b/crates/daemon/src/delegation/profile/native_history_tests.rs
@@ -0,0 +1,301 @@
+use super::*;
+
+const SESSION: &str = "71a2b020-312e-49cd-b084-924cbb3642ad";
+
+struct Fixture {
+ _storage: tempfile::TempDir,
+ home: PathBuf,
+ config: PathBuf,
+ workspace: PathBuf,
+ session: TaskSessionRoot,
+}
+
+impl Fixture {
+ fn new(harness: WorkerHarnessV1) -> Self {
+ let storage = tempfile::tempdir().unwrap();
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ fs::set_permissions(storage.path(), fs::Permissions::from_mode(0o700)).unwrap();
+ }
+ let home = storage.path().join("daily-home");
+ let config = home.join("native-config");
+ let workspace = storage.path().join("workspace");
+ fs::create_dir_all(&config).unwrap();
+ fs::create_dir(&workspace).unwrap();
+ let home = fs::canonicalize(home).unwrap();
+ let config = fs::canonicalize(config).unwrap();
+ let workspace = fs::canonicalize(workspace).unwrap();
+ let session = TaskSessionRoot::prepare(
+ storage.path(),
+ &WorkspaceId::parse("workspace").unwrap(),
+ "workspace-root",
+ "task",
+ harness,
+ SessionRootUse::New,
+ )
+ .unwrap();
+ session
+ .bind_borrowed_context(&home, &config, &workspace)
+ .unwrap();
+ Self {
+ _storage: storage,
+ home,
+ config,
+ workspace,
+ session,
+ }
+ }
+
+ fn reopen(&self, required: &[PathBuf]) -> Result<TaskSessionRoot, DelegationErrorV1> {
+ TaskSessionRoot::prepare(
+ self._storage.path(),
+ &WorkspaceId::parse("workspace").unwrap(),
+ "workspace-root",
+ "task",
+ self.session.harness,
+ SessionRootUse::Continue {
+ required_history: required,
+ },
+ )
+ }
+
+ fn claude_history(&self) -> PathBuf {
+ // Filesystem fixtures use the short-path native spelling. Unicode and long-path
+ // contract cases below use literal expected values captured from the native algorithm.
+ let cwd = fs::canonicalize(&self.workspace).unwrap();
+ let project = cwd
+ .to_str()
+ .unwrap()
+ .replace(|ch: char| !ch.is_ascii_alphanumeric(), "-");
+ self.config
+ .join("projects")
+ .join(project)
+ .join(format!("{SESSION}.jsonl"))
+ }
+}
+
+#[test]
+fn borrowed_codex_and_qoder_retain_exact_binding_without_claiming_native_history_availability() {
+ for harness in [WorkerHarnessV1::CodexCli, WorkerHarnessV1::QoderCli] {
+ let fixture = Fixture::new(harness);
+ let daily = fixture.config.join("daily-history.jsonl");
+ fs::write(&daily, b"unrelated user's history").unwrap();
+ let before = fs::read(&daily).unwrap();
+ let materials = native_history(fixture.session.path(), harness, SESSION).unwrap();
+ assert_eq!(materials, [SESSION_FILE]);
+ assert!(!fixture.config.join("sessions").exists());
+ assert!(!fixture.session.path().join("sessions").exists());
+ let required = materials.iter().map(PathBuf::from).collect::<Vec<_>>();
+ let resumed = fixture.reopen(&required).unwrap();
+ resumed.verify_native_session(SESSION).unwrap();
+ assert_eq!(
+ resumed.verify_native_session("other-session"),
+ Err(DelegationErrorV1::ResumeUnavailable)
+ );
+ assert_eq!(
+ TaskSessionRoot::native_transcript_path(fixture.session.path(), harness, SESSION),
+ Err(DelegationErrorV1::ResumeUnavailable)
+ );
+ assert_eq!(fs::read(daily).unwrap(), before);
+ }
+}
+
+#[test]
+fn borrowed_context_survives_restart_and_cannot_be_rebound_by_continue() {
+ let fixture = Fixture::new(WorkerHarnessV1::CodexCli);
+ let context = fixture.session.borrowed_context().unwrap().unwrap();
+ assert_eq!(context.home, fs::canonicalize(&fixture.home).unwrap());
+ assert_eq!(
+ context.config_root,
+ fs::canonicalize(&fixture.config).unwrap()
+ );
+ assert_eq!(
+ context.workspace,
+ fs::canonicalize(&fixture.workspace).unwrap()
+ );
+ fixture
+ .session
+ .bind_borrowed_context(&fixture.home, &fixture.config, &fixture.workspace)
+ .unwrap();
+ assert_eq!(
+ fixture
+ .session
+ .bind_borrowed_context(&fixture.home, &fixture.home, &fixture.workspace),
+ Err(DelegationErrorV1::Conflict)
+ );
+ native_history(fixture.session.path(), WorkerHarnessV1::CodexCli, SESSION).unwrap();
+ let resumed = fixture.reopen(&[PathBuf::from(SESSION_FILE)]).unwrap();
+ assert_eq!(resumed.borrowed_context().unwrap(), Some(context));
+ assert_eq!(
+ resumed.bind_borrowed_context(&fixture.home, &fixture.config, &fixture.workspace),
+ Err(DelegationErrorV1::Conflict)
+ );
+}
+
+#[test]
+fn borrowed_claude_checks_only_its_workspace_and_exact_native_session() {
+ let fixture = Fixture::new(WorkerHarnessV1::ClaudeCode);
+ let history = fixture.claude_history();
+ fs::create_dir_all(history.parent().unwrap()).unwrap();
+ fs::write(&history, b"opaque native transcript\n").unwrap();
+ // More than the old scanner's bound, plus an identical ID in a different project.
+ let unrelated = fixture.config.join("projects/unrelated");
+ fs::create_dir(&unrelated).unwrap();
+ for index in 0..520 {
+ fs::write(unrelated.join(format!("{index}.jsonl")), b"other").unwrap();
+ }
+ fs::write(
+ unrelated.join(format!("{SESSION}.jsonl")),
+ b"other workspace",
+ )
+ .unwrap();
+ #[cfg(unix)]
+ std::os::unix::fs::symlink("absent", unrelated.join("ignored-link")).unwrap();
+ assert_eq!(
+ TaskSessionRoot::native_transcript_path(
+ fixture.session.path(),
+ WorkerHarnessV1::ClaudeCode,
+ SESSION
+ )
+ .unwrap(),
+ history
+ );
+ native_history(fixture.session.path(), WorkerHarnessV1::ClaudeCode, SESSION).unwrap();
+ let resumed = fixture.reopen(&[PathBuf::from(SESSION_FILE)]).unwrap();
+ resumed.verify_native_session(SESSION).unwrap();
+ fs::remove_file(&history).unwrap();
+ assert_eq!(
+ resumed.verify_native_session(SESSION),
+ Err(DelegationErrorV1::ResumeUnavailable)
+ );
+ assert!(matches!(
+ fixture.reopen(&[PathBuf::from(SESSION_FILE)]),
+ Err(DelegationErrorV1::ResumeUnavailable)
+ ));
+ assert!(unrelated.join(format!("{SESSION}.jsonl")).exists());
+}
+
+#[test]
+fn missing_or_replaced_descriptor_never_becomes_legacy_continuation() {
+ let fixture = Fixture::new(WorkerHarnessV1::CodexCli);
+ native_history(fixture.session.path(), WorkerHarnessV1::CodexCli, SESSION).unwrap();
+ let descriptor = fixture.session.path().join(CONTEXT_FILE);
+ let original = fs::read(&descriptor).unwrap();
+ fs::write(&descriptor, b"{}").unwrap();
+ assert!(fixture.session.borrowed_context().is_err());
+ assert!(fixture.reopen(&[PathBuf::from(SESSION_FILE)]).is_err());
+ fs::write(&descriptor, &original).unwrap();
+ let mut changed: serde_json::Value = serde_json::from_slice(&original).unwrap();
+ changed["context"]["config_root"] = serde_json::json!(fixture.home);
+ fs::write(&descriptor, serde_json::to_vec(&changed).unwrap()).unwrap();
+ assert!(fixture.reopen(&[PathBuf::from(SESSION_FILE)]).is_err());
+ fs::remove_file(&descriptor).unwrap();
+ assert!(fixture.session.borrowed_context().is_err());
+}
+
+#[test]
+fn native_session_binding_is_immutable_and_is_not_an_arbitrary_material_path() {
+ let fixture = Fixture::new(WorkerHarnessV1::CodexCli);
+ native_history(fixture.session.path(), WorkerHarnessV1::CodexCli, SESSION).unwrap();
+ assert_eq!(
+ native_history(
+ fixture.session.path(),
+ WorkerHarnessV1::CodexCli,
+ "another-native-session"
+ ),
+ Err(DelegationErrorV1::Conflict)
+ );
+ fs::write(fixture.session.path().join("unrelated.jsonl"), b"unrelated").unwrap();
+ assert!(fixture.reopen(&[PathBuf::from("unrelated.jsonl")]).is_err());
+ for invalid in [
+ "",
+ "../session",
+ "session/name",
+ "session\\name",
+ "session\n",
+ ] {
+ assert!(
+ native_history(fixture.session.path(), WorkerHarnessV1::CodexCli, invalid).is_err()
+ );
+ }
+}
+
+#[cfg(unix)]
+#[test]
+fn owned_metadata_and_exact_claude_transcripts_reject_links() {
+ use std::os::unix::fs::symlink;
+ let fixture = Fixture::new(WorkerHarnessV1::ClaudeCode);
+ let history = fixture.claude_history();
+ fs::create_dir_all(history.parent().unwrap()).unwrap();
+ let target = fixture.home.join("not-this-session");
+ fs::write(&target, b"unrelated").unwrap();
+ symlink(&target, &history).unwrap();
+ assert!(native_history(fixture.session.path(), WorkerHarnessV1::ClaudeCode, SESSION).is_err());
+ let descriptor = fixture.session.path().join(CONTEXT_FILE);
+ let bytes = fs::read(&descriptor).unwrap();
+ fs::remove_file(&descriptor).unwrap();
+ let other = fixture.session.path().join("other-descriptor.json");
+ fs::write(&other, bytes).unwrap();
+ symlink(&other, descriptor).unwrap();
+ assert!(fixture.session.borrowed_context().is_err());
+ assert_eq!(fs::read(target).unwrap(), b"unrelated");
+}
+
+#[test]
+fn claude_workspace_keys_match_native_unicode_and_long_path_vectors() {
+ assert_eq!(
+ claude_workspace_key(Path::new("/Users/test/cafe\u{301}/任务/😀")).unwrap(),
+ "-Users-test-caf-------"
+ );
+ assert_eq!(
+ claude_workspace_key(Path::new("/Users/test/café/任务/😀")).unwrap(),
+ "-Users-test-caf-------"
+ );
+ assert_eq!(
+ claude_workspace_key(Path::new(&format!("/tmp/{}", "abc".repeat(80)))).unwrap(),
+ format!("-tmp-{}-89qna1", "abc".repeat(65))
+ );
+ assert_eq!(
+ claude_workspace_key(Path::new(&format!("/tmp/{}", "😀".repeat(110)))).unwrap(),
+ format!("-tmp{}-na1or3", "-".repeat(196))
+ );
+}
+
+#[test]
+fn creating_the_descriptor_does_not_create_a_missing_native_config_root() {
+ let fixture = Fixture::new(WorkerHarnessV1::CodexCli);
+ // Use a distinct new task: published descriptors are never overwritten.
+ let session = TaskSessionRoot::prepare(
+ fixture._storage.path(),
+ &WorkspaceId::parse("workspace").unwrap(),
+ "workspace-root",
+ "another-task",
+ WorkerHarnessV1::CodexCli,
+ SessionRootUse::New,
+ )
+ .unwrap();
+ let absent = fixture.home.join("new-client/config");
+ session
+ .bind_borrowed_context(&fixture.home, &absent, &fixture.workspace)
+ .unwrap();
+ assert!(!absent.exists());
+ assert_eq!(
+ session.borrowed_context().unwrap().unwrap().config_root,
+ absent
+ );
+}
+
+#[test]
+fn qoder_missing_borrowed_descriptor_cannot_be_reinterpreted_as_private_legacy_history() {
+ let fixture = Fixture::new(WorkerHarnessV1::QoderCli);
+ fs::remove_file(fixture.session.path().join(CONTEXT_FILE)).unwrap();
+ assert!(matches!(
+ fixture.session.borrowed_context(),
+ Err(DelegationErrorV1::ResumeUnavailable)
+ ));
+ assert!(matches!(
+ native_history(fixture.session.path(), WorkerHarnessV1::QoderCli, SESSION),
+ Err(DelegationErrorV1::ResumeUnavailable)
+ ));
+}
diff --git a/crates/daemon/src/delegation/profile/qoder.rs b/crates/daemon/src/delegation/profile/qoder.rs
new file mode 100644
index 00000000..da41f053
--- /dev/null
+++ b/crates/daemon/src/delegation/profile/qoder.rs
@@ -0,0 +1,76 @@
+//! Native ACP arguments and run materials. Shared Qoder settings live in integrations.
+use super::*;
+use hiroute_integrations::agents::{QoderTransientRouteInput, render_qoder_transient_route};
+
+pub(super) fn render(
+ input: &ProfileInput<'_>,
+ private_root: &Path,
+) -> Result<RenderedHarnessProfile, DelegationErrorV1> {
+ let context_window_tokens = input
+ .context_window_tokens
+ .ok_or(DelegationErrorV1::CapabilityUnavailable)?;
+ let max_output_tokens = input
+ .max_output_tokens
+ .ok_or(DelegationErrorV1::CapabilityUnavailable)?;
+ let task_key = input
+ .session_root
+ .path()
+ .file_name()
+ .and_then(|name| name.to_str())
+ .ok_or(DelegationErrorV1::InvalidArguments)?;
+ let provider_id = format!("hiroute-worker-{task_key}");
+ let endpoint = format!("http://{}/v1", input.gateway);
+ let route = render_qoder_transient_route(QoderTransientRouteInput {
+ provider_id: &provider_id,
+ endpoint: &endpoint,
+ alias: input.alias,
+ credential_env: "HIROUTE_RUN_TOKEN",
+ context_window_tokens: Some(context_window_tokens),
+ max_output_tokens,
+ })
+ .map_err(|_| DelegationErrorV1::CapabilityUnavailable)?;
+ let settings_file = PathBuf::from("qoder-worker-settings.json");
+ let settings =
+ serde_json::to_vec(&route.settings).map_err(|_| DelegationErrorV1::InvalidArguments)?;
+ let mut rendered = RenderedHarnessProfile {
+ native_model_id: route.native_model_id.clone(),
+ native_args: vec![
+ "--acp".into(),
+ "--config-dir".into(),
+ input.native_context.config_root().to_owned(),
+ "--setting-sources".into(),
+ "user,project,local".into(),
+ "--settings".into(),
+ private_root.join(&settings_file),
+ "--model".into(),
+ route.native_model_id.clone().into(),
+ "--permission-mode".into(),
+ "yolo".into(),
+ // Nested Agent and other model-using tools have no proven frozen-route contract.
+ // Keep the current native tool names explicit instead of granting unknown tools.
+ "--tools".into(),
+ "Read,Write,Edit,Bash,Grep,Glob,Skill".into(),
+ "--strict-mcp-config".into(),
+ "--mcp-config".into(),
+ r#"{"mcpServers":{}}"#.into(),
+ ],
+ files: vec![RunMaterialFile {
+ relative_path: settings_file,
+ contents: Zeroizing::new(settings),
+ executable: false,
+ }],
+ ..Default::default()
+ };
+ for (key, value) in [
+ (
+ "QODER_CONFIG_DIR",
+ path_string(input.native_context.config_root())?,
+ ),
+ ("QODER_MODEL", route.native_model_id.clone()),
+ ("QODER_SUBAGENT_MODEL", route.native_model_id),
+ ("HIROUTE_RUN_TOKEN", secret_string(&input.token)?),
+ ] {
+ rendered.env.insert(key.into(), Zeroizing::new(value));
+ }
+ Ok(rendered)
+}
diff --git a/crates/daemon/src/delegation/profile/tests.rs b/crates/daemon/src/delegation/profile/tests.rs
index 834b84c7..485ca56f 100644
--- a/crates/daemon/src/delegation/profile/tests.rs
+++ b/crates/daemon/src/delegation/profile/tests.rs
@@ -1,5 +1,7 @@
use super::*;
+mod qoder;
+
#[cfg(unix)]
#[test]
fn nested_cli_shebang_resolves_the_selected_node_runtime() {
@@ -11,7 +13,7 @@ fn nested_cli_shebang_resolves_the_selected_node_runtime() {
let harness = fixture.path().join("native-cli");
std::fs::write(&harness, b"#!/usr/bin/env node\n").unwrap();
std::fs::set_permissions(&harness, std::fs::Permissions::from_mode(0o700)).unwrap();
- let path = worker_path(&harness, Some(&node), &harness).unwrap();
+ let path = worker_path(&harness, Some(&node), Some(&harness)).unwrap();
assert_eq!(std::env::split_paths(&path).next().unwrap(), fixture.path());
let result = std::process::Command::new(harness)
.env_clear()
@@ -27,6 +29,11 @@ fn nested_cli_shebang_resolves_the_selected_node_runtime() {
fn isolated_worker_profiles_can_resolve_standard_tools() {
for harness in [WorkerHarnessV1::ClaudeCode, WorkerHarnessV1::CodexCli] {
let profile = request(harness, "private-token");
+ assert_eq!(
+ profile.native_selected_model_id(),
+ "hiroute/1234567890abcdef"
+ );
+ assert!(profile.codex_initialization_root().is_none());
let path = profile.env.get("PATH").expect("worker PATH");
let entries: Vec<_> = std::env::split_paths(path.as_str()).collect();
assert!(entries.iter().all(|entry| entry.is_absolute()));
@@ -130,6 +137,48 @@ fn try_request_at_with_catalog(
session: &TaskSessionRoot,
codex_catalog: Option<&[u8]>,
) -> Result<CandidateWorkerProfile, DelegationErrorV1> {
+ let context = NativeWorkerContext::isolated(private, session.path())?;
+ try_request_in_context(
+ harness,
+ token,
+ alias,
+ permission_policy,
+ private,
+ session,
+ codex_catalog,
+ &context,
+ None,
+ )
+}
+
+#[allow(clippy::too_many_arguments)]
+fn try_request_in_context(
+ harness: WorkerHarnessV1,
+ token: &str,
+ alias: &str,
+ permission_policy: WorkerPermissionPolicyV1,
+ private: &Path,
+ session: &TaskSessionRoot,
+ codex_catalog: Option<&[u8]>,
+ context: &NativeWorkerContext,
+ node_binary: Option<&Path>,
+) -> Result<CandidateWorkerProfile, DelegationErrorV1> {
+ let fixture_cli = session.path().join("selected-claude-fixture");
+ let harness_binary = if harness == WorkerHarnessV1::ClaudeCode && context.is_borrowed() {
+ std::fs::write(
+ &fixture_cli,
+ b"#!/bin/sh\n[ \"$1\" = --version ] || exit 23\nprintf '2.1.231 (Claude Code)\\n'\n",
+ )
+ .unwrap();
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ std::fs::set_permissions(&fixture_cli, std::fs::Permissions::from_mode(0o700)).unwrap();
+ }
+ fixture_cli.as_path()
+ } else {
+ Path::new("/trusted/harness")
+ };
let permit = WorkspaceExecutionPermitV1 {
permit_id: "p".into(),
generation: 1,
@@ -143,13 +192,20 @@ fn try_request_at_with_catalog(
revoked: false,
};
CandidateWorkerProfile::build(ProfileInput {
- claude_context_window: Some(272_000),
+ context_window_tokens: Some(272_000),
+ max_output_tokens: (harness == WorkerHarnessV1::QoderCli).then_some(4096),
harness,
- adapter: Path::new("/trusted/adapter"),
- harness_binary: Path::new("/trusted/harness"),
- node_binary: None,
+ adapter: match harness {
+ WorkerHarnessV1::CodexCli | WorkerHarnessV1::ClaudeCode => {
+ Some(Path::new("/trusted/adapter"))
+ }
+ WorkerHarnessV1::QoderCli => None,
+ },
+ harness_binary,
+ node_binary,
private_root: private,
session_root: session,
+ native_context: context,
workspace: Path::new("/work/a"),
alias,
codex_catalog,
@@ -364,6 +420,258 @@ fn independent_profiles_replace_token_without_reusing_original_credentials() {
}
}
+#[cfg(unix)]
+#[test]
+fn borrowed_codex_keeps_daily_config_and_routes_before_startup_with_task_owned_materials() {
+ use std::os::unix::fs::PermissionsExt;
+ let fixture = private_fixture();
+ let daily_home = fixture.path().join("user's home $(not-a-command)");
+ let config_root = daily_home.join("custom-codex");
+ std::fs::create_dir_all(&config_root).unwrap();
+ let daily_config = b"model_provider = 'hiroute'\n[model_providers.hiroute]\nbase_url = 'https://daily.invalid'\n";
+ std::fs::write(config_root.join("config.toml"), daily_config).unwrap();
+ let context = NativeWorkerContext::borrowed(&daily_home, &config_root).unwrap();
+ let session = TaskSessionRoot::prepare(
+ fixture.path(),
+ &hiroute_domain::WorkspaceId::parse("workspace").unwrap(),
+ "root",
+ "borrowed-task",
+ WorkerHarnessV1::CodexCli,
+ SessionRootUse::New,
+ )
+ .unwrap();
+ let catalog = test_codex_catalog("frozen-alias");
+ let first = try_request_in_context(
+ WorkerHarnessV1::CodexCli,
+ "first-run-secret",
+ "frozen-alias",
+ WorkerPermissionPolicyV1::ApproveAll,
+ &fixture.path().join("first-run"),
+ &session,
+ Some(&catalog),
+ &context,
+ None,
+ )
+ .unwrap();
+ let continued = try_request_in_context(
+ WorkerHarnessV1::CodexCli,
+ "fresh-run-secret",
+ "frozen-alias",
+ WorkerPermissionPolicyV1::ApproveAll,
+ &fixture.path().join("next-run"),
+ &session,
+ Some(&catalog),
+ &context,
+ None,
+ )
+ .unwrap();
+ assert_eq!(first.env["HOME"].as_str(), daily_home.to_str().unwrap());
+ assert_eq!(
+ first.codex_initialization_root(),
+ Some(config_root.as_path())
+ );
+ assert_eq!(
+ continued.codex_initialization_root(),
+ Some(config_root.as_path())
+ );
+ assert_eq!(
+ first.env["CODEX_HOME"].as_str(),
+ config_root.to_str().unwrap()
+ );
+ assert_eq!(first.materials.directories, vec![PathBuf::from("tmp")]);
+ assert_eq!(first.session_root, session.path());
+ assert_eq!(
+ std::fs::read(config_root.join("config.toml")).unwrap(),
+ daily_config
+ );
+ assert!(!session.path().join("config.toml").exists());
+ assert_eq!(
+ std::fs::read(session.path().join("worker-model-catalog.json")).unwrap(),
+ catalog
+ );
+ assert_eq!(first.env["MODEL_PROVIDER"], continued.env["MODEL_PROVIDER"]);
+ assert_ne!(first.env["MODEL_PROVIDER"].as_str(), "hiroute");
+ assert_ne!(first.env["CODEX_PATH"], continued.env["CODEX_PATH"]);
+ assert_eq!(
+ continued.env["HIROUTE_RUN_TOKEN"].as_str(),
+ "fresh-run-secret"
+ );
+ assert!(!continued.env.contains_key("OPENAI_API_KEY"));
+ assert!(!continued.env.contains_key("DEFAULT_AUTH_REQUEST"));
+ let config: Value = serde_json::from_str(first.env["CODEX_CONFIG"].as_str()).unwrap();
+ let provider = config["model_provider"].as_str().unwrap();
+ assert_eq!(
+ config["model_providers"][provider]["env_key"],
+ "HIROUTE_RUN_TOKEN"
+ );
+ assert_eq!(first.materials.files.len(), 1);
+ let launcher = &first.materials.files[0];
+ assert!(launcher.executable);
+ assert_eq!(
+ first.env["CODEX_PATH"].as_str(),
+ first
+ .private_root
+ .join(&launcher.relative_path)
+ .to_str()
+ .unwrap()
+ );
+ assert!(!String::from_utf8_lossy(&launcher.contents).contains("first-run-secret"));
+ assert!(!first.env["CODEX_CONFIG"].contains("first-run-secret"));
+
+ // Execute the actual rendered shell with a fake binary, checking argv before app-server.
+ // The quoted path must remain a single executable and must not run command substitution.
+ let native = daily_home.join("native's cli");
+ std::fs::write(&native, b"#!/bin/sh\nprintf '%s\\0' \"$@\"\n").unwrap();
+ std::fs::set_permissions(&native, std::fs::Permissions::from_mode(0o700)).unwrap();
+ let script = super::codex::render_launcher(&native, &config).unwrap();
+ let script_path = fixture.path().join("launcher");
+ std::fs::write(&script_path, script).unwrap();
+ let output = std::process::Command::new("/bin/sh")
+ .arg(script_path)
+ .arg("app-server")
+ .env_clear()
+ .output()
+ .unwrap();
+ assert!(output.status.success(), "{:?}", output.status);
+ let args = output
+ .stdout
+ .split(|byte| *byte == 0)
+ .filter(|value| !value.is_empty())
+ .map(|value| std::str::from_utf8(value).unwrap())
+ .collect::<Vec<_>>();
+ assert_eq!(args.last(), Some(&"app-server"));
+ assert!(
+ args[..args.len() - 1]
+ .chunks_exact(2)
+ .all(|pair| pair[0] == "-c")
+ );
+ for expected in [
+ "model=\"frozen-alias\"".to_owned(),
+ format!("model_provider=\"{provider}\""),
+ format!("model_providers.{provider}.base_url=\"http://127.0.0.1:44123/v1\""),
+ format!("model_providers.{provider}.env_key=\"HIROUTE_RUN_TOKEN\""),
+ format!("model_providers.{provider}.requires_openai_auth=false"),
+ format!("model_providers.{provider}.supports_websockets=false"),
+ format!("model_catalog_json={}", config["model_catalog_json"]),
+ ] {
+ assert!(
+ args.contains(&expected.as_str()),
+ "missing managed startup override: {expected}"
+ );
+ }
+}
+
+#[cfg(unix)]
+#[test]
+fn borrowed_claude_enables_skills_without_expanding_restricted_permissions() {
+ let fixture = private_fixture();
+ let context =
+ NativeWorkerContext::borrowed(Path::new("/instance-home"), Path::new("/native-claude"))
+ .unwrap();
+ let session = TaskSessionRoot::prepare(
+ fixture.path(),
+ &hiroute_domain::WorkspaceId::parse("workspace").unwrap(),
+ "root",
+ "borrowed-claude",
+ WorkerHarnessV1::ClaudeCode,
+ SessionRootUse::New,
+ )
+ .unwrap();
+ assert!(matches!(
+ try_request_in_context(
+ WorkerHarnessV1::ClaudeCode,
+ "run-only-secret",
+ "frozen-alias",
+ WorkerPermissionPolicyV1::ApproveAll,
+ &fixture.path().join("run-no-node"),
+ &session,
+ None,
+ &context,
+ None,
+ ),
+ Err(DelegationErrorV1::CapabilityUnavailable)
+ ));
+ for policy in [
+ WorkerPermissionPolicyV1::ApproveAll,
+ WorkerPermissionPolicyV1::ApproveReads,
+ WorkerPermissionPolicyV1::DenyAll,
+ ] {
+ let profile = try_request_in_context(
+ WorkerHarnessV1::ClaudeCode,
+ "run-only-secret",
+ "frozen-alias",
+ policy,
+ &fixture.path().join("run"),
+ &session,
+ None,
+ &context,
+ Some(Path::new("/trusted/selected-node")),
+ )
+ .unwrap();
+ assert_eq!(profile.env["HOME"].as_str(), "/instance-home");
+ assert!(profile.codex_initialization_root().is_none());
+ assert_eq!(profile.env["CLAUDE_CONFIG_DIR"].as_str(), "/native-claude");
+ assert_eq!(
+ profile.env["CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST"].as_str(),
+ "1"
+ );
+ assert_eq!(
+ profile.env["ANTHROPIC_CUSTOM_MODEL_OPTION"].as_str(),
+ "frozen-alias"
+ );
+ assert_eq!(profile.env["ANTHROPIC_MODEL"].as_str(), "frozen-alias");
+ assert_eq!(
+ profile.env["ANTHROPIC_AUTH_TOKEN"].as_str(),
+ "run-only-secret"
+ );
+ assert!(!profile.env.contains_key("ANTHROPIC_API_KEY"));
+ assert!(!profile.env.contains_key("CLAUDE_CODE_OAUTH_TOKEN"));
+ assert_eq!(profile.env["NO_PROXY"].as_str(), "127.0.0.1");
+ assert_eq!(profile.env["no_proxy"].as_str(), "127.0.0.1");
+ assert_eq!(profile.materials.directories, vec![PathBuf::from("tmp")]);
+ assert_eq!(profile.executable, Path::new("/trusted/selected-node"));
+ assert_eq!(profile.materials.files.len(), 1);
+ let bootstrap = &profile.materials.files[0];
+ assert!(!bootstrap.executable);
+ assert!(!String::from_utf8_lossy(&bootstrap.contents).contains("run-only-secret"));
+ assert_eq!(
+ profile.args,
+ vec![
+ profile.private_root.join(&bootstrap.relative_path),
+ PathBuf::from("/trusted/adapter")
+ ]
+ );
+ assert!(!profile.env.contains_key("NODE_OPTIONS"));
+ let options = &profile.session_meta["claudeCode"]["options"];
+ assert_eq!(
+ options["settingSources"],
+ json!(["user", "project", "local"])
+ );
+ assert_eq!(options["model"], "frozen-alias");
+ assert_eq!(options["strictMcpConfig"], true);
+ assert_eq!(options["mcpServers"], json!({}));
+ assert_eq!(options["settings"]["disableAllHooks"], true);
+ assert_eq!(options["settings"]["apiKeyHelper"], "");
+ assert_eq!(
+ options["settings"]["env"],
+ json!({"NO_PROXY": "127.0.0.1", "no_proxy": "127.0.0.1"})
+ );
+ assert!(options.get("plugins").is_none());
+ assert!(options.get("hooks").is_none());
+ assert!(!options.to_string().contains("run-only-secret"));
+ let tools = options["tools"].as_array().unwrap();
+ assert_eq!(
+ tools.contains(&json!("Skill")),
+ policy == WorkerPermissionPolicyV1::ApproveAll
+ );
+ if policy == WorkerPermissionPolicyV1::ApproveReads {
+ assert_eq!(tools, &vec![json!("Read"), json!("Glob"), json!("Grep")]);
+ } else if policy == WorkerPermissionPolicyV1::DenyAll {
+ assert!(tools.is_empty());
+ }
+ }
+}
+
#[test]
fn version_or_policy_label_is_not_a_confinement_proof() {
let profile = request(WorkerHarnessV1::CodexCli, "run-secret");
diff --git a/crates/daemon/src/delegation/profile/tests/qoder.rs b/crates/daemon/src/delegation/profile/tests/qoder.rs
new file mode 100644
index 00000000..23dd295e
--- /dev/null
+++ b/crates/daemon/src/delegation/profile/tests/qoder.rs
@@ -0,0 +1,187 @@
+use super::*;
+
+fn session(root: &Path, task: &str) -> TaskSessionRoot {
+ TaskSessionRoot::prepare(
+ root,
+ &hiroute_domain::WorkspaceId::default(),
+ "root",
+ task,
+ WorkerHarnessV1::QoderCli,
+ SessionRootUse::New,
+ )
+ .unwrap()
+}
+
+fn request(
+ root: &Path,
+ session: &TaskSessionRoot,
+ context: &NativeWorkerContext,
+ token: &str,
+ policy: WorkerPermissionPolicyV1,
+) -> Result<CandidateWorkerProfile, DelegationErrorV1> {
+ try_request_in_context(
+ WorkerHarnessV1::QoderCli,
+ token,
+ "plan/branch:cheap",
+ policy,
+ root,
+ session,
+ None,
+ context,
+ None,
+ )
+}
+
+#[test]
+fn native_qoder_uses_selected_cli_shared_resources_and_only_transient_managed_route() {
+ let fixture = private_fixture();
+ let home = fixture.path().join("daily home");
+ let config = home.join("selected-qoder");
+ std::fs::create_dir_all(&config).unwrap();
+ let daily_settings = config.join("settings.json");
+ let before = br#"{"model":{"name":"daily/foreign"},"providers":{"daily":{"baseUrl":"https://daily.invalid"}}}"#;
+ std::fs::write(&daily_settings, before).unwrap();
+ let context = NativeWorkerContext::borrowed(&home, &config).unwrap();
+ let session = session(fixture.path(), "task");
+ let profile = request(
+ &fixture.path().join("run"),
+ &session,
+ &context,
+ "first-run-secret",
+ WorkerPermissionPolicyV1::ApproveAll,
+ )
+ .unwrap();
+ let next = request(
+ &fixture.path().join("continued"),
+ &session,
+ &context,
+ "next-run-secret",
+ WorkerPermissionPolicyV1::ApproveAll,
+ )
+ .unwrap();
+ let another_session = self::session(fixture.path(), "neighbor");
+ let neighbor = request(
+ &fixture.path().join("neighbor-run"),
+ &another_session,
+ &context,
+ "neighbor-secret",
+ WorkerPermissionPolicyV1::ApproveAll,
+ )
+ .unwrap();
+ assert_eq!(profile.executable, Path::new("/trusted/harness"));
+ assert_eq!(profile.env["HOME"].as_str(), home.to_str().unwrap());
+ assert_eq!(
+ profile.env["QODER_CONFIG_DIR"].as_str(),
+ config.to_str().unwrap()
+ );
+ assert!(!profile.env.contains_key("QODER_PERSONAL_ACCESS_TOKEN"));
+ assert!(!profile.env.contains_key("NODE_OPTIONS"));
+ assert_eq!(profile.native_session_mode(), "yolo");
+ assert_eq!(
+ profile.identity_contract,
+ AcpNativeIdentityContract::QoderSessionV1
+ );
+ assert!(profile.codex_initialization_root().is_none());
+ assert!(profile.session_meta.is_empty());
+ assert_eq!(
+ profile.native_selected_model_id(),
+ next.native_selected_model_id()
+ );
+ assert_ne!(
+ profile.native_selected_model_id(),
+ neighbor.native_selected_model_id()
+ );
+ assert!(
+ profile
+ .native_selected_model_id()
+ .ends_with("/plan/branch:cheap")
+ );
+ assert_eq!(
+ profile.env["QODER_MODEL"].as_str(),
+ profile.native_selected_model_id()
+ );
+ assert_eq!(next.env["HIROUTE_RUN_TOKEN"].as_str(), "next-run-secret");
+ assert!(
+ next.env
+ .values()
+ .all(|value| !value.contains("first-run-secret"))
+ );
+ assert_eq!(profile.materials.directories, [PathBuf::from("tmp")]);
+ assert_eq!(profile.materials.files.len(), 1);
+ let material = &profile.materials.files[0];
+ assert!(!material.executable);
+ assert!(!String::from_utf8_lossy(&material.contents).contains("first-run-secret"));
+ let settings: Value = serde_json::from_slice(&material.contents).unwrap();
+ let providers = settings["providers"].as_object().unwrap();
+ assert_eq!(providers.len(), 1);
+ let (provider_id, provider) = providers.iter().next().unwrap();
+ assert_eq!(
+ profile.native_selected_model_id(),
+ format!("{provider_id}/plan/branch:cheap")
+ );
+ assert_eq!(provider["model"], "plan/branch:cheap");
+ assert_eq!(provider["baseUrl"], "http://127.0.0.1:44123/v1");
+ assert_eq!(provider["apiKey"], "${HIROUTE_RUN_TOKEN}");
+ assert_eq!(provider["models"][0]["contextWindow"], 272_000);
+ assert_eq!(provider["models"][0]["maxOutputTokens"], 4096);
+ let continued: Value = serde_json::from_slice(&next.materials.files[0].contents).unwrap();
+ assert_eq!(
+ continued["providers"][provider_id]["models"],
+ provider["models"]
+ );
+ let args = profile
+ .args
+ .iter()
+ .map(|value| value.to_str().unwrap())
+ .collect::<Vec<_>>();
+ assert_eq!(args[0], "--acp");
+ for (flag, value) in [
+ ("--config-dir", config.to_str().unwrap()),
+ ("--setting-sources", "user,project,local"),
+ ("--model", profile.native_selected_model_id()),
+ ("--permission-mode", "yolo"),
+ ("--tools", "Read,Write,Edit,Bash,Grep,Glob,Skill"),
+ ("--mcp-config", r#"{"mcpServers":{}}"#),
+ ] {
+ assert!(args.windows(2).any(|pair| pair == [flag, value]));
+ }
+ assert!(args.contains(&"--strict-mcp-config"));
+ assert!(args.windows(2).any(|pair| pair[0] == "--settings"
+ && Path::new(pair[1]) == profile.private_root.join(&material.relative_path)));
+ assert!(args.iter().all(|arg| !arg.contains("first-run-secret")));
+ assert_eq!(std::fs::read(daily_settings).unwrap(), before);
+}
+
+#[test]
+fn qoder_does_not_upgrade_unproven_restricted_policies_or_accept_an_adapter_runtime() {
+ let fixture = private_fixture();
+ let session = session(fixture.path(), "task");
+ let context =
+ NativeWorkerContext::borrowed(Path::new("/chosen-home"), Path::new("/chosen-config"))
+ .unwrap();
+ for policy in [
+ WorkerPermissionPolicyV1::ApproveReads,
+ WorkerPermissionPolicyV1::DenyAll,
+ ] {
+ let private = fixture.path().join("run");
+ assert!(matches!(
+ request(&private, &session, &context, "secret", policy),
+ Err(DelegationErrorV1::CapabilityUnavailable)
+ ));
+ assert!(!private.exists());
+ }
+ assert!(matches!(
+ try_request_in_context(
+ WorkerHarnessV1::QoderCli,
+ "secret",
+ "plan/branch:cheap",
+ WorkerPermissionPolicyV1::ApproveAll,
+ &fixture.path().join("run"),
+ &session,
+ None,
+ &context,
+ Some(Path::new("/selected-node"))
+ ),
+ Err(DelegationErrorV1::InvalidArguments)
+ ));
+}
diff --git a/crates/daemon/src/delegation/run_authority.rs b/crates/daemon/src/delegation/run_authority.rs
index 4d44e2eb..58643729 100644
--- a/crates/daemon/src/delegation/run_authority.rs
+++ b/crates/daemon/src/delegation/run_authority.rs
@@ -189,16 +189,7 @@ fn build_entry(
|| task.plan.plan_digest != version.reference.content_digest
|| task.plan.exact_reference != exact_reference(&version.reference)
|| task.plan.model_alias != version.compiled.model_alias().as_str()
- || !matches!(
- (task.plan.harness, work.harness),
- (
- hiroute_domain::delegation::WorkerHarnessV1::CodexCli,
- hiroute_domain::delegation::WorkerHarnessV1::CodexCli
- ) | (
- hiroute_domain::delegation::WorkerHarnessV1::ClaudeCode,
- hiroute_domain::delegation::WorkerHarnessV1::ClaudeCode
- )
- )
+ || task.plan.harness != work.harness
|| !verifier.protects_run(run)
{
return Err(DelegationErrorV1::Conflict);
@@ -288,6 +279,7 @@ fn build_entry(
match task.plan.harness {
hiroute_domain::delegation::WorkerHarnessV1::CodexCli => "codex",
hiroute_domain::delegation::WorkerHarnessV1::ClaudeCode => "claude",
+ hiroute_domain::delegation::WorkerHarnessV1::QoderCli => "qoder",
},
task.session
.as_ref()
@@ -360,3 +352,6 @@ fn now_ms() -> Result<u64, DelegationErrorV1> {
.as_millis();
u64::try_from(millis).map_err(|_| DelegationErrorV1::DeadlineExceeded)
}
+
+#[cfg(test)]
+mod tests;
diff --git a/crates/daemon/src/delegation/run_authority/tests.rs b/crates/daemon/src/delegation/run_authority/tests.rs
new file mode 100644
index 00000000..264ddf4f
--- /dev/null
+++ b/crates/daemon/src/delegation/run_authority/tests.rs
@@ -0,0 +1,260 @@
+//! Registration must reach the real exact-plan Gateway authority for every supported Harness.
+use super::*;
+use hiroute_application::delegation::safety::{RunSafetyBinding, RunSafetyProjection};
+use hiroute_application::publication::admission::SharedAdmissionGate;
+use hiroute_domain::delegation::*;
+use hiroute_domain::{
+ AgentPlanAuthoringV2, AgentPlanStrategyV2, CandidateSelectionV1, CapabilityRequirementsV1,
+ ExactNativeReasoningV1, PLAN_AUTHORING_SCHEMA_V2, PlanEditorMode, ReasoningSelectionV1,
+ WorkerPlanV1, WorkspaceId,
+};
+
+use crate::delegation::credentials::{RunCredentialPair, RunCredentialRecord};
+
+fn version(harness: WorkerHarnessV1) -> PlanVersionV1 {
+ let publication: GatewayPublicationV1 = serde_json::from_slice(include_bytes!(
+ "../../../../../e2e/product/fixtures/routing/current-publication.v3.json"
+ ))
+ .unwrap();
+ let compiled = publication
+ .plans
+ .into_iter()
+ .find(|plan| plan.agent_plan_id().as_str() == "plan/custom")
+ .unwrap();
+ let candidates = compiled.body.materialized.attempt_owned.groups[0]
+ .candidates
+ .iter()
+ .map(|candidate| CandidateSelectionV1 {
+ binding_id: candidate.binding_id.clone(),
+ reasoning: match &candidate.exact_reasoning {
+ ExactNativeReasoningV1::Fixed { .. } => None,
+ ExactNativeReasoningV1::Toggle { enabled, .. } => {
+ Some(ReasoningSelectionV1::Toggle { enabled: *enabled })
+ }
+ ExactNativeReasoningV1::Profile { profile, .. } => {
+ Some(ReasoningSelectionV1::Profile {
+ profile: profile.clone(),
+ })
+ }
+ ExactNativeReasoningV1::Budget { tokens, .. } => {
+ Some(ReasoningSelectionV1::Budget { tokens: *tokens })
+ }
+ },
+ })
+ .collect();
+ PlanVersionV1::new(
+ WorkspaceId::default(),
+ AgentPlanAuthoringV2 {
+ schema: PLAN_AUTHORING_SCHEMA_V2.into(),
+ display_name: compiled.body.identity.display_name.clone(),
+ purpose: compiled.body.identity.purpose.clone(),
+ mode: PlanEditorMode::FixedModel,
+ requirements: CapabilityRequirementsV1::default(),
+ limits: compiled.body.materialized.attempt_owned.limits.clone(),
+ strategy: AgentPlanStrategyV2::Custom { candidates },
+ delegation_enabled: true,
+ work: Some(WorkerPlanV1 {
+ harness,
+ protocol: if harness == WorkerHarnessV1::ClaudeCode {
+ AgentIngressProtocolV1::Messages
+ } else {
+ AgentIngressProtocolV1::Responses
+ },
+ }),
+ },
+ compiled,
+ )
+ .unwrap()
+}
+
+struct Fixture {
+ version: Arc<PlanVersionV1>,
+ task: DelegationTaskV1,
+ run: DelegationRunV1,
+ pair: RunCredentialPair,
+ verifier: Arc<RunCredentialVerifier>,
+}
+
+impl Fixture {
+ fn new(harness: WorkerHarnessV1) -> Self {
+ let version = Arc::new(version(harness));
+ let now = now_ms().unwrap();
+ let run = DelegationRunV1 {
+ workspace_id: WorkspaceId::default(),
+ task_id: "task/one".into(),
+ run_id: "run/one".into(),
+ ordinal: 1,
+ continued_from: None,
+ idempotency_key: "start/one".into(),
+ request_digest: CanonicalDigest::of_bytes(b"request"),
+ admission_sequence: 1,
+ accepted_at_ms: Some(now),
+ execution_owner_ref: "delegation-run/run/one".into(),
+ lease_id: "lease/one".into(),
+ daemon_epoch: "epoch".into(),
+ permit_id: "run-config/run/one".into(),
+ permit_generation: 1,
+ configuration: DelegationRunConfigurationV1 {
+ format_version: DELEGATION_RUN_CONFIGURATION_VERSION_V1,
+ scope_id: "run-config/run/one".into(),
+ generation: 1,
+ canonical_workspace_path: "/workspace".into(),
+ permission_policy: WorkerPermissionPolicyV1::ApproveAll,
+ },
+ execution: WorkerExecutionIntentV1 {
+ root_identity: "root".into(),
+ access: WorkspaceAccessV1::TrustedNative,
+ tools: vec![WorkerToolV1::Read],
+ network: WorkerNetworkV1::Allowed,
+ duration_ms: 30_000,
+ delegation_depth: 1,
+ },
+ deadline_ms: now + 30_000,
+ lease_revoked: false,
+ launch_nonce: "launch/one".into(),
+ process: None,
+ session: None,
+ progress: Default::default(),
+ stop_evidence: None,
+ result_body: None,
+ result_incomplete: false,
+ };
+ let task = DelegationTaskV1 {
+ workspace_id: run.workspace_id.clone(),
+ task_id: run.task_id.clone(),
+ parent_task_ref: None,
+ plan: DelegationPlanBindingV1 {
+ authority_id: "test-authority".into(),
+ plan_id: version.reference.plan_id.clone(),
+ plan_revision: version.reference.content_revision,
+ plan_digest: version.reference.content_digest.clone(),
+ publication_revision: 1,
+ publication_digest: CanonicalDigest::of_bytes(b"publication"),
+ exact_reference: exact_reference(&version.reference),
+ model_alias: version.compiled.model_alias().as_str().into(),
+ harness,
+ harness_configuration_digest: CanonicalDigest::of(
+ version.configuration.work.as_ref().unwrap(),
+ )
+ .unwrap(),
+ },
+ workspace: DelegationWorkspaceV1 {
+ root_identity: "root".into(),
+ volume_identity: "volume".into(),
+ ancestry: vec!["root".into()],
+ },
+ created_at_ms: now,
+ latest_run_id: run.run_id.clone(),
+ latest_admission_sequence: 1,
+ title: None,
+ session: None,
+ resume_until_ms: run.deadline_ms,
+ required_body_ids: vec![],
+ body_refs: vec![],
+ native_history_paths: vec![],
+ };
+ let safety = Arc::new(
+ RunSafetyProjection::new(Arc::new(SharedAdmissionGate::new()), "epoch".into()).unwrap(),
+ );
+ safety.finish_startup_recovery();
+ let pair = RunCredentialPair::generate().unwrap();
+ let verifier = Arc::new(
+ RunCredentialVerifier::new(
+ RunCredentialRecord {
+ task_id: run.task_id.clone(),
+ run_id: run.run_id.clone(),
+ lease_id: run.lease_id.clone(),
+ safety: RunSafetyBinding {
+ workspace: run.workspace_id.clone(),
+ daemon_epoch: run.daemon_epoch.clone(),
+ permit_id: run.permit_id.clone(),
+ permit_generation: run.permit_generation,
+ expires_at_ms: run.deadline_ms,
+ },
+ model_alias: task.plan.model_alias.clone(),
+ protocol: version.configuration.work.as_ref().unwrap().protocol,
+ fingerprints: pair.fingerprints(),
+ },
+ safety,
+ )
+ .unwrap(),
+ );
+ Self {
+ version,
+ task,
+ run,
+ pair,
+ verifier,
+ }
+ }
+}
+
+#[test]
+fn every_selected_harness_registers_the_exact_run_and_keeps_credential_boundaries() {
+ for harness in [
+ WorkerHarnessV1::CodexCli,
+ WorkerHarnessV1::ClaudeCode,
+ WorkerHarnessV1::QoderCli,
+ ] {
+ let fixture = Fixture::new(harness);
+ let authority = DelegationRunAuthority::default();
+ authority
+ .register(
+ &fixture.task,
+ &fixture.run,
+ fixture.version.clone(),
+ fixture.verifier.clone(),
+ )
+ .unwrap();
+ let bearer = format!(
+ "Bearer {}",
+ std::str::from_utf8(fixture.pair.model.expose()).unwrap()
+ );
+ let protocol = gateway_protocol(
+ fixture
+ .version
+ .configuration
+ .work
+ .as_ref()
+ .unwrap()
+ .protocol,
+ )
+ .unwrap();
+ let other_protocol = if protocol == IngressProtocol::Responses {
+ IngressProtocol::Messages
+ } else {
+ IngressProtocol::Responses
+ };
+ let verified = authority.authenticate_run(&bearer, protocol).unwrap();
+ assert_eq!(verified.locator().task_id(), fixture.task.task_id);
+ assert_eq!(verified.locator().run_id(), fixture.run.run_id);
+ assert_eq!(
+ verified.locator().exact_plan_reference(),
+ fixture.task.plan.exact_reference
+ );
+ assert!(authority.authenticate_run(&bearer, other_protocol).is_err());
+ let query_bearer = format!(
+ "Bearer {}",
+ std::str::from_utf8(fixture.pair.self_query.expose()).unwrap()
+ );
+ assert!(authority.authenticate_run(&query_bearer, protocol).is_err());
+ fixture.verifier.revoke();
+ assert!(authority.authenticate_run(&bearer, protocol).is_err());
+ }
+}
+
+#[test]
+fn qoder_task_cannot_register_against_a_different_harness_version() {
+ let mut fixture = Fixture::new(WorkerHarnessV1::CodexCli);
+ fixture.task.plan.harness = WorkerHarnessV1::QoderCli;
+ // Keep every digest, exact version and lease unchanged: only the harness is mismatched.
+ assert_eq!(
+ DelegationRunAuthority::default().register(
+ &fixture.task,
+ &fixture.run,
+ fixture.version,
+ fixture.verifier
+ ),
+ Err(DelegationErrorV1::Conflict)
+ );
+}
diff --git a/crates/daemon/tests/local_worker_platform.rs b/crates/daemon/tests/local_worker_platform.rs
index 7171ccf6..12211c02 100644
--- a/crates/daemon/tests/local_worker_platform.rs
+++ b/crates/daemon/tests/local_worker_platform.rs
@@ -25,6 +25,53 @@ fn local_worker_probe() {
std::fs::canonicalize(&cwd).unwrap()
);
assert!(std::env::var("HOME").is_err());
+ if mode == "native-owner" {
+ use std::os::unix::process::CommandExt;
+ tokio::runtime::Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .unwrap()
+ .block_on(async {
+ let mut terminate =
+ tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
+ .unwrap();
+ let mut tool = std::process::Command::new(std::env::current_exe().unwrap())
+ .args(["--exact", "local_worker_probe", "--nocapture"])
+ .env_clear()
+ .env("HIROUTE_PROBE_MODE", "child")
+ .env("HIROUTE_PROBE_CWD", &cwd)
+ .stdin(std::process::Stdio::null())
+ .stdout(std::process::Stdio::null())
+ .process_group(0)
+ .spawn()
+ .unwrap();
+ std::fs::write(cwd.join("child.pid"), tool.id().to_string()).unwrap();
+ std::fs::write(cwd.join("native-ready"), "ready").unwrap();
+ terminate.recv().await.unwrap();
+ // The adapter may already have exited; its native child still needs
+ // time to clean tools outside the original Worker process group.
+ tokio::time::sleep(Duration::from_millis(150)).await;
+ std::fs::write(cwd.join("stop"), "stop").unwrap();
+ tool.wait().unwrap();
+ std::fs::write(cwd.join("native-cleanup"), "complete").unwrap();
+ });
+ return;
+ }
+ if mode == "ignore-term" {
+ tokio::runtime::Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .unwrap()
+ .block_on(async {
+ let _terminate =
+ tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
+ .unwrap();
+ println!("PROBE_READY");
+ std::io::stdout().flush().unwrap();
+ std::future::pending::<()>().await;
+ });
+ return;
+ }
if mode == "child" {
let mut file = std::fs::OpenOptions::new()
.create(true)
@@ -38,17 +85,26 @@ fn local_worker_probe() {
}
return;
}
- let mut child = if mode == "tree" || mode == "root-first" || mode == "cooperate" {
+ let mut child = if ["tree", "root-first", "cooperate", "native-tree"].contains(&mode.as_str()) {
let child = std::process::Command::new(std::env::current_exe().unwrap())
.args(["--exact", "local_worker_probe", "--nocapture"])
.env_clear()
- .env("HIROUTE_PROBE_MODE", "child")
+ .env(
+ "HIROUTE_PROBE_MODE",
+ if mode == "native-tree" {
+ "native-owner"
+ } else {
+ "child"
+ },
+ )
.env("HIROUTE_PROBE_CWD", &cwd)
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.spawn()
.unwrap();
- std::fs::write(cwd.join("child.pid"), child.id().to_string()).unwrap();
+ if mode != "native-tree" {
+ std::fs::write(cwd.join("child.pid"), child.id().to_string()).unwrap();
+ }
for _ in 0..500 {
if cwd.join("heartbeat").exists() {
break;
@@ -217,6 +273,102 @@ async fn local_worker_normal_close_then_stop() {
cancel_tree("cooperate").await;
}
+#[tokio::test]
+async fn local_worker_native_shutdown_reclaims_separate_tool_group_without_stopping_neighbor() {
+ use std::os::unix::fs::DirBuilderExt;
+ let temp = private_tempdir().unwrap();
+ let target = temp.path().join("target");
+ let neighbor = temp.path().join("neighbor");
+ for root in [&target, &neighbor] {
+ std::fs::DirBuilder::new().mode(0o700).create(root).unwrap();
+ }
+ // On a failing assertion, release only these test-owned tools through their
+ // explicit fixture condition, never signal numeric PIDs read from receipt files.
+ struct ReleaseTools(Vec<PathBuf>);
+ impl Drop for ReleaseTools {
+ fn drop(&mut self) {
+ for root in &self.0 {
+ let _ = std::fs::write(root.join("stop"), "stop");
+ }
+ }
+ }
+ let _release = ReleaseTools(vec![target.clone(), neighbor.clone()]);
+ let platform = LocalWorkerPlatform::default();
+ let (a, _ar) = start(
+ &platform,
+ &target.join("run"),
+ &target,
+ "native-a",
+ "native-tree",
+ )
+ .await;
+ let (b, _br) = start(
+ &platform,
+ &neighbor.join("run"),
+ &neighbor,
+ "native-b",
+ "native-tree",
+ )
+ .await;
+ let short = platform.terminate(&a.identity, 20).await.unwrap();
+ assert!(!short.scope_stopped && short.residual_unknown, "{short:?}");
+ assert_eq!(platform.release(&a.identity), Err(DelegationErrorV1::Busy));
+ let result = platform.terminate(&a.identity, 5000).await.unwrap();
+ assert!(
+ result.scope_stopped && !result.residual_unknown,
+ "{result:?}"
+ );
+ assert_eq!(result.scope, WorkerStopScope::ProcessGroup);
+ assert_eq!(
+ std::fs::read_to_string(target.join("native-cleanup")).unwrap(),
+ "complete"
+ );
+ let target_size = std::fs::metadata(target.join("heartbeat")).unwrap().len();
+ let neighbor_size = std::fs::metadata(neighbor.join("heartbeat")).unwrap().len();
+ tokio::time::sleep(Duration::from_millis(80)).await;
+ assert_eq!(
+ std::fs::metadata(target.join("heartbeat")).unwrap().len(),
+ target_size
+ );
+ assert!(std::fs::metadata(neighbor.join("heartbeat")).unwrap().len() > neighbor_size);
+ assert_eq!(
+ platform.observe(&b.identity).await.unwrap(),
+ WorkerObservation::Running
+ );
+ assert!(
+ platform
+ .terminate(&b.identity, 5000)
+ .await
+ .unwrap()
+ .scope_stopped
+ );
+}
+
+#[tokio::test]
+async fn local_worker_native_shutdown_remains_bounded_when_term_is_ignored() {
+ let temp = private_tempdir().unwrap();
+ let platform = LocalWorkerPlatform::default();
+ let (ready, _reader) = start(
+ &platform,
+ &temp.path().join("run"),
+ temp.path(),
+ "ignore",
+ "ignore-term",
+ )
+ .await;
+ let result = tokio::time::timeout(
+ Duration::from_secs(3),
+ platform.terminate(&ready.identity, 2500),
+ )
+ .await
+ .unwrap()
+ .unwrap();
+ assert!(
+ result.scope_stopped && !result.residual_unknown,
+ "{result:?}"
+ );
+}
+
#[tokio::test]
async fn local_worker_identity_isolation_zero_budget_and_restart_unknown() {
let temp = private_tempdir().unwrap();
@@ -258,10 +410,18 @@ async fn local_worker_materials_and_sessions_never_share_ownership() {
req.profile.session_root = session.clone();
req.profile.materials = RunMaterials {
directories: vec!["home".into()],
- files: vec![RunMaterialFile {
- relative_path: "home/opaque".into(),
- contents: Zeroizing::new(b"secret".to_vec()),
- }],
+ files: vec![
+ RunMaterialFile {
+ relative_path: "home/opaque".into(),
+ contents: Zeroizing::new(b"secret".to_vec()),
+ executable: false,
+ },
+ RunMaterialFile {
+ relative_path: "native-launcher".into(),
+ contents: Zeroizing::new(b"#!/bin/sh\nprintf '%s' \"$1\"\n".to_vec()),
+ executable: true,
+ },
+ ],
};
let ready = p.launch(req).await.unwrap();
assert_eq!(std::fs::read(root.join("home/opaque")).unwrap(), b"secret");
@@ -277,6 +437,21 @@ async fn local_worker_materials_and_sessions_never_share_ownership() {
& 0o777,
0o600
);
+ assert_eq!(
+ std::fs::metadata(root.join("native-launcher"))
+ .unwrap()
+ .permissions()
+ .mode()
+ & 0o777,
+ 0o700
+ );
+ let literal = "a path with spaces; $(not-a-command)";
+ let output = std::process::Command::new(root.join("native-launcher"))
+ .arg(literal)
+ .output()
+ .unwrap();
+ assert!(output.status.success());
+ assert_eq!(output.stdout, literal.as_bytes());
assert!(
p.terminate(&ready.identity, 5000)
.await
@@ -312,6 +487,7 @@ async fn local_worker_rejects_paths_existing_root_pin_and_spawn_failure() {
files: vec![RunMaterialFile {
relative_path: path.into(),
contents: Zeroizing::new(vec![]),
+ executable: false,
}],
};
assert!(p.launch(req).await.is_err());
diff --git a/crates/daemon/tests/local_worker_support/mod.rs b/crates/daemon/tests/local_worker_support/mod.rs
index eacfd5c0..4a30ad41 100644
--- a/crates/daemon/tests/local_worker_support/mod.rs
+++ b/crates/daemon/tests/local_worker_support/mod.rs
@@ -1,7 +1,9 @@
use hiroute_daemon::delegation::{
local_worker::LocalWorkerPlatform,
platform::{ReadyWorker, WorkerLaunchRequest, WorkerPlatformPort},
- profile::{CandidateWorkerProfile, ProfileInput, SessionRootUse, TaskSessionRoot},
+ profile::{
+ CandidateWorkerProfile, NativeWorkerContext, ProfileInput, SessionRootUse, TaskSessionRoot,
+ },
};
use hiroute_domain::{ProtectedSecret, delegation::*};
use std::{
@@ -48,13 +50,15 @@ pub fn request(root: &Path, cwd: &Path, nonce: &str, mode: &str) -> WorkerLaunch
.unwrap();
let builder_root = cwd.join(format!("build-{nonce}"));
let mut profile = CandidateWorkerProfile::build(ProfileInput {
- claude_context_window: None,
+ context_window_tokens: None,
+ max_output_tokens: None,
harness: WorkerHarnessV1::CodexCli,
- adapter: &binary,
+ adapter: Some(&binary),
harness_binary: &binary,
node_binary: None,
private_root: &builder_root,
session_root: &session,
+ native_context: &NativeWorkerContext::isolated(&builder_root, session.path()).unwrap(),
workspace: cwd,
alias: "probe",
codex_catalog: None,
diff --git a/crates/daemon/tests/publication_process.rs b/crates/daemon/tests/publication_process.rs
index 4435a2d7..22ceff1c 100644
--- a/crates/daemon/tests/publication_process.rs
+++ b/crates/daemon/tests/publication_process.rs
@@ -6,6 +6,16 @@ fn real_process_publication_crashes_recover_without_reapplying() {
run_script("publication_process.py");
}
+/// Unmanaged native directories may have ordinary user permissions. Only operations that
+/// actually use protected targets should reject them; startup must preserve their contents.
+#[test]
+fn real_process_starts_without_changing_unmanaged_native_directory_permissions() {
+ run_script_case(
+ "publication_process.py",
+ Some("unmanaged-native-permissions"),
+ );
+}
+
#[test]
fn real_process_three_domain_interleavings_preserve_all_accepted_changes() {
run_script("publication_interleaving.py");
@@ -80,6 +90,10 @@ fn real_gateway_native_protocol_usage_populates_home_value() {
}
fn run_script(script: &str) {
+ run_script_case(script, None);
+}
+
+fn run_script_case(script: &str, scenario: Option<&str>) {
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../..")
.canonicalize()
@@ -104,6 +118,7 @@ fn run_script(script: &str) {
.arg("-B")
.arg(root.join("crates/daemon/tests/support").join(script))
.arg(&root)
+ .args(scenario)
.status()
.unwrap();
assert!(result.success(), "production publication scenarios failed");
diff --git a/crates/daemon/tests/support/NATIVE_CONTEXT_BOUNDARIES.md b/crates/daemon/tests/support/NATIVE_CONTEXT_BOUNDARIES.md
new file mode 100644
index 00000000..b6aa86e1
--- /dev/null
+++ b/crates/daemon/tests/support/NATIVE_CONTEXT_BOUNDARIES.md
@@ -0,0 +1,50 @@
+# Borrowed native context: boundary acceptance
+
+`native_context_boundaries.py` complements the two core cases in
+`native_context_product.py`. It reuses the same normal API source, Plan,
+installation selection, public Worker CLI, isolated native roots and synthetic
+Responses/Messages server. It does not build binaries or replace ACP. Run it
+only with the exact candidate binaries and explicitly selected real installations:
+
+```sh
+python3 crates/daemon/tests/support/native_context_boundaries.py \
+ /absolute/candidate/checkout FULL_CANDIDATE_SHA --harness codex
+# Repeat with --harness claude and that harness's selected installation.
+```
+
+Use the managed product runner to prepare the candidate binaries and environment.
+The direct entry consumes `HIROUTE_VALIDATION_PRODUCT_BIN_DIR` and the existing
+`HIROUTE_WORKER_*` installation variables; it never discovers a daily account.
+Its JSON report has required case IDs, per-case outcomes, candidate and binary
+hashes. Process success alone is not a product verdict.
+
+| Stable capability | Smallest useful evidence |
+| --- | --- |
+| `worker.context.native-skills` | Core real Harness case: user and project skill discovery, content and actual shell receipts; conflicting settings and neighboring files unchanged. |
+| `worker.context.concurrent-routing` | Boundary real Harness case: two tasks concurrently run native shell children in one HOME/configuration/workspace, with distinct Plan, source endpoint, source credential, upstream model and native session. Each source rejects the other task's prompt marker. |
+| `worker.context.run-authority` | Existing daemon journal tests: `persistent_journal_streams_result_before_revoking_the_exact_run_credential`, `stop_evidence_reconciles_the_exact_lease_after_formal_cancel_advances_revision`, and `interleaved_runs_are_reconstructable_from_their_own_tokens`. They preserve exact lease/token assertions that model success cannot establish. |
+| `worker.context.exact-continue` | Core immediate/restarted Continue retains native ID and prior tool history after publication of a different source/model; replay sends no request. Boundary removes only the fixture's exact transcript: public Continue must reject, or fail native load without a result, model request, new history or changed neighboring history. |
+| `worker.context.cancel-owned-work` | Boundary formal cancel: target native tool PID disappears and heartbeat stops while the neighbor PID/heartbeat survives and its task succeeds. Keep `local_worker_platform` process-group/root-exit tests for precise OS cleanup failure branches. |
+| `worker.context.retention-ownership` | Daemon consumer tests `deleted_worker_body_revokes_continue_and_cleans_only_owned_metadata` and `expired_worker_body_revokes_continue_and_cleans_only_owned_metadata`: managed-text visibility, actual Continue refusal and maintenance remove only owned metadata while preserving borrowed roots, native history and the neighboring task. This is consumer evidence, not a public delete API or real-Harness deletion verdict. |
+
+The boundary case observes PIDs from its own synthetic scripts but never signals
+those PIDs. Cleanup releases only those scripts and delegates Worker shutdown to
+the product. The missing-history case restores its exact original transcript;
+if a regression creates a replacement, it refuses to overwrite it and retains
+both files for diagnosis. No caller-owned history is removed.
+
+`python3 scripts/test-native-context-boundaries.py` checks the oracle, rejection
+branches and two test-owned shell processes. It starts neither HiRoute nor an
+Agent and cannot satisfy the real-Harness cases. The original delegation product
+lifecycle/progress tests remain useful for public reads, replay and restricted
+policy; their terminal `cancelled` assertion alone cannot prove native tool or
+neighbor isolation. Native macOS Desktop remains a separate real Pilot journey.
+
+Claude setup also writes all uppercase/lowercase HTTP(S)/ALL proxy variables to
+an independent loopback trap in user `settings.json`, with deliberately
+nonmatching `NO_PROXY`/`no_proxy`. Real execution must succeed while
+`assert_preserved(fixture)` verifies both unchanged user bytes and zero proxy
+requests. The trap records only a request marker for every HTTP method, never
+headers, URLs or tokens. The normal model-server lifetime owns it, so the same
+`prepare_desktop` helper preserves this check across real Pilot takeover; its
+`proxy_trap_events` output identifies the synthetic evidence file.
diff --git a/crates/daemon/tests/support/agent_product_support.py b/crates/daemon/tests/support/agent_product_support.py
new file mode 100644
index 00000000..2bb004db
--- /dev/null
+++ b/crates/daemon/tests/support/agent_product_support.py
@@ -0,0 +1,57 @@
+"""Shared product-entry mechanics; native argv, configuration and verdicts stay in leaves."""
+import os
+import signal
+import subprocess
+
+
+def settings_status(product, context):
+ return product.preview('agents connect status', {
+ 'schema_version': {'major': 2, 'minor': 0}, 'context_id': context})
+
+
+def apply_settings(product, spec, key, facet):
+ """Apply the previewed intent and read its authoritative state through the product settings entry."""
+ assert facet in ('model', 'collaboration'), 'unknown settings facet'
+ command = 'agents restore' if spec[facet]['intent'] == 'restore' else 'agents connect'
+ preview = product.preview(command + ' preview', {'spec': spec})
+ assert preview['applicable'], 'settings Preview is blocked; inspect private diagnostics'
+ body = {'spec': preview['spec'], 'accept_digest': preview['accept_digest'],
+ 'dependency_digest': preview['dependency_digest'], 'expected_revisions': preview['expected_revisions'],
+ 'idempotency_key': key}
+ resident = preview.get('resident_service', {})
+ if resident.get('login_item_required'):
+ body['login_item'] = {'before': 'not_registered', 'after': 'enabled', 'created': True}
+ elif resident.get('login_item_removal_required'):
+ body['login_item'] = {'before': 'enabled', 'after': 'not_registered', 'created': False}
+ _, applied = product.cli(command + ' apply', body)
+ assert applied['data']['state'] == 'succeeded', 'settings operation did not succeed'
+ return preview, settings_status(product, spec['context_id'])
+
+
+def run_native_command(product, command, *, timeout, label, env=None):
+ """Capture private output and bound the owned process; success still needs a native oracle."""
+ process = subprocess.Popen(command, env=dict(product.env if env is None else env), cwd=product.project,
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE, start_new_session=True)
+ try:
+ try:
+ stdout, stderr = process.communicate(timeout=timeout)
+ except subprocess.TimeoutExpired:
+ os.killpg(process.pid, signal.SIGTERM)
+ try:
+ stdout, stderr = process.communicate(timeout=3)
+ except subprocess.TimeoutExpired:
+ os.killpg(process.pid, signal.SIGKILL)
+ stdout, stderr = process.communicate(timeout=3)
+ product.outputs.extend((stdout, stderr))
+ raise AssertionError(f'{label} exceeded its deadline') from None
+ product.outputs.extend((stdout, stderr))
+ assert process.returncode == 0, f'{label} failed; inspect private diagnostics'
+ return stdout
+ finally:
+ if process.poll() is None:
+ os.killpg(process.pid, signal.SIGTERM)
+ try:
+ process.wait(timeout=3)
+ except subprocess.TimeoutExpired:
+ os.killpg(process.pid, signal.SIGKILL)
+ process.wait(timeout=3)
diff --git a/crates/daemon/tests/support/delegation_product.py b/crates/daemon/tests/support/delegation_product.py
index dc45cea6..b0328e41 100644
--- a/crates/daemon/tests/support/delegation_product.py
+++ b/crates/daemon/tests/support/delegation_product.py
@@ -29,9 +29,9 @@ def configure_worker_installation(product, harness, adapter, cli, node):
if entry['harness'] == harness)
selection = {
'harness': harness,
- 'adapter_path': str(adapter),
+ **({'adapter_path': str(adapter)} if adapter is not None else {}),
'cli_path': str(cli),
- 'node_path': str(node),
+ **({'node_path': str(node)} if node is not None else {}),
'expected_selection_revision': revision,
}
selected = product.control('SelectWorkerDependencies', selection)
@@ -42,9 +42,9 @@ def configure_worker_installation(product, harness, adapter, cli, node):
if entry['harness'] == harness) == revision + 1, view
assert {
'harness': harness,
- 'adapter_path': str(adapter),
+ **({'adapter_path': str(adapter)} if adapter is not None else {}),
'cli_path': str(cli),
- 'node_path': str(node),
+ **({'node_path': str(node)} if node is not None else {}),
} in view['selected'], view
diff --git a/crates/daemon/tests/support/native_context_boundaries.py b/crates/daemon/tests/support/native_context_boundaries.py
new file mode 100644
index 00000000..cdcb12b2
--- /dev/null
+++ b/crates/daemon/tests/support/native_context_boundaries.py
@@ -0,0 +1,311 @@
+"""Focused real shared-context concurrency/cancellation and missing-history cases.
+
+Reuse the core native context transport and product setup. No fake ACP, database
+edits, deletion API, or private execution port. This entry never builds binaries.
+"""
+import qoder_native_context
+import argparse
+from concurrent.futures import ThreadPoolExecutor
+import copy
+import hashlib
+import json
+import os
+from pathlib import Path
+import shlex
+import subprocess
+import sys
+import time
+
+from delegation_product import configure_worker_installation, wait_for_worker_result, worker_cli
+from native_context_fixture import (NativeContextUpstream, assert_preserved, decision, digest,
+ tool_results, write_new)
+from native_context_product import selected_installation
+from native_context_product import (exact_history, prepare_product, report_failure, save_context_source,
+ wait_for_resumable_task)
+from publication_process import plan_change
+from publication_product import Product
+
+
+CASES = ('worker.context.concurrent-routing', 'worker.context.cancel-owned-work',
+ 'worker.context.exact-continue')
+
+
+def wait_until(check, reason, timeout=30):
+ deadline = time.monotonic() + timeout
+ while True:
+ result = check()
+ if result:
+ return result
+ assert time.monotonic() < deadline, reason
+ time.sleep(.1)
+
+
+def prepare_heartbeat(fixture, role):
+ fixture = copy.deepcopy(fixture)
+ root = Path(fixture['project']) / ('native-context-' + role)
+ root.mkdir(mode=0o700)
+ receipt = role + '-' + fixture['receipt']
+ script = root / 'heartbeat.sh'
+ paths = {name: str(root / name) for name in ('pid', 'heartbeat', 'release', 'done')}
+ write_new(script, '\n'.join((
+ '#!/bin/sh', 'set -eu', 'trap "exit 0" TERM INT',
+ 'printf "%s\\n" "$$" > ' + shlex.quote(paths['pid']), 'iterations=0',
+ 'while [ ! -f ' + shlex.quote(paths['release']) + ' ]; do',
+ ' printf x >> ' + shlex.quote(paths['heartbeat']),
+ ' iterations=$((iterations + 1))',
+ ' [ "$iterations" -lt 900 ] || exit 9', ' sleep 0.1', 'done',
+ 'printf "%s\\n" ' + shlex.quote(receipt) + ' > ' + shlex.quote(paths['done']),
+ 'printf "%s\\n" ' + shlex.quote(receipt), '',
+ )), True)
+ fixture['receipt'] = receipt
+ fixture['boundary'] = dict(paths, role=role, script=str(script),
+ marker='NATIVE-CONTEXT-WORKER-' + role)
+ return fixture
+
+
+def boundary_decision(fixture, body):
+ """Two source oracles reject cross-routing and execute actual native shell children."""
+ state = fixture['boundary']
+ assert state['marker'] in json.dumps(body), 'task reached the other task source'
+ results = tool_results(body, fixture['harness'])
+ heartbeat_id = 'native_context_heartbeat_' + state['role']
+ if heartbeat_id in results:
+ # Codex may return a still-running tool session. The actual script's done
+ # receipt, rather than that adapter-specific result spelling, proves completion.
+ done = Path(state['done'])
+ wait_until(done.exists, 'native tool did not finish after release', timeout=25)
+ assert done.read_text().strip() == fixture['receipt'], 'wrong native child receipt'
+ return {'kind': 'text', 'text': fixture['receipt'], 'continued': False}
+ action = decision(fixture, body)
+ if action['kind'] != 'text':
+ return action
+ names = {tool.get('name') for tool in body.get('tools', [])}
+ command = '/bin/sh ' + shlex.quote(state['script'])
+ if fixture['harness'] in ('claude', 'qoder'):
+ assert 'Bash' in names, 'native Bash tool unavailable'
+ name, arguments = 'Bash', {'command': command, 'timeout': 120000}
+ elif 'exec_command' in names:
+ name, arguments = 'exec_command', {'cmd': command, 'yield_time_ms': 30000,
+ 'max_output_tokens': 1000}
+ else:
+ assert 'shell_command' in names, 'native shell tool unavailable'
+ name, arguments = 'shell_command', {'command': command, 'timeout_ms': 120000}
+ return dict(kind='tool', id=heartbeat_id, name=name, arguments=arguments)
+
+
+def install_oracle(upstream, fixture):
+ (upstream.controls / 'native-context.json').write_text(json.dumps(fixture))
+ upstream.reply = boundary_decision
+
+
+def heartbeat_size(fixture):
+ path = Path(fixture['boundary']['heartbeat'])
+ return path.stat().st_size if path.exists() else 0
+
+
+def running_child(fixture):
+ path = Path(fixture['boundary']['pid'])
+ if not path.exists():
+ return False
+ pid = int(path.read_text())
+ try:
+ os.kill(pid, 0) # Observation only; never signal a PID read from a file.
+ except ProcessLookupError:
+ return False
+ return True
+
+
+def assert_cancelled_child_and_live_neighbor(target, neighbor):
+ wait_until(lambda: not running_child(target), 'cancelled native tool child still exists', 15)
+ target_size, neighbor_size = heartbeat_size(target), heartbeat_size(neighbor)
+ assert target_size > 0 and neighbor_size > 0, 'both real native children must have started'
+ wait_until(lambda: heartbeat_size(neighbor) > neighbor_size,
+ 'neighbor stopped when the other task was cancelled', 5)
+ time.sleep(.3)
+ assert heartbeat_size(target) == target_size, 'cancelled native tool still produces side effects'
+ assert running_child(neighbor), 'neighbor native tool did not survive cancellation'
+
+
+def source_events(upstream):
+ path = upstream.controls / 'native-context-events.jsonl'
+ return [json.loads(line) for line in path.read_text().splitlines()] if path.exists() else []
+
+
+def transcript_snapshot(fixture):
+ root = (qoder_native_context.history_directory(fixture) if fixture['harness'] == 'qoder'
+ else Path(fixture['config']) / ('sessions' if fixture['harness'] == 'codex' else 'projects'))
+ paths = list(root.rglob('*.jsonl'))
+ assert all(not path.is_symlink() for path in paths), 'unexpected linked fixture history'
+ return {str(path): digest(path) for path in paths if path.is_file()}
+
+
+def missing_history_refuses_new_session(product, fixture, task, upstreams):
+ """Move only the exact transcript created by this synthetic task; restore afterward."""
+ path, native_id = exact_history(fixture)
+ path = Path(path)
+ original = path.read_bytes()
+ removed = path.with_suffix('.native-context-held')
+ assert not removed.exists(), 'missing-history fixture would overwrite a neighboring file'
+ before_calls = [upstream.request_count() for upstream in upstreams]
+ path.rename(removed)
+ before_histories = transcript_snapshot(fixture)
+ try:
+ command = ('worker continue --task ' + task['task_id'] + ' --expected-latest-run '
+ + task['run_id'] + ' --run-timeout 30 --no-wait'
+ + ' --submission-key native-context-missing-history --file - --output json')
+ status, response = worker_cli(product, command, 'Continue the same task.', success=False)
+ if status == 0:
+ # Codex owns history discovery: an accepted run may fail during native load.
+ accepted = response['data']
+ result = wait_for_worker_result(product, accepted['run_id'], expected='failed', timeout=45)
+ assert not result.get('result'), 'missing native history produced a replacement result'
+ else:
+ error = response.get('error', {}).get('code', '')
+ # The public envelope intentionally projects ResumeUnavailable to this
+ # capability code; do not assert an internal domain enum on the CLI wire.
+ assert error == 'CAPABILITY_UNAVAILABLE', response
+ assert [upstream.request_count() for upstream in upstreams] == before_calls, \
+ 'missing history sent a model prompt'
+ assert transcript_snapshot(fixture) == before_histories, \
+ 'missing native history created or changed another session'
+ assert not path.exists(), 'missing transcript was silently recreated'
+ assert_preserved(fixture)
+ return {'native_session_id': native_id, 'native_history_restored_after_case': True}
+ finally:
+ assert not path.exists(), 'refusing to overwrite an unexpected replacement transcript'
+ removed.rename(path)
+ assert path.read_bytes() == original
+
+
+def publish_neighbor(product, upstream):
+ saved = save_context_source(product, upstream, variant='native-context-neighbor')
+ change = plan_change(product, 'create', 'native-context-neighbor-plan',
+ display_name='Native context independent neighbor',
+ candidates=[{'binding_id': saved['binding_id']}])
+ preview = product.preview('routing preview', {'change': change})
+ product.apply('routing apply', 'ApplyAgentPlanChange', preview, {'change': change}, 'neighbor-plan')
+ return preview['plan_head']['reference']['plan_id']
+
+
+def submit_concurrent_workers(product, fixtures, plans):
+ """Submit both public requests before waiting for either native tool to start."""
+ def submit(item):
+ fixture, plan = item
+ command = ('worker exec --plan ' + plan + ' --cwd ' + str(product.project)
+ + ' --run-timeout 180 --no-wait --submission-key native-context-'
+ + fixture['boundary']['role'] + ' --file - --output json')
+ prompt = fixture['boundary']['marker'] + ': use both native context skills and run the requested receipt tool.'
+ _, accepted = worker_cli(product, command, prompt)
+ return accepted['data']
+
+ with ThreadPoolExecutor(max_workers=2) as executor:
+ return list(executor.map(submit, zip(fixtures, plans)))
+
+
+def run(repository, candidate, harness):
+ repo = Path(repository).resolve()
+ assert subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=repo, text=True).strip() == candidate
+ product = Product(repo)
+ upstreams, fixtures, runs = [], [], []
+ stage = 'setup'
+ report = dict(scenario='worker-native-context-boundaries', candidate=candidate,
+ worker_harness=harness, required_cases=list(CASES), selected_cases=list(CASES), cases=[],
+ evidence_limit='Real native children and borrowed configuration; synthetic sources; no Desktop verdict')
+ try:
+ base, target_source = prepare_product(product, harness)
+ report['source_context_tokens'] = base['source_context_tokens']
+ upstreams.append(target_source)
+ target = prepare_heartbeat(base, 'target')
+ neighbor = prepare_heartbeat(base, 'neighbor')
+ fixtures.extend((target, neighbor))
+ install_oracle(target_source, target)
+ other_controls = product.root / 'neighbor-upstream'
+ other_controls.mkdir(mode=0o700)
+ neighbor_source = NativeContextUpstream(other_controls)
+ neighbor_source.token = 'different-synthetic-neighbor-source-token'
+ neighbor_source.model = 'gpt-5.5'
+ upstreams.append(neighbor_source)
+ install_oracle(neighbor_source, neighbor)
+ neighbor_plan = publish_neighbor(product, neighbor_source)
+ binary, adapter, node = selected_installation(harness)
+ configure_worker_installation(product, product.worker_work['harness'], adapter, binary, node)
+ # This standalone journey creates its own native roots. No core journey,
+ # native initialization, or completed Worker may warm them before these requests.
+ _, initial = worker_cli(product, 'worker list --output json')
+ assert initial['data']['tasks'] == [], 'expected the first Workers in this fresh fixture'
+ report['native_context_setup'] = ('explicit-borrowed-login-context-concurrent-first-tasks'
+ if harness == 'qoder' else 'fresh-shared-context-concurrent-first-tasks')
+ stage = 'simultaneous-native-tools'
+ runs = submit_concurrent_workers(product, fixtures, (product.plan_id, neighbor_plan))
+ for fixture, run in zip(fixtures, runs):
+ fixture['task_id'] = run['task_id']
+ wait_until(lambda: all(heartbeat_size(item) > 0 and running_child(item) for item in fixtures),
+ 'both real Workers did not execute their native tools concurrently', 120)
+ for fixture, source in zip(fixtures, upstreams):
+ attempts = source_events(source)
+ assert attempts and all(event['state'] == 'green' and event['model'] == source.model
+ for event in attempts), attempts
+ assert_preserved(fixture)
+ assert runs[0]['task_id'] != runs[1]['task_id']
+ report['simultaneous_routes'] = [dict(model=source.model, requests_before_cancel=len(source_events(source)))
+ for source in upstreams]
+ report['cases'].append({'id': CASES[0], 'state': 'green'})
+ stage = 'cancel-target-with-live-neighbor'
+ worker_cli(product, 'worker cancel --run ' + runs[0]['run_id']
+ + ' --idempotency-key native-context-cancel --reason user-requested --output json')
+ wait_for_worker_result(product, runs[0]['run_id'], expected='cancelled', timeout=30)
+ assert_cancelled_child_and_live_neighbor(target, neighbor)
+ Path(neighbor['boundary']['release']).touch()
+ result = wait_for_worker_result(product, runs[1]['run_id'], timeout=45)
+ assert neighbor['receipt'] in result['result']
+ wait_until(lambda: not running_child(neighbor), 'completed neighbor tool still exists', 10)
+ for fixture in fixtures:
+ assert_preserved(fixture)
+ cancelled = dict(target, receipt=target['boundary']['marker'])
+ target_history = (qoder_native_context.cancelled_history(cancelled, runs[0]['run_id'])
+ if harness == 'qoder' else exact_history(cancelled))
+ wait_for_resumable_task(product, runs[1]['task_id'], runs[1]['run_id'])
+ neighbor_history = exact_history(neighbor)
+ assert target_history[1] != neighbor_history[1], 'concurrent tasks shared a native session'
+ report['native_session_ids'] = [target_history[1], neighbor_history[1]]
+ for history in (target_history, neighbor_history):
+ text = Path(history[0]).read_text()
+ assert all(source.token not in text for source in upstreams), 'source credential entered native history'
+ report['cases'].append({'id': CASES[1], 'state': 'green'})
+ report['task_ids'] = [run['task_id'] for run in runs]
+ report['run_ids'] = [run['run_id'] for run in runs]
+ stage = 'missing-native-history'
+ report['missing_history'] = missing_history_refuses_new_session(product, neighbor, runs[1], upstreams)
+ report['cases'].append({'id': CASES[2], 'state': 'green', 'variant': 'missing-history-no-new'})
+ report.update(state='green', binaries={name: digest(product.bin / name) for name in ('hiroute', 'hirouted')},
+ harness_sha256=hashlib.sha256(binary.read_bytes()).hexdigest())
+ product.stop()
+ diagnostics = product.diagnostics_snapshot()
+ assert diagnostics['state'] == 'complete', diagnostics
+ assert diagnostics['level_applied']['level'] == 'debug', diagnostics
+ print(json.dumps(report), flush=True)
+ except Exception:
+ report_failure(product, report, stage)
+ raise
+ finally:
+ # Let our synthetic scripts finish on a failed assertion. Product.stop retains
+ # ownership of actual Worker cancellation; never signal a PID from a fixture file.
+ for fixture in fixtures:
+ Path(fixture['boundary']['release']).touch()
+ try:
+ product.close()
+ finally:
+ try:
+ qoder_native_context.cleanup_context(product)
+ finally:
+ for upstream in upstreams:
+ upstream.close()
+
+
+if __name__ == '__main__':
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument('repository')
+ parser.add_argument('candidate')
+ parser.add_argument('--harness', choices=('codex', 'claude', 'qoder'), required=True)
+ args = parser.parse_args()
+ run(args.repository, args.candidate, args.harness)
diff --git a/crates/daemon/tests/support/native_context_fixture.py b/crates/daemon/tests/support/native_context_fixture.py
new file mode 100644
index 00000000..866ee3e3
--- /dev/null
+++ b/crates/daemon/tests/support/native_context_fixture.py
@@ -0,0 +1,413 @@
+"""Owned receipt skills and protocol oracle for an explicitly selected native context.
+
+The setup CLI creates a NEW private directory for a real Desktop/Pilot journey.
+It does not launch agents, install settings through IPC, or claim a product verdict.
+"""
+import argparse
+import hashlib
+import http.server
+import json
+from pathlib import Path
+import secrets
+import shlex
+import threading
+
+
+BUSINESS_CASES = tuple('worker.context.' + name for name in (
+ 'native-skills', 'concurrent-routing', 'run-authority', 'exact-continue',
+ 'cancel-owned-work', 'retention-ownership'))
+CORE_CASES = (BUSINESS_CASES[0], BUSINESS_CASES[3])
+CONTINUE_PROMPT = 'NATIVE-CONTEXT-CONTINUE: continue the same task using its previous tool history.'
+
+
+def write_new(path, text, executable=False):
+ missing = []
+ parent = path.parent
+ while not parent.exists():
+ missing.append(parent)
+ parent = parent.parent
+ # mkdir(parents=True) ignores mode for intermediate ancestors. Create only
+ # our absent directories privately; never change a borrowed parent's mode.
+ for parent in reversed(missing):
+ parent.mkdir(mode=0o700)
+ with path.open('x', encoding='utf-8') as stream:
+ stream.write(text)
+ path.chmod(0o700 if executable else 0o600)
+
+
+def prepare(home, config, project, harness, suffix='', owned_files=None):
+ """Add only new fixture-owned skills and neighbors; never replace existing files."""
+ assert harness in ('codex', 'claude', 'qoder')
+ home, config, project = map(lambda path: Path(path).resolve(), (home, config, project))
+ def owned_write(path, text, executable=False):
+ write_new(path, text, executable)
+ if owned_files is not None:
+ owned_files[str(path)] = digest(path)
+
+ skills = []
+ for scope, parent in (
+ ('user', home / '.agents/skills' if harness == 'codex' else config / 'skills'),
+ ('project', project / {'codex': '.agents/skills', 'claude': '.claude/skills', 'qoder': '.qoder/skills'}[harness]),
+ ):
+ nonce = secrets.token_hex(12)
+ name = 'native-context-' + scope + suffix
+ directory = parent / name
+ discovery, contents, executed = ('discovery-' + nonce, 'contents-' + nonce, 'executed-' + nonce)
+ script = directory / 'receipt.sh'
+ owned_write(script, '#!/bin/sh\nprintf "%s\\n" ' + shlex.quote(executed) + '\n', True)
+ skill = directory / 'SKILL.md'
+ owned_write(skill, '\n'.join((
+ '---', 'name: ' + name,
+ 'description: Native context read-only receipt ' + discovery, '---', '',
+ 'Read this skill and run its receipt script using the native shell tool.',
+ 'Content receipt: ' + contents, 'Script: ' + str(script), '',
+ )))
+ skills.append(dict(name=name, scope=scope, discovery=discovery, contents=contents,
+ executed=executed, skill=str(skill), script=str(script)))
+ neighbor = config / ('native-context-neighbor' + suffix + '.txt')
+ owned_write(neighbor, 'A neighboring user file must survive Worker cleanup.\n')
+ protected = [neighbor, *(Path(item[key]) for item in skills for key in ('skill', 'script'))]
+ return dict(harness=harness, home=str(home), config=str(config), project=str(project),
+ skills=skills, receipt='completed-' + secrets.token_hex(12),
+ protected={str(path): digest(path) for path in protected})
+
+
+def digest(path):
+ return hashlib.sha256(Path(path).read_bytes()).hexdigest()
+
+
+def protect_configuration(fixture, paths):
+ fixture['protected'].update({str(path): digest(path) for path in paths})
+
+
+def assert_preserved(fixture):
+ if fixture.get('foreign_route_events'):
+ assert not Path(fixture['foreign_route_events']).read_text().strip(), \
+ 'native Worker used the foreign project model route'
+ for path, expected in fixture['protected'].items():
+ assert digest(path) == expected, 'changed native user material: ' + path
+ if fixture.get('proxy_trap_events'):
+ assert not Path(fixture['proxy_trap_events']).read_text().strip(), \
+ 'native Worker used the user-configured proxy'
+
+
+def tool_results(body, harness):
+ """Only correlated tool-result records count, never arbitrary prompt substrings."""
+ if harness in ('codex', 'qoder'):
+ source = body.get('input', [])
+ return {item.get('call_id'): item.get('output', '') for item in source
+ if isinstance(item, dict) and item.get('type') == 'function_call_output'} \
+ if isinstance(source, list) else {}
+ return {block.get('tool_use_id'): block.get('content', '')
+ for message in body.get('messages', [])
+ for block in (message.get('content', []) if isinstance(message.get('content'), list) else [])
+ if isinstance(block, dict) and block.get('type') == 'tool_result'
+ and block.get('is_error') is not True}
+
+
+def qoder_skill_expansions(body, directory):
+ """Read exact native Skill user-message expansions, never a path substring."""
+ expected_header = 'Base directory for this skill: ' + str(directory)
+ for item in body.get('input', []):
+ if not isinstance(item, dict) or item.get('role') != 'user':
+ continue
+ content = item.get('content', [])
+ texts = ([content] if isinstance(content, str) else
+ [part.get('text', '') for part in content if isinstance(part, dict)])
+ for text in texts:
+ header, separator, contents = text.partition('\n\n')
+ if separator and header == expected_header:
+ yield contents
+
+
+def native_text(value):
+ if isinstance(value, str):
+ return value
+ if isinstance(value, list):
+ return '\n'.join(native_text(item) for item in value)
+ if isinstance(value, dict):
+ return '\n'.join(native_text(item) for key, item in value.items()
+ if key in ('text', 'content', 'input', 'instructions', 'output'))
+ return ''
+
+
+def is_native_compaction(body):
+ """Pinned Qoder 1.1.65 request signature, independent of request order."""
+ items = body.get('input', [])
+ last = native_text(items[-1]) if isinstance(items, list) and items else native_text(items)
+ return 'detailed summary' in last.lower() and 'summarization' in last.lower()
+
+
+def decision(fixture, body):
+ """Small deterministic model: require native discovery, then real tools, then history."""
+ harness = fixture['harness']
+ if harness == 'qoder' and 'expected_max_output_tokens' in fixture:
+ assert body.get('max_output_tokens') == fixture['expected_max_output_tokens'], \
+ 'Qoder request did not carry the frozen source output budget'
+ assert harness != 'qoder' or not is_native_compaction(body), \
+ 'unexpected Qoder compaction in the ordinary Skill journey; check the native context budget'
+ rendered = json.dumps(body)
+ results = tool_results(body, harness)
+ result_text = json.dumps(results.get('native_context_execute', ''))
+ if CONTINUE_PROMPT in rendered:
+ # This receipt was only emitted by the prior native shell tool, not by the prompt.
+ assert all(skill['executed'] in result_text for skill in fixture['skills']), \
+ 'Continue did not retain the exact prior tool result'
+ return dict(kind='text', text='continued-' + fixture['receipt'], continued=True)
+ if 'native_context_execute' in results:
+ assert all(skill['contents'] in result_text and skill['executed'] in result_text
+ for skill in fixture['skills']), 'native skill execution receipt mismatch'
+ return dict(kind='text', text=fixture['receipt'], continued=False)
+ for skill in fixture['skills']:
+ assert skill['discovery'] in rendered or skill['contents'] in rendered, \
+ 'native skill discovery missing: ' + skill['scope']
+ names = {tool.get('name') for tool in body.get('tools', [])}
+ if harness in ('claude', 'qoder'):
+ assert 'Skill' in names, 'native Skill tool unavailable'
+ for skill in fixture['skills']:
+ call_id = 'native_context_skill_' + skill['scope']
+ if call_id not in results:
+ return dict(kind='tool', id=call_id, name='Skill',
+ arguments={'skill': skill['name']})
+ # Some native releases expand the body in a following user message rather
+ # than in the Skill tool_result itself. The matching non-error call is still required.
+ assert skill['contents'] in rendered, 'Skill did not load its body'
+ if harness == 'qoder':
+ contents = qoder_skill_expansions(body, Path(skill['skill']).parent)
+ assert any(skill['contents'] in text for text in contents), \
+ 'expected native Skill directory was not loaded'
+ assert 'Bash' in names, 'native Bash tool unavailable'
+ name = 'Bash'
+ else:
+ name = next((name for name in ('exec_command', 'shell_command') if name in names), None)
+ assert name, 'native shell tool unavailable'
+ command = ' && '.join('/bin/cat ' + shlex.quote(skill['skill']) + ' && /bin/sh '
+ + shlex.quote(skill['script']) for skill in fixture['skills'])
+ arguments = ({'cmd': command, 'max_output_tokens': 2000, 'yield_time_ms': 1000}
+ if name == 'exec_command' else {'command': command, 'timeout_ms': 10000}
+ if name == 'shell_command' else {'command': command, 'timeout': 10000})
+ return dict(kind='tool', id='native_context_execute', name=name, arguments=arguments)
+
+
+def events(body, action, protocol):
+ """Use the real native client's declared protocol; no fake ACP adapter."""
+ if protocol == 'messages':
+ tool = action['kind'] == 'tool'
+ block = ({'type': 'tool_use', 'id': action['id'], 'name': action['name'],
+ 'input': action['arguments']} if tool else {'type': 'text', 'text': action['text']})
+ initial = dict(block, input={}) if tool else dict(block, text='')
+ delta = ({'type': 'input_json_delta', 'partial_json': json.dumps(action['arguments'])}
+ if tool else {'type': 'text_delta', 'text': action['text']})
+ return [
+ ('message_start', {'message': {'id': 'msg_native_context', 'type': 'message',
+ 'role': 'assistant', 'model': body['model'], 'content': [], 'stop_reason': None,
+ 'stop_sequence': None, 'usage': {'input_tokens': 1, 'output_tokens': 0}}}),
+ ('content_block_start', {'index': 0, 'content_block': initial}),
+ ('content_block_delta', {'index': 0, 'delta': delta}),
+ ('content_block_stop', {'index': 0}),
+ ('message_delta', {'delta': {'stop_reason': 'tool_use' if tool else 'end_turn',
+ 'stop_sequence': None}, 'usage': {'output_tokens': 1}}),
+ ('message_stop', {}),
+ ]
+ item = ({'type': 'function_call', 'id': 'fc_' + action['id'], 'call_id': action['id'],
+ 'name': action['name'], 'arguments': json.dumps(action['arguments']), 'status': 'completed'}
+ if action['kind'] == 'tool' else
+ {'type': 'message', 'id': 'msg_native_context', 'role': 'assistant', 'status': 'completed',
+ 'content': [{'type': 'output_text', 'text': action['text'], 'annotations': []}]})
+ response = {'id': 'resp_native_context', 'object': 'response', 'model': body['model'],
+ 'status': 'completed', 'output': [item],
+ 'usage': {'input_tokens': action.get('input_tokens', 1), 'output_tokens': 1,
+ 'total_tokens': action.get('input_tokens', 1) + 1}}
+ added = dict(item, status='in_progress')
+ added['arguments' if action['kind'] == 'tool' else 'content'] = '' if action['kind'] == 'tool' else []
+ middle = ([('response.function_call_arguments.delta', {'item_id': item['id'],
+ 'output_index': 0, 'delta': item['arguments']}),
+ ('response.function_call_arguments.done', {'item_id': item['id'],
+ 'output_index': 0, 'arguments': item['arguments']})]
+ if action['kind'] == 'tool' else [
+ ('response.content_part.added', {'item_id': item['id'], 'output_index': 0,
+ 'content_index': 0, 'part': {'type': 'output_text', 'text': '', 'annotations': []}}),
+ ('response.output_text.delta', {'item_id': item['id'], 'output_index': 0,
+ 'content_index': 0, 'delta': action['text']}),
+ ('response.output_text.done', {'item_id': item['id'], 'output_index': 0,
+ 'content_index': 0, 'text': action['text']})])
+ return [('response.created', {'response': dict(response, status='in_progress', output=[])}),
+ ('response.output_item.added', {'output_index': 0, 'item': added}), *middle,
+ ('response.output_item.done', {'output_index': 0, 'item': item}),
+ ('response.completed', {'response': response})]
+
+
+def handle(handler, body, controls, lock, reply=decision):
+ path = controls / 'native-context.json'
+ if not path.exists():
+ return False
+ fixture = json.loads(path.read_text())
+ protocol = 'messages' if handler.path == '/v1/messages' else 'responses'
+ try:
+ action = reply(fixture, body)
+ except AssertionError as error:
+ with lock, (controls / 'native-context-events.jsonl').open('a') as stream:
+ stream.write(json.dumps({'state': 'red', 'reason': str(error)}) + '\n')
+ handler.send({'error': {'message': str(error), 'type': 'invalid_request_error'}}, 400)
+ return True
+ with lock, (controls / 'native-context-events.jsonl').open('a') as stream:
+ stream.write(json.dumps({'state': 'green', 'action': action['kind'],
+ 'call_id': action.get('id'), 'continued': action.get('continued'),
+ 'model': body['model'], 'protocol': protocol,
+ **({'request_kind': action['request_kind']} if 'request_kind' in action else {})}) + '\n')
+ handler.send_messages_stream(events(body, action, protocol))
+ return True
+
+
+class NativeProxyTrap:
+ """Count every proxy method without recording URLs, headers, bodies or credentials."""
+
+ def __init__(self, path):
+ self.path = Path(path)
+ write_new(self.path, '')
+ lock = threading.Lock()
+ owner = self
+
+ class Handler(http.server.BaseHTTPRequestHandler):
+ def log_message(self, *_):
+ pass
+
+ def reject_proxy(self):
+ with lock, owner.path.open('a') as stream:
+ stream.write('proxy-request\n')
+ self.send_response(502)
+ self.send_header('Content-Length', '0')
+ self.send_header('Connection', 'close')
+ self.end_headers()
+ self.close_connection = True
+
+ def __getattr__(self, name):
+ # BaseHTTPRequestHandler dispatches even custom methods through
+ # do_<method>; count those too, without retaining request content.
+ if name.startswith('do_'):
+ return self.reject_proxy
+ raise AttributeError(name)
+
+ self.server = http.server.ThreadingHTTPServer(('127.0.0.1', 0), Handler)
+ self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)
+ self.thread.start()
+ self.url = 'http://%s:%d' % self.server.server_address
+
+ def close(self):
+ self.server.shutdown()
+ self.server.server_close()
+ self.thread.join(timeout=5)
+
+
+def install_proxy_conflict(fixture, upstream):
+ """Keep the proxy alive with the model fixture, including real Pilot takeover."""
+ assert fixture['harness'] == 'claude'
+ assert upstream.proxy_trap is None
+ trap = NativeProxyTrap(upstream.controls / 'native-context-proxy-attempts.log')
+ upstream.proxy_trap = trap
+ fixture['proxy_trap_events'] = str(trap.path)
+ return {**{name: trap.url for name in ('HTTP_PROXY', 'HTTPS_PROXY', 'ALL_PROXY',
+ 'http_proxy', 'https_proxy', 'all_proxy')},
+ 'NO_PROXY': 'synthetic-no-bypass.invalid', 'no_proxy': 'synthetic-no-bypass.invalid'}
+
+
+class NativeContextUpstream:
+ """Loopback model server shared by headless and real Desktop journeys."""
+ token = 'synthetic-native-context-source-token'
+ model = 'gpt-5.4'
+
+ def __init__(self, controls):
+ owner = self
+ self.controls = Path(controls)
+ self.lock = threading.Lock()
+ self.reply = decision
+ self.requests = 0
+ self.proxy_trap = None
+
+ class Handler(http.server.BaseHTTPRequestHandler):
+ protocol_version = 'HTTP/1.1'
+
+ def log_message(self, *_):
+ pass
+
+ def send(self, value, status=200):
+ body = json.dumps(value).encode()
+ self.send_response(status)
+ self.send_header('Content-Type', 'application/json')
+ self.send_header('Content-Length', str(len(body)))
+ self.send_header('Connection', 'close')
+ self.close_connection = True
+ self.end_headers()
+ self.wfile.write(body)
+
+ def do_GET(self):
+ # A manually declared model remains usable without directory discovery.
+ self.send({'error': 'directory not implemented'}, 404)
+
+ def do_POST(self):
+ with owner.lock:
+ owner.requests += 1
+ if self.headers.get('Authorization') != 'Bearer ' + owner.token:
+ return self.send({'error': 'incorrect synthetic source credential'}, 401)
+ if self.path not in ('/v1/responses', '/v1/messages'):
+ return self.send({'error': 'incorrect source endpoint'}, 404)
+ body = json.loads(self.rfile.read(int(self.headers['Content-Length'])))
+ if body.get('model') != owner.model:
+ return self.send({'error': 'incorrect source model'}, 400)
+ if not handle(self, body, owner.controls, owner.lock, owner.reply):
+ self.send({'error': 'native context fixture is not prepared'}, 503)
+
+ def send_messages_stream(self, frames):
+ encoded = []
+ for index, (kind, value) in enumerate(frames):
+ payload = dict(value, type=kind)
+ if self.path == '/v1/responses':
+ payload['sequence_number'] = index
+ encoded.append(f'event: {kind}\ndata: {json.dumps(payload)}\n\n'.encode())
+ self.send_response(200)
+ self.send_header('Content-Type', 'text/event-stream')
+ self.send_header('Content-Length', str(sum(map(len, encoded))))
+ self.end_headers()
+ for frame in encoded:
+ self.wfile.write(frame)
+ self.wfile.flush()
+
+ self.server = http.server.ThreadingHTTPServer(('127.0.0.1', 0), Handler)
+ self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)
+ self.thread.start()
+ self.base_url = 'http://%s:%d/v1' % self.server.server_address
+
+ def request_count(self):
+ """All source attempts, including rejected credentials; never record a secret."""
+ with self.lock:
+ return self.requests
+
+ def close(self):
+ try:
+ self.server.shutdown()
+ self.server.server_close()
+ self.thread.join(timeout=5)
+ finally:
+ if self.proxy_trap:
+ self.proxy_trap.close()
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument('--root', type=Path, required=True, help='new private synthetic context root')
+ parser.add_argument('--harness', choices=('codex', 'claude'), required=True)
+ args = parser.parse_args()
+ root = args.root.resolve()
+ root.mkdir(mode=0o700) # Refuse any existing directory: never adopt daily user material.
+ home, project = root / 'home', root / 'project'
+ home.mkdir(mode=0o700)
+ project.mkdir(mode=0o700)
+ config = home / ('.codex' if args.harness == 'codex' else '.claude')
+ fixture = prepare(home, config, project, args.harness)
+ write_new(root / 'native-context.json', json.dumps(fixture, indent=2) + '\n')
+ print(json.dumps({'state': 'prepared', 'harness': args.harness, 'process_home': str(home),
+ 'workspace': str(project), 'fixture': str(root / 'native-context.json')}))
+
+
+if __name__ == '__main__':
+ main()
diff --git a/crates/daemon/tests/support/native_context_product.py b/crates/daemon/tests/support/native_context_product.py
new file mode 100644
index 00000000..ba7fa710
--- /dev/null
+++ b/crates/daemon/tests/support/native_context_product.py
@@ -0,0 +1,387 @@
+"""Real installed Worker/native context journey with a deterministic model upstream.
+
+Requires the same exact-candidate binaries and selected native installations as
+delegation_product.py. No business SQL, private execution port, or replacement ACP.
+"""
+import argparse
+import hashlib
+import json
+import os
+from pathlib import Path
+import signal
+import subprocess
+import sys
+import time
+
+from delegation_product import configure_worker_installation
+from delegation_product import wait_for_worker_result, worker_cli
+from native_context_fixture import (BUSINESS_CASES, CORE_CASES, CONTINUE_PROMPT, NativeContextUpstream,
+ assert_preserved, install_proxy_conflict, prepare, protect_configuration)
+from model_connections_product import save_native_source
+from publication_product import Product
+from publication_process import plan_change
+import qoder_native_context
+
+
+def save_context_source(product, upstream, variant='', context_tokens=None):
+ """Declare a source budget supported by the selected native client contract."""
+ protocol = product.worker_work['protocol']
+ return save_native_source(product, upstream, token=upstream.token, protocol=protocol,
+ upstream_model_id=upstream.model, variant=variant,
+ context_tokens=context_tokens if context_tokens is not None else
+ native_context_budget(product))
+
+
+def native_context_budget(product):
+ if product.worker_work.get('harness') == 'qoder_cli':
+ # Ordinary collaboration/cancellation use a roomy budget. The core
+ # journey separately supplies 32768/4096 to test native budget projection.
+ return 100_000
+ return 200_000 if product.worker_work['protocol'] == 'messages' else 32_768
+
+
+def selected_installation(harness):
+ binary = Path(os.environ['HIROUTE_WORKER_' + harness.upper() + '_BINARY']).resolve(strict=True)
+ if harness == 'qoder':
+ return binary, None, None
+ adapter = Path(os.environ['HIROUTE_WORKER_' + harness.upper() + '_ACP_ADAPTER']).resolve(strict=True)
+ node = Path(os.environ['HIROUTE_WORKER_NODE']).resolve(strict=True)
+ return binary, adapter, node
+
+
+def prepare_product(product, harness, context_tokens=None):
+ """Prepare a normal API source/Plan; Desktop can take over after product.stop()."""
+ product.enable_debug_diagnostics()
+ roots = {'codex': 'CODEX_HOME', 'claude': 'CLAUDE_CONFIG_DIR', 'qoder': 'QODER_CONFIG_DIR'}
+ if harness == 'qoder':
+ qoder_native_context.select_context(product)
+ fixture = qoder_native_context.prepare_context(product)
+ else:
+ fixture = prepare(Path(product.env['HOME']), Path(product.env[roots[harness]]),
+ product.project, harness)
+ native = Path(product.env[roots[harness]])
+ product.worker_work = {'harness': {'codex': 'codex_cli', 'claude': 'claude_code',
+ 'qoder': 'qoder_cli'}[harness],
+ 'protocol': 'messages' if harness == 'claude' else 'responses'}
+ fixture['source_context_tokens'] = (context_tokens if context_tokens is not None
+ else native_context_budget(product))
+ upstream = NativeContextUpstream(product.root)
+ try:
+ product.start()
+ saved = save_context_source(product, upstream, context_tokens=context_tokens)
+ product.editor = {
+ 'schema': 'hiroute.plan-editor/v2', 'display_name': 'Native Worker context',
+ 'purpose': 'Read native user and project skills', 'mode': 'fixed_model',
+ 'candidates': [{'binding_id': saved['binding_id']}],
+ 'smart': {'economy': [], 'primary': [], 'primary_fallback': False,
+ 'reselect_on_user_message': False, 'classifier': {'kind': 'local_rules'},
+ 'complex_keywords': []},
+ 'free': {'candidates': [], 'primary': [], 'primary_fallback': False},
+ 'delegation_enabled': True, 'work': product.worker_work, 'requirements': {},
+ 'limits': {'maximum_attempts': 1, 'request_timeout_ms': 30000, 'attempt_timeout_ms': 30000},
+ }
+ change = plan_change(product, 'create', 'native-context-plan')
+ preview = product.preview('routing preview', {'change': change})
+ product.apply('routing apply', 'ApplyAgentPlanChange', preview, {'change': change}, 'native-worker-plan')
+ product.plan_id = preview['plan_head']['reference']['plan_id']
+ product.model_alias = preview['plan_head']['model_alias']
+ configuration = native / ('config.toml' if harness == 'codex' else 'settings.json')
+ if harness == 'codex':
+ configuration.write_text('model = "gpt-5.5"\nmodel_provider = "native_context_ambient"\n'
+ '[model_providers.native_context_ambient]\nname = "Unreachable synthetic source"\n'
+ 'base_url = "http://127.0.0.1:9/v1"\nwire_api = "responses"\n'
+ 'env_key = "NATIVE_CONTEXT_UNUSED_TOKEN"\nrequires_openai_auth = false\n')
+ elif harness == 'qoder':
+ qoder_native_context.install_project_conflict(fixture, upstream)
+ elif harness == 'claude':
+ configuration.write_text(json.dumps({'env': {'ANTHROPIC_BASE_URL': 'http://127.0.0.1:9',
+ 'ANTHROPIC_AUTH_TOKEN': 'synthetic-ambient-must-not-authorize-worker',
+ 'ANTHROPIC_MODEL': 'synthetic-wrong-model',
+ **install_proxy_conflict(fixture, upstream)}}))
+ if harness != 'qoder':
+ configuration.chmod(0o600)
+ protect_configuration(fixture, [configuration])
+ fixture['plan_id'] = product.plan_id
+ fixture['model_alias'] = product.model_alias
+ (product.root / 'native-context.json').write_text(json.dumps(fixture))
+ return fixture, upstream
+ except Exception:
+ upstream.close()
+ raise
+
+
+def publish_replacement_route(product, fixture):
+ """Publish a distinguishable route; existing tasks must retain their original route."""
+ controls = product.root / 'replacement-native-context-source'
+ controls.mkdir(mode=0o700)
+ (controls / 'native-context.json').write_text(json.dumps(fixture))
+ upstream = NativeContextUpstream(controls)
+ upstream.model = 'gpt-5.5'
+ upstream.token = 'synthetic-replacement-native-context-source-token'
+ try:
+ saved = save_context_source(product, upstream, variant='native-context-replacement')
+ change = plan_change(product, 'update', display_name='Published replacement Worker route',
+ candidates=[{'binding_id': saved['binding_id']}],
+ delegation_enabled=True, work=product.worker_work)
+ preview = product.preview('routing preview', {'change': change})
+ product.apply('routing apply', 'ApplyAgentPlanChange', preview,
+ {'change': change}, 'native-plan-update')
+ return upstream
+ except Exception:
+ upstream.close()
+ raise
+
+
+def assert_frozen_route(original_events, before, replacement):
+ """Require actual requests to the old route and no requests to the new route."""
+ requests = original_events[before:]
+ assert requests and all(event['state'] == 'green' for event in requests), \
+ 'Continue did not use the original source'
+ assert any(event.get('continued') is True for event in requests), \
+ 'original source did not receive the resumed native history'
+ replacement_log = replacement.controls / 'native-context-events.jsonl'
+ assert not replacement_log.exists() or not replacement_log.read_text().strip(), \
+ 'existing task used the newly published route'
+ assert replacement.request_count() == 0, 'existing task sent a model request to the newly published route'
+
+
+def exact_history(fixture):
+ """Inspect only this synthetic context's native transcript directory, never auth."""
+ if fixture['harness'] == 'qoder':
+ return qoder_native_context.exact_history(fixture)
+ folder = Path(fixture['config']) / ('sessions' if fixture['harness'] == 'codex' else 'projects')
+ matches = []
+ for path in folder.rglob('*.jsonl'):
+ assert not path.is_symlink(), 'unexpected linked fixture history'
+ text = path.read_text()
+ if fixture['receipt'] not in text:
+ continue
+ identities = set()
+ for line in text.splitlines():
+ row = json.loads(line)
+ identity = (row.get('payload', {}).get('id') if row.get('type') == 'session_meta'
+ else row.get('sessionId') if fixture['harness'] == 'claude' else None)
+ if identity:
+ identities.add(identity)
+ assert len(identities) == 1, 'native transcript has ambiguous session identity'
+ matches.append((str(path), identities.pop()))
+ assert len(matches) == 1, 'expected exactly the task native transcript in borrowed context'
+ return matches[0]
+
+
+def events(product):
+ return [json.loads(line) for line in
+ (product.root / 'native-context-events.jsonl').read_text().splitlines()]
+
+
+def task_plan_revision(product, task_id):
+ _, response = worker_cli(product, 'worker list --output json')
+ task = next(task for task in response['data']['tasks'] if task['task_id'] == task_id)
+ return task['plan_revision']
+
+
+def wait_for_resumable_task(product, task_id, run_id, timeout=10):
+ """Read public finalization readiness before inspecting native disk evidence."""
+ deadline = time.monotonic() + timeout
+ while True:
+ _, response = worker_cli(product, 'worker list --output json')
+ task = next((item for item in response['data']['tasks'] if item['task_id'] == task_id), None)
+ if task:
+ assert task['latest_run_id'] == run_id, 'another run replaced the expected latest run'
+ if (task['run']['state'] == 'succeeded' and task['run']['cleanup'] == 'complete'
+ and (task['resumable_until_ms'] or 0) > int(time.time() * 1000)):
+ return task
+ assert time.monotonic() < deadline, ('native continuation did not become ready', task)
+ time.sleep(.05)
+
+
+def report_failure(product, report, stage):
+ """Preserve this journey's current daemon diagnostics before fixture cleanup."""
+ try:
+ product.stop()
+ stopped = 'stopped'
+ except Exception:
+ stopped = 'failed'
+ evidence = product.repo / 'target/product-e2e-evidence' / (
+ report['scenario'] + '-' + report['worker_harness'] + '-' + str(os.getpid()))
+ report.update(state='red', stage=stage, daemon_stop_state=stopped)
+ try:
+ report['diagnostics'] = product.preserve_diagnostics(evidence)
+ except OSError:
+ # Diagnostics are secondary evidence; never replace the original failure or
+ # emit raw paths/exception content that could contain sensitive material.
+ report['diagnostics'] = {'state': 'unavailable', 'reason': 'diagnostics_io'}
+ print(json.dumps(report), flush=True)
+
+
+def run(repository, candidate):
+ repo = Path(repository).resolve()
+ assert subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=repo, text=True).strip() == candidate
+ harness = os.environ['HIROUTE_PRODUCT_WORKER_HARNESS']
+ assert harness in ('codex', 'claude', 'qoder')
+ product = Product(repo)
+ # Headless services may explicitly select a non-default native configuration.
+ # Mac Pilot intentionally uses its documented HOME/.codex and HOME/.claude roots.
+ if harness != 'qoder':
+ product.env['CODEX_HOME' if harness == 'codex' else 'CLAUDE_CONFIG_DIR'] = str(
+ Path(product.env['HOME']) / ('selected-' + harness + '-config'))
+ upstream = replacement = None
+ stage = 'prepare-native-context'
+ report = dict(scenario='worker-native-context-core', candidate=candidate, worker_harness=harness,
+ required_cases=list(CORE_CASES), selected_cases=list(CORE_CASES), cases=[],
+ evidence_limit='Real native Harness and daemon; controlled upstream; no Desktop verdict',
+ related_contracts=[{'id': case, 'state': 'not_executed'}
+ for case in BUSINESS_CASES if case not in CORE_CASES])
+ try:
+ binary, adapter, node = selected_installation(harness)
+ stage = 'real-daemon-and-plan'
+ fixture, upstream = prepare_product(product, harness,
+ context_tokens=32_768 if harness == 'qoder' else None)
+ report['source_context_tokens'] = fixture['source_context_tokens']
+ if harness == 'qoder':
+ fixture['expected_max_output_tokens'] = 4096
+ report['source_output_tokens'] = 4096
+ (product.root / 'native-context.json').write_text(json.dumps(fixture))
+ configure_worker_installation(product, product.worker_work['harness'], adapter, binary, node)
+ if harness == 'qoder':
+ stage = 'unsupported-qoder-permissions'
+ report['rejected_permission_modes'] = qoder_native_context.assert_restricted_modes_unavailable(product, upstream)
+ stage = 'native-skills'
+ prompt = 'Use ' + ' and '.join(skill['name'] for skill in fixture['skills']) + ' to produce their read-only receipts.'
+ command = ('worker exec --plan ' + product.plan_id + ' --cwd ' + str(product.project)
+ + ' --run-timeout 120 --no-wait --submission-key native-context-start --file - --output json')
+ _, accepted = worker_cli(product, command, prompt)
+ first = accepted['data']
+ fixture['task_id'] = first['task_id']
+ result = wait_for_worker_result(product, first['run_id'], timeout=150)
+ assert fixture['receipt'] in result['result'], 'missing native skill execution receipt'
+ history = None
+ report['task_id'] = first['task_id']
+ report['run_ids'] = [first['run_id']]
+ # Submit the first Continue immediately after result: no readiness probe,
+ # native file wait or retry may hide the product's finalization contract.
+ for restart in (False, True):
+ stage = 'continue-after-restart' if restart else 'immediate-continue'
+ if restart:
+ replacement = publish_replacement_route(product, fixture)
+ product.stop()
+ if harness == 'qoder':
+ qoder_native_context.replace_current_context(product)
+ product.start()
+ before_requests = len(events(product))
+ command = ('worker continue --task ' + first['task_id'] + ' --expected-latest-run '
+ + report['run_ids'][-1] + ' --run-timeout 120 --no-wait --submission-key '
+ + ('native-context-reopen' if restart else 'native-context-continue')
+ + ' --file - --output json')
+ _, accepted = worker_cli(product, command, CONTINUE_PROMPT)
+ continued = accepted['data']
+ assert continued['task_id'] == first['task_id']
+ assert continued['run_id'] not in report['run_ids'] and not continued['replayed']
+ result = wait_for_worker_result(product, continued['run_id'], timeout=150)
+ assert 'continued-' + fixture['receipt'] in result['result']
+ ready = wait_for_resumable_task(product, first['task_id'], continued['run_id'])
+ current_history = exact_history(fixture)
+ if restart:
+ assert current_history == history, 'Continue changed native session or transcript'
+ assert ready['plan_revision'] == report['frozen_plan_revision']
+ assert_frozen_route(events(product), before_requests, replacement)
+ report['continued_after_route_replacement'] = True
+ else:
+ # The oracle required the first run's real tool history. Both turns
+ # must now occupy one native transcript; a replacement is ambiguous.
+ history = current_history
+ report['native_session_id'] = history[1]
+ report['frozen_plan_revision'] = ready['plan_revision']
+ report['cases'].append({'id': CORE_CASES[0], 'state': 'green'})
+ assert_preserved(fixture)
+ report['run_ids'].append(continued['run_id'])
+ replay_sources = [source for source in (upstream, replacement) if source is not None]
+ before = [source.request_count() for source in replay_sources]
+ _, replay = worker_cli(product, command, CONTINUE_PROMPT)
+ assert replay['data']['replayed'] and replay['data']['run_id'] == continued['run_id']
+ assert [source.request_count() for source in replay_sources] == before, \
+ 'Continue replay sent another model request'
+ report['cases'].append({'id': CORE_CASES[1], 'state': 'green'})
+ attempts = events(product)
+ if fixture.get('proxy_trap_events'):
+ report['native_proxy_requests'] = len(Path(fixture['proxy_trap_events']).read_text().splitlines())
+ assert report['native_proxy_requests'] == 0, 'native Worker used the user-configured proxy'
+ assert attempts and all(event['state'] == 'green' for event in attempts)
+ assert sum(event.get('continued') is True for event in attempts) == 2
+ if harness == 'qoder':
+ qoder_native_context.assert_settings_preserved(fixture)
+ report['foreign_project_requests'] = len(Path(fixture['foreign_route_events']).read_text().splitlines())
+ if harness != 'qoder':
+ report['conflicting_settings_unchanged'] = True
+ report.update(state='green', native_settings_unchanged=True,
+ neighboring_material_preserved=True, upstream_requests=len(attempts),
+ binaries={name: hashlib.sha256((product.bin / name).read_bytes()).hexdigest()
+ for name in ('hiroute', 'hirouted')},
+ harness_sha256=hashlib.sha256(binary.read_bytes()).hexdigest())
+ product.stop()
+ diagnostics = product.diagnostics_snapshot()
+ assert diagnostics['state'] == 'complete', diagnostics
+ assert diagnostics['level_applied']['level'] == 'debug', diagnostics
+ print(json.dumps(report), flush=True)
+ except Exception:
+ report_failure(product, report, stage)
+ raise
+ finally:
+ try:
+ product.close()
+ finally:
+ try:
+ qoder_native_context.cleanup_context(product)
+ finally:
+ if upstream:
+ upstream.close()
+ if replacement:
+ replacement.close()
+
+
+def prepare_desktop(repository, candidate, root, harness):
+ """Keep only the independent model server alive for a real Pilot takeover."""
+ repo = Path(repository).resolve()
+ assert subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=repo, text=True).strip() == candidate
+ product = Product(repo, root=root)
+ upstream = None
+ try:
+ fixture, upstream = prepare_product(product, harness)
+ product.stop()
+ print(json.dumps({'state': 'prepared', 'candidate': candidate, 'harness': harness,
+ 'data_root': str(product.root), 'process_home': fixture['home'],
+ 'workspace': fixture['project'], 'plan_id': product.plan_id,
+ 'base_url': upstream.base_url, 'fixture': str(product.root / 'native-context.json'),
+ 'proxy_trap_events': fixture.get('proxy_trap_events'),
+ 'configuration_saved_through_ui': False}), flush=True)
+ # The caller owns this helper process. Stop it only after the Desktop journey ends.
+ def stop_helper(*_):
+ raise KeyboardInterrupt()
+ signal.signal(signal.SIGTERM, stop_helper)
+ signal.pause()
+ except KeyboardInterrupt:
+ pass
+ finally:
+ try:
+ product.close()
+ finally:
+ try:
+ qoder_native_context.cleanup_context(product)
+ finally:
+ if upstream:
+ upstream.close()
+
+
+if __name__ == '__main__':
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument('repository')
+ parser.add_argument('candidate')
+ parser.add_argument('--desktop-root', type=Path)
+ parser.add_argument('--harness', choices=('codex', 'claude', 'qoder'))
+ args = parser.parse_args()
+ if args.desktop_root:
+ if not args.harness:
+ parser.error('--harness is required with --desktop-root')
+ prepare_desktop(args.repository, args.candidate, args.desktop_root, args.harness)
+ else:
+ run(args.repository, args.candidate)
diff --git a/crates/daemon/tests/support/publication_process.py b/crates/daemon/tests/support/publication_process.py
index 138b1abf..cd690605 100644
--- a/crates/daemon/tests/support/publication_process.py
+++ b/crates/daemon/tests/support/publication_process.py
@@ -1,6 +1,8 @@
"""Operation recovery assertions over the real CLI, daemon and Gateway HTTP catalog."""
import hashlib
import json
+from pathlib import Path
+import stat
import sys
from publication_product import Product, encoded
@@ -313,7 +315,64 @@ def recovery(repository, boundary):
product.close()
+def native_directory_snapshot(roots):
+ snapshot = {}
+ for root in roots:
+ for path in (root, *sorted(root.rglob('*'))):
+ metadata = path.lstat()
+ assert stat.S_ISDIR(metadata.st_mode) or stat.S_ISREG(metadata.st_mode), \
+ 'startup fixture must contain only owned directories and files'
+ snapshot[str(path)] = {
+ 'mode': stat.S_IMODE(metadata.st_mode), 'uid': metadata.st_uid,
+ 'sha256': hashlib.sha256(path.read_bytes()).hexdigest() if path.is_file() else None,
+ }
+ return snapshot
+
+
+def unmanaged_native_permissions(repository):
+ """Unconfigured native targets cannot prevent the real local service from starting."""
+ cases = ('.agents', '.claude', '.qoder/skills')
+ completed = []
+ for selected in cases:
+ product = Product(repository)
+ try:
+ product.enable_debug_diagnostics()
+ home = Path(product.env['HOME'])
+ roots = [home / name for name in ('.agents', '.claude', '.qoder')]
+ for root in roots:
+ root.mkdir(mode=0o700, parents=True, exist_ok=True)
+ root.chmod(0o700)
+ neighbor = root / 'unmanaged-user-file'
+ neighbor.write_text('Preserve native contents: ' + str(root))
+ neighbor.chmod(0o600)
+ (home / '.qoder/skills').mkdir(mode=0o700)
+ # These are private fixture directories, never the caller's native HOME.
+ (home / selected).chmod(0o775)
+ before = native_directory_snapshot(roots)
+ product.start()
+ status = product.control('GetSystemStatus', {})['data']
+ assert status['daemon'] == 'role_all' and status['gateway'] == 'ready', status
+ product.control('GetClientServiceStatus', {})
+ product.stop()
+ assert native_directory_snapshot(roots) == before, \
+ 'startup changed an unmanaged native directory, file or permission'
+ diagnostics = product.diagnostics_snapshot()
+ assert diagnostics['state'] == 'complete' and diagnostics['level_applied']['level'] == 'debug'
+ completed.append(selected)
+ print(json.dumps({'scenario': 'unmanaged-native-target-startup', 'state': 'green',
+ 'permissive_target': selected, 'role': 'all',
+ 'native_material_unchanged': True, 'diagnostics': diagnostics}), flush=True)
+ finally:
+ product.close()
+ assert tuple(completed) == cases, 'all three native target permission variants are required'
+
+
if __name__ == '__main__':
- for boundary in ('after_prepare', 'before_install', 'after_gateway_durable',
- 'after_target', 'after_active', 'after_terminal'):
- recovery(sys.argv[1], boundary)
+ if len(sys.argv) == 3:
+ assert sys.argv[2] == 'unmanaged-native-permissions', 'unknown publication scenario'
+ unmanaged_native_permissions(sys.argv[1])
+ else:
+ assert len(sys.argv) == 2, 'repository required'
+ for boundary in ('after_prepare', 'before_install', 'after_gateway_durable',
+ 'after_target', 'after_active', 'after_terminal'):
+ recovery(sys.argv[1], boundary)
diff --git a/crates/daemon/tests/support/publication_product.py b/crates/daemon/tests/support/publication_product.py
index 91ce8395..46a53a8a 100644
--- a/crates/daemon/tests/support/publication_product.py
+++ b/crates/daemon/tests/support/publication_product.py
@@ -136,10 +136,17 @@ finally:
self.diagnostics_root = self.storage / 'diagnostics'
self.diagnostics_args = []
self.env = {k: v for k, v in os.environ.items()
- if not k.startswith(('ANTHROPIC_', 'HIROUTE_', 'OPENAI_'))}
+ if not k.startswith(('ANTHROPIC_', 'HIROUTE_', 'OPENAI_', 'AWS_', 'AZURE_',
+ 'GOOGLE_', 'VERTEX_', 'QODER_'))
+ and k not in ('CODEX_CONFIG', 'CODEX_API_KEY', 'CLAUDE_CODE_OAUTH_TOKEN',
+ 'GEMINI_API_KEY', 'OPENROUTER_API_KEY', 'CLAUDE_CODE_USE_BEDROCK',
+ 'CLAUDE_CODE_USE_VERTEX', 'CLAUDE_CODE_USE_FOUNDRY')}
self.env.update(HOME=str(home), CODEX_HOME=str(home / '.codex'),
+ CLAUDE_CONFIG_DIR=str(home / '.claude'),
+ QODER_CONFIG_DIR=str(home / '.qoder'),
PATH=str(bin_dir) + ':/usr/bin:/bin',
HIROUTE_RUNTIME_DIR=str(self.root / 'runtime'),
+ HIROUTE_WORKER_RECEIPT_DIR=str(self.root / 'worker-receipts'),
HIROUTE_REPLAY_ROOT=str(self.root / 'replay'))
with socket.socket() as sock:
sock.bind(('127.0.0.1', 0))
diff --git a/crates/daemon/tests/support/qoder_collaboration_fixture.py b/crates/daemon/tests/support/qoder_collaboration_fixture.py
new file mode 100644
index 00000000..1a8d75eb
--- /dev/null
+++ b/crates/daemon/tests/support/qoder_collaboration_fixture.py
@@ -0,0 +1,170 @@
+"""Two independent model-role oracles for real Qoder Skill → public CLI → Worker.
+
+Only native tool results and the Worker's disk artifact can complete this journey.
+This module does not start HiRoute, impersonate an Agent, or write its installed Skill.
+"""
+import json
+from pathlib import Path
+import shlex
+
+from native_context_fixture import decision, qoder_skill_expansions, tool_results
+
+
+CASES = ('agent.collaboration.user-skill', 'agent.collaboration.public-worker-delegation',
+ 'agent.collaboration.disable-owned-skill')
+
+
+def successful_envelope(output):
+ """Qoder Bash may surround stdout with native timing/status text."""
+ assert isinstance(output, str), 'expected a native Bash text result'
+ decoder = json.JSONDecoder()
+ matches = []
+ for index, char in enumerate(output):
+ if char != '{':
+ continue
+ try:
+ value, _ = decoder.raw_decode(output[index:])
+ except ValueError:
+ continue
+ if isinstance(value, dict) and 'schema_version' in value and 'status' in value:
+ matches.append(value)
+ assert len(matches) == 1 and matches[0]['status'] == 'succeeded', \
+ 'expected one successful public CLI envelope in the correlated tool result'
+ return matches[0]
+
+
+def output_envelope(output):
+ return successful_envelope(output)['data']
+
+
+def worker_decision(fixture, body):
+ results = tool_results(body, 'qoder')
+ artifact = fixture['artifact']
+ if 'delegated_artifact' in results:
+ assert artifact['receipt'] in results['delegated_artifact'], 'Worker tool did not return artifact receipt'
+ path = Path(artifact['path'])
+ assert path.is_file() and not path.is_symlink() and path.read_text().strip() == artifact['receipt'], \
+ 'Worker did not produce the independent disk artifact'
+ return dict(kind='text', text=artifact['receipt'], continued=False)
+ action = decision(fixture, body)
+ if action['kind'] != 'text':
+ return action
+ command = ('/usr/bin/printf "%s\\n" ' + shlex.quote(artifact['receipt']) + ' > ' +
+ shlex.quote(artifact['path']) + ' && /bin/cat ' + shlex.quote(artifact['path']))
+ return dict(kind='tool', id='delegated_artifact', name='Bash',
+ arguments={'command': command, 'timeout': 10000})
+
+
+class MainAgentOracle:
+ def __init__(self, fixture, skill, cli, worker_events):
+ self.fixture = fixture
+ self.skill = Path(skill)
+ self.skill_body = self.skill.read_text().split('---', 2)[-1].strip()
+ assert self.skill_body and 'hiroute worker plans' in self.skill_body
+ self.cli = str(Path(cli).resolve(strict=True))
+ self.worker_events = worker_events
+ self.accepted = None
+ self.user_skill_proved = False
+ self.completed = False
+ self.requests = 0
+
+ def reply(self, _unused, body):
+ self.requests += 1
+ assert self.requests <= 32, 'main Agent exceeded the bounded public observation budget'
+ rendered = json.dumps(body)
+ assert self.fixture['main_marker'] in rendered, 'Worker request reached the main Agent source'
+ results = tool_results(body, 'qoder')
+ names = {item.get('name') for item in body.get('tools', [])}
+ assert {'Skill', 'Bash'} <= names, 'native main Agent Skill/Bash tools unavailable'
+ if 'main_skill' not in results:
+ assert 'hiroute-collaboration' in rendered, 'installed user collaboration Skill not discovered'
+ return dict(kind='tool', id='main_skill', name='Skill',
+ arguments={'skill': 'hiroute-collaboration'})
+ # Native Qoder returns a correlated launch receipt, then expands the body
+ # into a user message. Exact directory excludes a same-named project/plugin.
+ contents = qoder_skill_expansions(body, self.skill.parent)
+ assert any(text.strip() == self.skill_body for text in contents), \
+ 'actual installed user Skill directory and body were not loaded'
+ self.user_skill_proved = True
+ if 'main_plans' not in results:
+ return self.bash('main_plans', shlex.quote(self.cli) + ' worker plans --output json')
+ directory = output_envelope(results['main_plans'])
+ plans = [plan for plan in directory['plans'] if plan['agent_plan_id'] == self.fixture['plan_id']]
+ assert len(plans) == 1 and plans[0]['harness'] == 'qoder_cli' and plans[0]['availability'] == 'ready', \
+ 'the public directory did not offer the published Qoder Worker Plan'
+ if 'main_exec' not in results:
+ prompt = 'Use ' + ' and '.join(item['name'] for item in self.fixture['skills']) + \
+ ' to complete the delegated native receipt task.'
+ command = ('/usr/bin/printf %s ' + shlex.quote(prompt) + ' | ' + shlex.quote(self.cli) +
+ ' worker exec --plan ' + shlex.quote(plans[0]['agent_plan_id']) + ' --cwd ' +
+ shlex.quote(self.fixture['project']) + ' --run-timeout 120 --wait-timeout 120' +
+ ' --submission-key qoder-main-agent-delegation --file - --output json')
+ return self.bash('main_exec', command, 150000)
+ envelope = successful_envelope(results['main_exec'])
+ accepted = envelope['data']
+ # Retain the actual public result even on failure for scoped diagnosis;
+ # completion still requires success and the independent disk artifact.
+ self.accepted = accepted
+ assert accepted.get('task_id') and accepted.get('run_id'), 'public Worker acceptance has no identity'
+ wait_index = 1
+ while 'main_wait_' + str(wait_index) in results:
+ envelope = successful_envelope(results['main_wait_' + str(wait_index)])
+ self.assert_same_worker(envelope['data'], accepted)
+ wait_index += 1
+ current = envelope['data']
+ self.accepted = current
+ if current['run_state'] not in ('succeeded', 'failed', 'cancelled', 'unknown'):
+ actions = [action['input'] for action in envelope.get('next_actions', [])
+ if action.get('command_id') == 'worker.wait'
+ and action.get('input', {}).get('run_id') == accepted['run_id']]
+ assert (len(actions) == 1 and type(actions[0].get('after_revision')) is int
+ and actions[0]['after_revision'] >= 0), \
+ 'active public Worker result must provide its exact wait cursor'
+ command = (shlex.quote(self.cli) + ' worker wait --run ' + shlex.quote(accepted['run_id']) +
+ ' --after-revision ' + str(actions[0]['after_revision']) +
+ ' --wait-timeout 20 --output json')
+ return self.bash('main_wait_' + str(wait_index), command, 25000)
+ assert current['run_state'] == 'succeeded', 'main Agent did not observe successful public Worker execution'
+ if 'result' not in current:
+ if 'main_result' not in results:
+ return self.bash('main_result', shlex.quote(self.cli) + ' worker result --run ' +
+ shlex.quote(accepted['run_id']) + ' --output json')
+ current = output_envelope(results['main_result'])
+ self.assert_same_worker(current, accepted)
+ assert current['run_state'] == 'succeeded', 'public Worker result is not successful'
+ receipt = self.fixture['artifact']['receipt']
+ assert receipt in current.get('result', ''), 'public Worker result lost its tool artifact'
+ assert Path(self.fixture['artifact']['path']).read_text().strip() == receipt, 'disk artifact missing'
+ attempts = self.worker_events()
+ assert attempts and all(event['state'] == 'green' for event in attempts), 'Worker source is incomplete'
+ assert any(event.get('call_id') == 'delegated_artifact' for event in attempts), \
+ 'no real Worker tool request produced the artifact'
+ self.accepted, self.completed = current, True
+ return dict(kind='text', text='MAIN-AGENT-COMPLETED-' + receipt, continued=False)
+
+ @staticmethod
+ def assert_same_worker(current, accepted):
+ assert all(current.get(key) == accepted[key] for key in ('task_id', 'run_id')), \
+ 'public observation switched the accepted Worker identity'
+
+ @staticmethod
+ def bash(call_id, command, timeout=10000):
+ return dict(kind='tool', id=call_id, name='Bash', arguments={'command': command, 'timeout': timeout})
+
+
+def main_route_settings(endpoint, alias, credential_env):
+ """Independent native-main fixture settings; Worker uses the production renderer."""
+ provider = 'hiroute-main-acceptance'
+ selected = provider + '/' + alias
+ own_alias = {'modelConfig': {'model': selected}}
+ return selected, {
+ 'general': {'enableAutoUpdate': False, 'sessionRetention': {'enabled': False},
+ 'plan': {'modelRouting': False}},
+ 'disableAllHooks': True, 'promptSuggestionEnabled': False, 'model': {'name': selected},
+ 'modelConfigs': {'aliases': {selected: own_alias}, 'customAliases': {selected: own_alias},
+ 'overrides': [], 'customOverrides': []},
+ 'providers': {provider: {'protocol': 'openai-responses', 'baseUrl': endpoint,
+ 'apiKey': '${' + credential_env + '}', 'model': alias,
+ 'models': [{'model': alias, 'contextWindow': 100000, 'capabilities': {'tools': True}}],
+ 'routing': {purpose: alias for purpose in ('utility', 'session_title', 'summary', 'compact', 'subagent')}}},
+ }
diff --git a/crates/daemon/tests/support/qoder_collaboration_product.py b/crates/daemon/tests/support/qoder_collaboration_product.py
new file mode 100644
index 00000000..ac8c11ce
--- /dev/null
+++ b/crates/daemon/tests/support/qoder_collaboration_product.py
@@ -0,0 +1,213 @@
+"""Real Qoder main Agent → installed user Skill → public CLI → real Qoder Worker.
+
+Uses the same Product, managed candidate and native context as the Worker journeys.
+Only model upstreams are deterministic. No daily provider/auth settings are edited.
+"""
+import hashlib
+import json
+import os
+from pathlib import Path
+import secrets
+import subprocess
+import sys
+
+from agent_product_support import apply_settings, run_native_command
+from delegation_product import configure_worker_installation
+from native_context_boundaries import source_events
+from native_context_fixture import NativeContextUpstream, assert_preserved, digest, write_new
+from native_context_product import prepare_product, report_failure, selected_installation, wait_for_resumable_task
+from publication_product import Product, encoded
+from qoder_collaboration_fixture import CASES, MainAgentOracle, main_route_settings, worker_decision
+import qoder_native_context
+
+
+AGENT = 'agent_qoder_default'
+
+
+def check_collaboration(product, key):
+ check = {'agent_id': AGENT, 'scope': 'collaboration', 'suite': 'quick', 'allow_model_call': False}
+ consent = {'change_digest': 'sha256:' + hashlib.sha256(encoded(check)).hexdigest(),
+ 'expected_revisions': product.control('GetClientServiceStatus', {})['data']['revisions']}
+ capability = product.grant('CheckAgentConnection', consent, key)
+ _, checked = product.cli('agents check ' + AGENT + ' --scope collaboration', capability=capability)
+ assert checked['data']['skill_loading'] == 'proven' and checked['data']['trusted_cli_execution'] == 'proven', \
+ 'native collaboration capability check did not complete'
+
+
+def apply_collaboration(product, context, intent, key):
+ spec = {'schema_version': {'major': 2, 'minor': 0}, 'context_id': context, 'collaboration': intent}
+ _, status = apply_settings(product, spec, key, 'collaboration')
+ return status['collaboration']
+
+
+def run_main_agent(product, binary, upstream, fixture):
+ native_id, overlay = main_route_settings(upstream.base_url, upstream.model, 'HIROUTE_QODER_MAIN_TOKEN')
+ settings = product.root / 'qoder-main-settings.json'
+ write_new(settings, json.dumps(overlay))
+ temporary = product.root / 'qoder-main-tmp'
+ temporary.mkdir(mode=0o700)
+ args = [str(binary), '--cwd', str(product.project), '--config-dir', fixture['config'],
+ '--setting-sources', 'user', '--settings', str(settings), '--model', native_id,
+ '--print', '--no-session-persistence', '--output-format', 'stream-json',
+ '--strict-mcp-config', '--mcp-config', '{"mcpServers":{}}', '--tools', 'Skill,Read,Bash',
+ '--allowed-tools', 'Skill,Bash', '--permission-mode', 'dont_ask',
+ '--max-model-request-retries', '0', '--max-output-tokens', '2048', '--max-turns', '32',
+ '-p', fixture['main_marker'] + ': Use hiroute-collaboration and explicitly delegate the native receipt task.']
+ env = dict(product.env, HIROUTE_QODER_MAIN_TOKEN=upstream.token, TMPDIR=str(temporary))
+ stdout = run_native_command(product, args, env=env, timeout=190, label='native main Agent')
+ assert ('MAIN-AGENT-COMPLETED-' + fixture['artifact']['receipt']).encode() in stdout, \
+ 'native main Agent did not return the independently verified completion'
+
+
+def restore_skill(product, context, restore_ref, before, skill):
+ # A journey can configure/restore more than once. Each restoration point
+ # represents a distinct operation; do not reuse one global idempotency key.
+ key = 'qoder-collaboration-disable-' + hashlib.sha256(encoded(restore_ref)).hexdigest()[:16]
+ status = apply_collaboration(product, context, {'intent': 'restore', 'restore_point_ref': restore_ref},
+ key)
+ assert (status['state'] == 'restored' and status.get('current_selection') is None
+ and status.get('restore_point_ref') is None), \
+ 'collaboration disable did not restore and release its current selection/reference'
+ if before is None:
+ assert not skill.exists(), 'product left its owned collaboration Skill installed'
+ else:
+ assert skill.read_bytes() == before, 'product removed or rewrote a borrowed user Skill'
+
+
+def finish_collaboration(product, sources, restore, report, stage, primary_failure):
+ """Restore before stopping the service; preserve the first business failure."""
+ errors = []
+ if restore is not None:
+ try:
+ if product.process is None:
+ product.start()
+ restore()
+ report['restore_after_failure'] = {'state': 'succeeded'}
+ except Exception as error:
+ errors.append({'step': 'restore_collaboration', 'error_type': type(error).__name__})
+ report['restore_after_failure'] = {'state': 'red'}
+ if primary_failure or errors:
+ report['cleanup_failures'] = list(errors)
+ try:
+ report_failure(product, report, stage)
+ except Exception as error:
+ errors.append({'step': 'preserve_failure_report', 'error_type': type(error).__name__})
+ # Try every independently owned cleanup even when another fails. Never remove
+ # user material directly to compensate for a failed product Restore.
+ actions = [('close_product', product.close),
+ ('cleanup_owned_receipts', lambda: qoder_native_context.cleanup_context(product))]
+ actions.extend(('close_source', source.close) for source in sources)
+ for step, action in actions:
+ try:
+ action()
+ except Exception as error:
+ errors.append({'step': step, 'error_type': type(error).__name__})
+ if errors:
+ print(json.dumps({'scenario': 'qoder-collaboration-cleanup', 'state': 'red',
+ 'candidate': report['candidate'], 'failures': errors,
+ 'primary_failure_preserved': primary_failure}), flush=True)
+ if not primary_failure:
+ raise AssertionError('Qoder collaboration cleanup failed; inspect the cleanup report')
+
+
+def run(repository, candidate):
+ repo = Path(repository).resolve()
+ assert subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=repo, text=True).strip() == candidate
+ product = Product(repo)
+ sources = []
+ fixture = None
+ context = restore_ref = None
+ restored = False
+ skill = None
+ before_skill = None
+ primary_failure = False
+ oracle = None
+ stage = 'explicit-qoder-context'
+ report = dict(scenario='qoder-main-agent-delegation', candidate=candidate, worker_harness='qoder',
+ required_cases=list(CASES), selected_cases=list(CASES), cases=[],
+ evidence_limit='Real main Agent, user Skill, public CLI, daemon, Gateway and Worker; synthetic models; no Desktop verdict')
+ try:
+ binary, _, _ = selected_installation('qoder')
+ (product.root / 'bin/qodercli').symlink_to(binary)
+ fixture, worker_source = prepare_product(product, 'qoder')
+ report['source_context_tokens'] = fixture['source_context_tokens']
+ sources.append(worker_source)
+ configure_worker_installation(product, 'qoder_cli', None, binary, None)
+ fixture['main_marker'] = 'QODER-MAIN-' + secrets.token_hex(12)
+ fixture['artifact'] = dict(path=str(product.project / 'delegated-native-artifact.txt'),
+ receipt='QODER-WORKER-' + secrets.token_hex(16))
+ (product.root / 'native-context.json').write_text(json.dumps(fixture))
+ worker_source.reply = worker_decision
+ skill = qoder_native_context.prepare_collaboration_target(product)
+ assert not skill.is_symlink(), 'user collaboration Skill is a symlink'
+ before_skill = skill.read_bytes() if skill.exists() else None
+ stage = 'native-collaboration-preflight'
+ check_collaboration(product, 'qoder-preflight')
+ scan = product.preview('agents scan')
+ agents = [agent for agent in scan['agents'] if agent['agent_id'] == AGENT]
+ assert len(agents) == 1, 'Qoder installation/context was not discovered'
+ context = agents[0]['context_id']
+ stage = 'install-real-user-collaboration-skill'
+ status = apply_collaboration(product, context,
+ {'intent': 'configure', 'settings': {'trigger_mode': 'explicit'}}, 'qoder-collaboration-enable')
+ assert status['state'] == 'configured' and status['current_selection']['trigger_mode'] == 'explicit', status
+ restore_ref = status['restore_point_ref']
+ assert restore_ref and skill.is_file(), 'configured collaboration has no owned restore reference/Skill'
+ assert not (product.project / '.qoder/skills/hiroute-collaboration').exists(), 'project Skill shadows user target'
+ stage = 'verify-installed-user-skill'
+ check_collaboration(product, 'qoder-installed-user-skill')
+ qoder_native_context.assert_settings_preserved(fixture)
+ controls = product.root / 'main-agent-source'
+ controls.mkdir(mode=0o700)
+ (controls / 'native-context.json').write_text('{}')
+ main_source = NativeContextUpstream(controls)
+ sources.append(main_source)
+ main_source.token, main_source.model = 'synthetic-main-agent-only-token', 'main-agent/receipt:v1'
+ oracle = MainAgentOracle(fixture, skill, product.bin / 'hiroute', lambda: source_events(worker_source))
+ main_source.reply = oracle.reply
+ stage = 'real-main-agent-to-worker'
+ run_main_agent(product, binary, main_source, fixture)
+ assert oracle.user_skill_proved and oracle.completed, 'main Agent oracle did not complete all stages'
+ assert all(event['state'] == 'green' for source in sources for event in source_events(source))
+ fixture['task_id'] = oracle.accepted['task_id']
+ wait_for_resumable_task(product, oracle.accepted['task_id'], oracle.accepted['run_id'])
+ report.update(task_id=oracle.accepted['task_id'], run_id=oracle.accepted['run_id'],
+ native_session_id=qoder_native_context.task_binding(fixture),
+ main_requests=len(source_events(main_source)), worker_requests=len(source_events(worker_source)),
+ actual_user_skill_sha256=digest(skill), artifact_sha256=digest(fixture['artifact']['path']),
+ main_worker_distinct_sources=True, native_context_setup='explicit-borrowed-login-context')
+ report['cases'].extend({'id': case, 'state': 'green'} for case in CASES[:2])
+ assert_preserved(fixture)
+ stage = 'disable-only-owned-collaboration-skill'
+ restore_skill(product, context, restore_ref, before_skill, skill)
+ restored = True
+ qoder_native_context.assert_settings_preserved(fixture)
+ report['cases'].append({'id': CASES[2], 'state': 'green'})
+ product.stop()
+ diagnostics = product.diagnostics_snapshot()
+ assert diagnostics['state'] == 'complete' and diagnostics['level_applied']['level'] == 'debug'
+ report.update(state='green', user_settings_unchanged=True, diagnostics=diagnostics,
+ binaries={name: digest(product.bin / name) for name in ('hiroute', 'hirouted')},
+ harness_sha256=digest(binary))
+ except Exception:
+ primary_failure = True
+ if oracle is not None:
+ report['main_observations'] = {
+ 'actual_user_skill_proved': oracle.user_skill_proved,
+ 'requests': oracle.requests,
+ 'completed': oracle.completed,
+ 'public_worker_result': ({key: oracle.accepted.get(key)
+ for key in ('task_id', 'run_id', 'run_state')}
+ if oracle.accepted is not None else None),
+ }
+ raise
+ finally:
+ restore = None
+ if restore_ref and not restored:
+ restore = lambda: restore_skill(product, context, restore_ref, before_skill, skill)
+ finish_collaboration(product, sources, restore, report, stage, primary_failure)
+ print(json.dumps(report), flush=True)
+
+
+if __name__ == '__main__':
+ run(sys.argv[1], sys.argv[2])
diff --git a/crates/daemon/tests/support/qoder_compaction_product.py b/crates/daemon/tests/support/qoder_compaction_product.py
new file mode 100644
index 00000000..e878de28
--- /dev/null
+++ b/crates/daemon/tests/support/qoder_compaction_product.py
@@ -0,0 +1,164 @@
+"""Automatic native compaction stays on the real Worker's frozen Gateway route.
+
+The synthetic usage receipt triggers Qoder's own compactor inside one public
+Worker execution. This is separate from the no-probe Continue/Skill journey.
+"""
+import json
+from pathlib import Path
+import secrets
+import shlex
+import subprocess
+import sys
+
+from delegation_product import configure_worker_installation, wait_for_worker_result, worker_cli
+from native_context_boundaries import source_events
+from native_context_fixture import (assert_preserved, digest, is_native_compaction, native_text,
+ protect_configuration, tool_results, write_new)
+from native_context_product import (exact_history, prepare_product, report_failure,
+ selected_installation, wait_for_resumable_task)
+from publication_product import Product
+import qoder_native_context
+
+
+CASES = ('worker.context.tool-summary-route', 'worker.context.compaction-route')
+CONTEXT_TOKENS = 100_000
+PRESSURE_TOKENS = 90_000
+
+
+class CompactionOracle:
+ def __init__(self, fixture, upstream_model):
+ self.fixture, self.model = fixture, upstream_model
+ self.main_requests = self.compact_requests = self.tool_summary_requests = 0
+ self.tool_receipt = 'NATIVE-TOOL-' + secrets.token_hex(12)
+ self.summary_receipt = 'NATIVE-COMPACT-' + secrets.token_hex(12)
+ self.tool_summary_receipt = 'NATIVE-TOOL-SUMMARY-' + secrets.token_hex(12)
+
+ def reply(self, _fixture, body):
+ assert body.get('model') == self.model, 'compaction or main request changed the frozen upstream model'
+ results = tool_results(body, 'qoder')
+ items = body.get('input', [])
+ last = native_text(items[-1]) if isinstance(items, list) and items else native_text(items)
+ if 'tool output' in last.lower() and 'summar' in last.lower() and self.tool_receipt in last:
+ assert self.main_requests == 1 and self.tool_summary_requests == 0, 'unexpected native tool summarization'
+ self.tool_summary_requests += 1
+ return dict(kind='text', request_kind='tool_summary', input_tokens=30,
+ text=self.tool_summary_receipt + ': The read-only tool returned ' + self.tool_receipt)
+ if is_native_compaction(body):
+ assert self.main_requests == 1 and self.compact_requests == 0, 'unexpected or repeated native compaction'
+ assert self.tool_summary_requests == 1 and self.tool_summary_receipt in results.get('native_compaction_tool', ''), \
+ 'native compaction omitted the correlated summarized tool receipt'
+ assert self.summary_receipt not in native_text(body), 'summary receipt was present before compaction'
+ self.compact_requests += 1
+ return dict(kind='text', request_kind='compact', input_tokens=30,
+ text='<analysis>Local routing acceptance only.</analysis><summary>' +
+ self.summary_receipt + ': The read-only tool returned ' + self.tool_summary_receipt +
+ '. Finish the requested native routing receipt.</summary>')
+ self.main_requests += 1
+ assert self.main_requests <= 3, 'unexpected native main request'
+ if self.main_requests == 1:
+ assert self.fixture['compaction_prompt'] in native_text(body), 'unknown native task'
+ return dict(kind='tool', request_kind='main', id='native_compaction_tool', name='Bash',
+ arguments={'command': '/bin/sh ' + shlex.quote(self.fixture['compaction_script']),
+ 'timeout': 10000}, input_tokens=PRESSURE_TOKENS)
+ assert (self.compact_requests == 1 and self.summary_receipt in native_text(body)
+ and self.tool_summary_receipt in native_text(body)), \
+ 'main request did not consume the actual native summary'
+ return dict(kind='text', request_kind='main', input_tokens=30,
+ text='compacted-' + self.fixture['receipt'])
+
+
+def assert_native_compaction(path, summary_receipt):
+ rows = [json.loads(line) for line in Path(path).read_text().splitlines() if line]
+ boundaries = [row.get('compactMetadata', {}) for row in rows if row.get('subtype') == 'compact_boundary']
+ assert any(item.get('trigger') == 'auto' and item.get('preTokens', 0) >= PRESSURE_TOKENS
+ for item in boundaries), 'native history has no actual automatic compaction boundary'
+ assert any(row.get('isCompactSummary') and summary_receipt in json.dumps(row) for row in rows), \
+ 'exact native session did not persist the independently issued summary'
+ return [{'trigger': item.get('trigger'), 'pre_tokens': item.get('preTokens'),
+ 'post_tokens': item.get('postTokens')} for item in boundaries]
+
+
+def run(repository, candidate):
+ repo = Path(repository).resolve()
+ assert subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=repo, text=True).strip() == candidate
+ product, upstream = Product(repo), None
+ stage = 'prepare-frozen-worker-source'
+ report = dict(scenario='qoder-worker-compaction-route', candidate=candidate, worker_harness='qoder',
+ required_cases=list(CASES), selected_cases=list(CASES), cases=[],
+ evidence_limit='Real Plan/admission/profile/native Worker/Gateway; controlled upstream; no Desktop verdict')
+ try:
+ fixture, upstream = prepare_product(product, 'qoder', context_tokens=CONTEXT_TOKENS)
+ report['source_context_tokens'] = fixture['source_context_tokens']
+ binary, _, _ = selected_installation('qoder')
+ configure_worker_installation(product, 'qoder_cli', None, binary, None)
+ project_settings = product.project / '.qoder/settings.json'
+ settings = json.loads(project_settings.read_text())
+ settings['experimental'] = {'contextManagement': True}
+ settings['model']['summarizeToolOutput'] = {'Bash': {'tokenBudget': 2000}}
+ project_settings.write_text(json.dumps(settings))
+ protect_configuration(fixture, [project_settings])
+ fixture['compaction_prompt'] = 'QODER-COMPACTION-' + secrets.token_hex(12)
+ fixture['compaction_script'] = str(product.project / 'native-compaction-receipt.sh')
+ oracle = CompactionOracle(fixture, upstream.model)
+ script = Path(fixture['compaction_script'])
+ write_new(script, '#!/bin/sh\ni=0\nwhile [ "$i" -lt 300 ]; do\n' +
+ ' /usr/bin/printf "%s\\n" ' + shlex.quote(oracle.tool_receipt) +
+ '\n i=$((i + 1))\ndone\n', executable=True)
+ protect_configuration(fixture, [script])
+ (product.root / 'native-context.json').write_text(json.dumps(fixture))
+ upstream.reply = oracle.reply
+ stage = 'automatic-compaction-in-real-worker'
+ command = ('worker exec --plan ' + product.plan_id + ' --cwd ' + str(product.project) +
+ ' --run-timeout 120 --no-wait --submission-key qoder-compaction --file - --output json')
+ _, accepted = worker_cli(product, command,
+ fixture['compaction_prompt'] + ': Execute the requested read-only receipt tool, then finish the task.')
+ first = accepted['data']
+ fixture['task_id'] = first['task_id']
+ result = wait_for_worker_result(product, first['run_id'], timeout=150)
+ assert 'compacted-' + fixture['receipt'] in result['result'], 'missing compacted Worker result'
+ wait_for_resumable_task(product, first['task_id'], first['run_id'])
+ history = exact_history(fixture)
+ report['native_compaction_boundaries'] = assert_native_compaction(history[0], oracle.summary_receipt)
+ stage = 'continue-native-compacted-history'
+ command = ('worker continue --task ' + first['task_id'] + ' --expected-latest-run ' + first['run_id'] +
+ ' --run-timeout 120 --no-wait --submission-key qoder-compaction-continue --file - --output json')
+ _, accepted = worker_cli(product, command, 'Continue the same native task using its compacted summary.')
+ continued = accepted['data']
+ result = wait_for_worker_result(product, continued['run_id'], timeout=150)
+ assert 'compacted-' + fixture['receipt'] in result['result']
+ wait_for_resumable_task(product, first['task_id'], continued['run_id'])
+ assert exact_history(fixture) == history, 'compacted Continue changed the exact native session'
+ assert oracle.main_requests == 3 and oracle.compact_requests == oracle.tool_summary_requests == 1, \
+ 'required native request kinds missing'
+ attempts = source_events(upstream)
+ assert [event.get('request_kind') for event in attempts] == ['main', 'tool_summary', 'compact', 'main', 'main'], attempts
+ assert all(event['state'] == 'green' and event['model'] == upstream.model for event in attempts)
+ assert_preserved(fixture)
+ qoder_native_context.assert_settings_preserved(fixture)
+ product.stop()
+ diagnostics = product.diagnostics_snapshot()
+ assert diagnostics['state'] == 'complete' and diagnostics['level_applied']['level'] == 'debug'
+ report.update(state='green', cases=[{'id': case, 'state': 'green'} for case in CASES], task_id=first['task_id'],
+ run_ids=[first['run_id'], continued['run_id']], native_session_id=history[1],
+ main_requests=oracle.main_requests, compact_requests=oracle.compact_requests,
+ tool_summary_requests=oracle.tool_summary_requests,
+ upstream_model=upstream.model, foreign_requests=0, diagnostics=diagnostics,
+ binaries={name: digest(product.bin / name) for name in ('hiroute', 'hirouted')},
+ harness_sha256=digest(binary))
+ print(json.dumps(report), flush=True)
+ except Exception:
+ report_failure(product, report, stage)
+ raise
+ finally:
+ try:
+ product.close()
+ finally:
+ try:
+ qoder_native_context.cleanup_context(product)
+ finally:
+ if upstream:
+ upstream.close()
+
+
+if __name__ == '__main__':
+ run(sys.argv[1], sys.argv[2])
diff --git a/crates/daemon/tests/support/qoder_model_fixture.py b/crates/daemon/tests/support/qoder_model_fixture.py
new file mode 100644
index 00000000..348c2406
--- /dev/null
+++ b/crates/daemon/tests/support/qoder_model_fixture.py
@@ -0,0 +1,172 @@
+"""Owned Qoder settings and native reads for the persisted-model product journey.
+
+Only this leaf may write the explicitly selected MODEL context. It never reads
+authentication, and it never supplies native provider/settings/credential overrides.
+"""
+from copy import deepcopy
+import json
+import os
+from pathlib import Path
+import secrets
+import stat
+
+from agent_product_support import run_native_command
+from native_context_fixture import native_text
+from qoder_native_context import selected_directory
+
+
+CASES = ('agent.models.persisted-routes', 'agent.models.credential-rotation',
+ 'agent.models.independent-restore', 'agent.models.default-reference-guard')
+LIVE_PROMPT = 'Reply with exactly HIROUTE_LIVE_CHECK_OK. Do not use tools or perform any other action.'
+
+
+def select_model_context(product):
+ home = selected_directory('HIROUTE_QODER_MODEL_CONTEXT_HOME')
+ config = selected_directory('HIROUTE_QODER_MODEL_CONFIG_DIR')
+ assert home != Path.home().resolve() and config.is_relative_to(home), \
+ 'model acceptance requires a dedicated context, never the daily HOME/config'
+ product.env.update(HOME=str(home), QODER_CONFIG_DIR=str(config))
+ return config
+
+
+class OwnedModelSettings:
+ """Seed a synthetic user baseline; undo only our unchanged final baseline."""
+ def __init__(self, config, foreign_endpoint):
+ self.path = Path(config) / 'settings.json'
+ assert not self.path.is_symlink(), 'model fixture cannot own a linked settings target'
+ self.original = self.path.read_bytes() if self.path.exists() else None
+ self.original_mode = stat.S_IMODE(self.path.stat().st_mode) if self.original is not None else None
+ self.baseline = json.loads(self.original) if self.original is not None else {}
+ assert isinstance(self.baseline, dict), 'dedicated model settings must be a JSON object'
+ self.baseline = deepcopy(self.baseline)
+ assert not {'hirouteAcceptance', 'hirouteLaterEdit'} & self.baseline.keys(), \
+ 'another model fixture owns this context'
+ providers = self.baseline.setdefault('providers', {})
+ assert isinstance(providers, dict) and 'fixture-native' not in providers
+ providers['fixture-native'] = {
+ 'type': 'openai-compatible', 'protocol': 'openai-responses', 'authType': 'bearer',
+ 'baseUrl': foreign_endpoint, 'apiKey': 'synthetic-unselected-native-key',
+ 'models': [{'model': 'native-default', 'contextWindow': 100000,
+ 'maxOutputTokens': 4096, 'capabilities': {'tools': True}}],
+ 'fixtureUnknownProviderKey': {'preserve': ['native', 'user']},
+ }
+ self.native_default = 'fixture-native/native-default'
+ self.baseline.setdefault('model', {})['name'] = self.native_default
+ self.baseline.setdefault('general', {})['enableAutoUpdate'] = False
+ self.baseline.setdefault('hooks', {})
+ self.baseline.setdefault('mcpServers', {})
+ self.baseline['hirouteAcceptance'] = {'unknown': ['preserve', secrets.token_hex(8)]}
+ self.write(self.baseline)
+
+ def read(self):
+ assert not self.path.is_symlink() and self.path.is_file(), 'settings target was replaced'
+ return json.loads(self.path.read_text())
+
+ def write(self, value):
+ assert not self.path.is_symlink(), 'refusing to write linked fixture settings'
+ self.path.write_text(json.dumps(value, indent=2) + '\n')
+ self.path.chmod(0o600)
+
+ def assert_preserved(self, provider_id, selected_default=None):
+ actual = self.read()
+ actual.get('providers', {}).pop(provider_id, None)
+ expected = deepcopy(self.baseline)
+ if selected_default is not None:
+ expected['model']['name'] = selected_default
+ assert actual == expected, 'model operation changed native/default/unknown user fields'
+
+ def add_user_edit(self, provider_id):
+ self.assert_preserved(provider_id)
+ text = self.path.read_text()
+ value = {'edited_after_apply': secrets.token_hex(8)}
+ # Add one root field without reserializing the managed provider. Otherwise
+ # a fixture's unrelated edit could manufacture owned-node formatting drift.
+ end = text.rfind('}')
+ updated = text[:end].rstrip() + ',\n "hirouteLaterEdit": ' + json.dumps(value) + '\n' + text[end:]
+ expected = self.read()
+ expected['hirouteLaterEdit'] = value
+ assert json.loads(updated) == expected, 'fixture root edit changed another field'
+ self.path.write_text(updated)
+ self.baseline['hirouteLaterEdit'] = value
+
+ def select_default(self, expected, replacement):
+ actual = self.read()
+ assert actual['model']['name'] == expected, 'fixture default changed independently'
+ actual['model']['name'] = replacement
+ text = self.path.read_text()
+ token = json.dumps(expected)
+ assert text.count(token) == 1, 'fixture default token is ambiguous'
+ updated = text.replace(token, json.dumps(replacement), 1)
+ assert json.loads(updated) == actual, 'fixture default edit changed another field'
+ self.path.write_text(updated)
+
+ def close(self):
+ assert self.read() == self.baseline, 'cannot undo fixture baseline while managed/drifted fields remain'
+ if self.original is None:
+ self.path.unlink()
+ else:
+ self.path.write_bytes(self.original)
+ self.path.chmod(self.original_mode)
+
+
+class PersistedRouteOracle:
+ def __init__(self, model):
+ self.model = model
+ self.marker = None
+ self.receipt = None
+ self.calls = []
+
+ def arm(self, label):
+ self.marker = 'PERSISTED-INPUT-' + secrets.token_hex(12)
+ self.receipt = 'PERSISTED-OUTPUT-' + secrets.token_hex(12)
+ self.label = label
+ return self.marker
+
+ def reply(self, _fixture, body):
+ assert body['model'] == self.model, 'persisted model reached the wrong source'
+ text = native_text(body)
+ if LIVE_PROMPT in text:
+ self.calls.append('live-check')
+ return dict(kind='text', text='HIROUTE_LIVE_CHECK_OK', request_kind='live-check')
+ assert self.marker is not None and self.marker in text, 'unplanned persisted model request'
+ self.calls.append(self.label)
+ return dict(kind='text', text=self.receipt, request_kind=self.label)
+
+
+def native_command(product, binary, selector, prompt):
+ # Ordinary settings precedence remains active. In particular, no --settings,
+ # --setting-sources or credential environment can hide a persistence defect.
+ return [str(binary), '--cwd', str(product.project), '--config-dir', product.env['QODER_CONFIG_DIR'],
+ '--model', selector, '--print', '--no-session-persistence', '--output-format', 'stream-json',
+ '--tools', 'Read', '--permission-mode', 'dont_ask', '--max-model-request-retries', '0',
+ '--max-turns', '2', '-p', prompt]
+
+
+def successful_native_result(stdout, receipt):
+ records = []
+ for line in stdout.decode().splitlines():
+ try:
+ value = json.loads(line)
+ except ValueError:
+ continue
+ if isinstance(value, dict) and value.get('type') == 'result':
+ records.append(value)
+ assert len(records) == 1, 'expected one native Qoder terminal result'
+ result = records[0]
+ assert result.get('subtype') == 'success' and result.get('is_error') is False, \
+ 'native Qoder terminal result is an error'
+ assert result.get('result', '').strip() == receipt, 'native result lost the independent source receipt'
+ assert isinstance(result.get('session_id'), str) and result['session_id'], 'native result lacks session identity'
+ return result['session_id']
+
+
+def read_persisted_route(product, binary, selector, source, oracle, label):
+ prompt = oracle.arm(label)
+ before = len(oracle.calls)
+ command = native_command(product, binary, selector, prompt)
+ # Product already strips inherited provider/auth variables. Only its selected
+ # native config root and private runtime/receipt roots enter this process.
+ stdout = run_native_command(product, command, timeout=60, label='ordinary Qoder model invocation')
+ assert oracle.calls[before:] == [label], 'ordinary Qoder did not make one actual persisted-route request'
+ native_session_id = successful_native_result(stdout, oracle.receipt)
+ return {'label': label, 'model': source.model, 'native_session_id': native_session_id, 'state': 'green'}
diff --git a/crates/daemon/tests/support/qoder_model_product.py b/crates/daemon/tests/support/qoder_model_product.py
new file mode 100644
index 00000000..26c58ac1
--- /dev/null
+++ b/crates/daemon/tests/support/qoder_model_product.py
@@ -0,0 +1,304 @@
+"""Save additional Qoder models, then read them through ordinary native Qoder.
+
+Uses production Local Control settings, publication and Gateway. Native starts
+read only the persisted provider in a dedicated, normally logged-in test context.
+The original four Worker/collaboration journeys remain separate.
+"""
+import hashlib
+import http.client
+import json
+from pathlib import Path
+import secrets
+import subprocess
+import sys
+
+from model_connections_product import save_native_source
+from agent_product_support import apply_settings, settings_status
+from native_context_boundaries import source_events
+from native_context_fixture import NativeContextUpstream, NativeProxyTrap, digest
+from native_context_product import report_failure, selected_installation
+from publication_process import plan_change
+from publication_product import Product, encoded
+from qoder_collaboration_product import AGENT, apply_collaboration, check_collaboration, restore_skill
+from qoder_model_fixture import (CASES, OwnedModelSettings, PersistedRouteOracle,
+ read_persisted_route, select_model_context)
+import qoder_native_context
+
+
+def model_spec(context, plans=None, restore_ref=None, regenerate=False):
+ model = ({'intent': 'restore', 'restore_point_ref': restore_ref} if restore_ref else
+ {'intent': 'configure', 'settings': {'mode': 'qoder_additional', 'allowed_plan_ids': plans}})
+ return {'schema_version': {'major': 2, 'minor': 0}, 'context_id': context, 'model': model,
+ 'collaboration': {'intent': 'keep'},
+ 'access_token': {'intent': 'regenerate' if regenerate else 'keep'}}
+
+
+def apply_models(product, spec, key):
+ return apply_settings(product, spec, key, 'model')
+
+
+def publish_source_plan(product, source, index):
+ saved = save_native_source(product, source, token=source.token, upstream_model_id=source.model,
+ variant='qoder-model-' + str(index), context_tokens=100000)
+ product.editor = {
+ 'schema': 'hiroute.plan-editor/v2', 'display_name': 'Additional Qoder route ' + str(index),
+ 'purpose': 'Read a persisted additional model route', 'mode': 'fixed_model',
+ 'candidates': [{'binding_id': saved['binding_id']}],
+ 'smart': {'economy': [], 'primary': [], 'primary_fallback': False,
+ 'reselect_on_user_message': False, 'classifier': {'kind': 'local_rules'}, 'complex_keywords': []},
+ 'free': {'candidates': [], 'primary': [], 'primary_fallback': False},
+ 'delegation_enabled': False, 'requirements': {},
+ 'limits': {'maximum_attempts': 1, 'request_timeout_ms': 30000, 'attempt_timeout_ms': 30000},
+ }
+ change = plan_change(product, 'create', 'qoder-model-plan-' + str(index))
+ preview = product.preview('routing preview', {'change': change})
+ product.apply('routing apply', 'ApplyAgentPlanChange', preview, {'change': change}, 'model-plan-' + str(index))
+ product.plan_id = preview['plan_head']['reference']['plan_id']
+ return {'plan_id': product.plan_id, 'alias': preview['plan_head']['model_alias']}
+
+
+def assert_configured(status, plans):
+ assert status['state'] == 'configured' and status.get('restore_point_ref'), 'model route is not configured'
+ assert status['current_selection'] == {'mode': 'qoder_additional', 'allowed_plan_ids': sorted(plans)}, \
+ 'model selection changed the selected Plan set'
+
+
+def assert_saved_aliases(settings, provider, aliases):
+ models = settings.read()['providers'][provider]['models']
+ assert len(models) == len(aliases) and {item['model'] for item in models} == set(aliases), \
+ 'persisted native choices do not match the selected routes'
+
+
+def live_check(product, context, aliases, oracles):
+ status = settings_status(product, context)
+ targets = [target for target in status.get('live_check_targets', []) if target['surface'] == 'qoder_cli']
+ assert len(targets) == 1 and set(targets[0]['client_model_ids']) == set(aliases), 'live scope lost persisted routes'
+ check = {'agent_id': AGENT, 'scope': 'live', 'suite': 'quick', 'allow_model_call': True, 'target': targets[0]}
+ consent = {'change_digest': 'sha256:' + hashlib.sha256(encoded(check)).hexdigest(),
+ 'expected_revisions': product.control('GetClientServiceStatus', {})['data']['revisions']}
+ capability = product.grant('CheckAgentConnection', consent, 'qoder-persisted-live')
+ before = [len(oracle.calls) for oracle in oracles]
+ product.cli('agents check', check, capability)
+ status = settings_status(product, context)
+ assert status['model_verified'] is True and any(
+ row['surface'] == 'qoder_cli' and row['state'] == 'passed'
+ and row['applied_revision'] == status['applied_revision'] for row in status['surface_results']), \
+ 'real persisted-route Live check did not verify the current publication'
+ assert all(oracle.calls[index:] == ['live-check'] for oracle, index in zip(oracles, before)), \
+ 'Live verification must actually request each selected persisted route once'
+
+
+def reject_gateway_request(product, token, alias, sources, expected_statuses):
+ before = [source.request_count() for source in sources]
+ client = http.client.HTTPConnection('127.0.0.1', product.port, timeout=10)
+ try:
+ client.request('POST', '/_hiroute/qoder/v1/responses', body=encoded({
+ 'model': alias, 'input': 'Untrusted removed route', 'max_output_tokens': 16, 'stream': True}),
+ headers={'Content-Type': 'application/json', 'Authorization': 'Bearer ' + token})
+ response = client.getresponse()
+ response.read()
+ assert response.status in expected_statuses, 'obsolete authority or removed alias was not rejected'
+ finally:
+ client.close()
+ assert [source.request_count() for source in sources] == before, 'rejected request reached a source'
+
+
+def assert_default_blocks_removal(product, context, settings, provider, plans, skill):
+ selected = provider + '/' + plans[0]['alias']
+ settings.select_default(settings.native_default, selected)
+ try:
+ status = settings_status(product, context)
+ before, skill_before = digest(settings.path), digest(skill)
+ original_token = product.bearer(product.agent_connection)
+ for spec in (model_spec(context, [plans[1]['plan_id']]),
+ model_spec(context, restore_ref=status['restore_point_ref'])):
+ command = 'agents restore' if spec['model']['intent'] == 'restore' else 'agents connect'
+ preview = product.preview(command + ' preview', {'spec': spec})
+ assert not preview['applicable'] and any(
+ item['reason'] == 'qoder_default_in_use' for item in preview['blockers']), \
+ 'removing the selected native default must fail closed'
+ assert digest(settings.path) == before and digest(skill) == skill_before, 'blocked removal changed files'
+ assert settings_status(product, context) == status, 'blocked removal changed settings authority'
+ assert product.bearer(product.agent_connection) == original_token, 'blocked removal changed the model token'
+ # Keeping the default-selected alias remains a legal user adjustment.
+ preview = product.preview('agents connect preview', {'spec': model_spec(context, [p['plan_id'] for p in plans])})
+ assert preview['applicable'], 'retaining the selected default was incorrectly rejected'
+ settings.assert_preserved(provider, selected_default=selected)
+ finally:
+ settings.select_default(selected, settings.native_default)
+
+
+def restore_models(product, context):
+ current = settings_status(product, context)
+ _, restored = apply_models(product, model_spec(context, restore_ref=current['restore_point_ref']),
+ 'qoder-model-restore')
+ assert restored['state'] == 'not_configured' and restored.get('current_selection') is None \
+ and restored.get('restore_point_ref') is None, 'model Restore did not release its selection/reference'
+
+
+def run(repository, candidate):
+ repo = Path(repository).resolve()
+ assert subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=repo, text=True).strip() == candidate
+ product = Product(repo)
+ sources, oracles, settings, context, skill = [], [], None, None, None
+ foreign = None
+ model_active = skill_active = False
+ before_skill = None
+ stage = 'dedicated-model-context'
+ report = dict(scenario='qoder-persisted-model-routes', candidate=candidate, worker_harness='qoder',
+ required_cases=list(CASES), selected_cases=list(CASES), cases=[], native_reads=[],
+ evidence_limit='Real persisted settings/native Qoder/Gateway; controlled sources; no Desktop verdict')
+ failed = False
+ cleanup_errors = []
+ try:
+ config = select_model_context(product)
+ binary, _, _ = selected_installation('qoder')
+ (product.root / 'bin/qodercli').symlink_to(binary)
+ foreign = NativeProxyTrap(product.root / 'unselected-native.log')
+ settings = OwnedModelSettings(config, foreign.url + '/v1')
+ product.enable_debug_diagnostics()
+ product.start()
+ plans = []
+ for index, model in enumerate(('gpt-5.4', 'gpt-5.5')):
+ controls = product.root / ('persisted-source-' + str(index))
+ controls.mkdir(mode=0o700)
+ (controls / 'native-context.json').write_text('{}')
+ source = NativeContextUpstream(controls)
+ source.model, source.token = model, 'synthetic-persisted-source-' + secrets.token_hex(12)
+ oracle = PersistedRouteOracle(model)
+ source.reply = oracle.reply
+ sources.append(source)
+ oracles.append(oracle)
+ plans.append(publish_source_plan(product, source, index))
+ agent = next(item for item in product.preview('agents scan')['agents'] if item['agent_id'] == AGENT)
+ context = agent['context_id']
+ product.agent_connection = 'agent-connection/' + context
+ stage = 'persist-model-routes'
+ plan_ids = [plan['plan_id'] for plan in plans]
+ preview, status = apply_models(product, model_spec(context, plan_ids), 'qoder-model-enable')
+ model_active = True
+ product.bearer(product.agent_connection) # Register the actual secret for output-leak checks immediately.
+ provider = preview['model_effect']['provider_id']
+ assert preview['model_effect']['endpoint'] == 'http://127.0.0.1:' + str(product.port) + '/_hiroute/qoder/v1'
+ assert_configured(status, plan_ids)
+ assert_saved_aliases(settings, provider, [plan['alias'] for plan in plans])
+ settings.assert_preserved(provider)
+ settings.add_user_edit(provider)
+ for index, plan in enumerate(plans):
+ report['native_reads'].append(read_persisted_route(product, binary, provider + '/' + plan['alias'],
+ sources[index], oracles[index], 'persisted-' + str(index)))
+ product.stop()
+ product.start()
+ report['native_reads'].append(read_persisted_route(product, binary, provider + '/' + plans[0]['alias'],
+ sources[0], oracles[0], 'after-daemon-restart'))
+ live_check(product, context, [plan['alias'] for plan in plans], oracles)
+ report['cases'].append({'id': CASES[0], 'state': 'green'})
+
+ stage = 'rotate-only-model-authority'
+ old_token = product.bearer(product.agent_connection)
+ _, status = apply_models(product, model_spec(context, plan_ids, regenerate=True), 'qoder-model-rotate')
+ assert_configured(status, plan_ids)
+ new_token = product.bearer(product.agent_connection)
+ assert old_token != new_token, 'model token rotation reused the prior credential'
+ reject_gateway_request(product, old_token, plans[0]['alias'], sources, (401, 403))
+ report['native_reads'].append(read_persisted_route(product, binary, provider + '/' + plans[1]['alias'],
+ sources[1], oracles[1], 'after-token-rotation'))
+ settings.assert_preserved(provider)
+ report['cases'].append({'id': CASES[1], 'state': 'green'})
+
+ stage = 'independent-model-and-skill'
+ (config / 'skills').mkdir(mode=0o700, exist_ok=True)
+ skill = qoder_native_context.prepare_collaboration_target(product)
+ before_skill = skill.read_bytes() if skill.exists() else None
+ check_collaboration(product, 'model-skill-preflight')
+ collaboration = apply_collaboration(product, context,
+ {'intent': 'configure', 'settings': {'trigger_mode': 'explicit'}}, 'model-skill-enable')
+ skill_active = True
+ check_collaboration(product, 'model-skill-installed')
+ restore_skill(product, context, collaboration['restore_point_ref'], before_skill, skill)
+ skill_active = False
+ assert_configured(settings_status(product, context), plan_ids)
+ report['native_reads'].append(read_persisted_route(product, binary, provider + '/' + plans[0]['alias'],
+ sources[0], oracles[0], 'after-skill-restore'))
+ # Restore invalidates evidence about the formerly installed Skill. A new
+ # configuration must prove the current capability rather than reuse it.
+ check_collaboration(product, 'model-skill-reenable-preflight')
+ collaboration = apply_collaboration(product, context,
+ {'intent': 'configure', 'settings': {'trigger_mode': 'explicit'}}, 'model-skill-enable-again')
+ skill_active = True
+ skill_digest = digest(skill)
+ assert_default_blocks_removal(product, context, settings, provider, plans, skill)
+ report['cases'].append({'id': CASES[3], 'state': 'green'})
+ _, status = apply_models(product, model_spec(context, [plan_ids[0]]), 'qoder-model-adjust')
+ assert_configured(status, [plan_ids[0]])
+ assert_saved_aliases(settings, provider, [plans[0]['alias']])
+ reject_gateway_request(product, product.bearer(product.agent_connection), plans[1]['alias'], sources, (403, 404))
+ report['native_reads'].append(read_persisted_route(product, binary, provider + '/' + plans[0]['alias'],
+ sources[0], oracles[0], 'after-route-adjustment'))
+ restore_models(product, context)
+ model_active = False
+ assert settings.read() == settings.baseline, 'model Restore did not preserve unrelated user edits'
+ assert digest(skill) == skill_digest, 'model Restore changed the independent Skill'
+ remaining = settings_status(product, context)['collaboration']
+ assert remaining['state'] == 'configured' and remaining['restore_point_ref'] == collaboration['restore_point_ref']
+ check_collaboration(product, 'skill-survives-model-restore')
+ report['cases'].append({'id': CASES[2], 'state': 'green'})
+ restore_skill(product, context, remaining['restore_point_ref'], before_skill, skill)
+ skill_active = False
+ assert not foreign.path.read_text().strip(), 'native defaults or providers unexpectedly received requests'
+ assert all(event['state'] == 'green' for source in sources for event in source_events(source))
+ assert all(source.request_count() == len(source_events(source)) for source in sources), \
+ 'an unrecorded rejected request reached the source'
+ diagnostics = product.diagnostics_snapshot()
+ assert diagnostics['state'] == 'complete' and diagnostics['level_applied']['level'] == 'debug'
+ report.update(state='green', diagnostics=diagnostics, persisted_aliases=[p['alias'] for p in plans],
+ native_default_preserved=True, unknown_user_fields_preserved=True, foreign_requests=0,
+ source_requests=[source.request_count() for source in sources], live_requests=2,
+ source_context_tokens=100000, source_output_tokens=4096,
+ binaries={name: digest(product.bin / name) for name in ('hiroute', 'hirouted')},
+ harness_sha256=digest(binary))
+ except Exception:
+ failed = True
+ raise
+ finally:
+ # Restore through production while its daemon is alive. A failed operation
+ # never authorizes deleting a managed provider or installed Skill directly.
+ for label, active, action in (
+ ('restore_model', model_active, lambda: restore_models(product, context)),
+ ('restore_skill', skill_active, lambda: restore_skill(product, context,
+ settings_status(product, context)['collaboration']['restore_point_ref'], before_skill, skill)),
+ ):
+ if active:
+ try:
+ if product.process is None:
+ product.start()
+ action()
+ except Exception as error:
+ cleanup_errors.append({'step': label, 'error_type': type(error).__name__})
+ if failed or cleanup_errors:
+ report['cleanup_failures'] = list(cleanup_errors)
+ try:
+ report_failure(product, report, stage)
+ except Exception as error:
+ cleanup_errors.append({'step': 'preserve_failure_report', 'error_type': type(error).__name__})
+ actions = [('close_product', product.close), ('owned_skill_directory', lambda: qoder_native_context.cleanup_context(product))]
+ if settings is not None:
+ actions.append(('owned_settings_baseline', settings.close))
+ actions.extend(('close_source', source.close) for source in sources)
+ if foreign is not None:
+ actions.append(('close_foreign', foreign.close))
+ for label, action in actions:
+ try:
+ action()
+ except Exception as error:
+ cleanup_errors.append({'step': label, 'error_type': type(error).__name__})
+ if cleanup_errors:
+ print(json.dumps({'scenario': 'qoder-model-cleanup', 'state': 'red', 'candidate': candidate,
+ 'primary_failure_preserved': failed, 'failures': cleanup_errors}), flush=True)
+ if not failed:
+ raise AssertionError('model acceptance cleanup failed')
+ print(json.dumps(report), flush=True)
+
+
+if __name__ == '__main__':
+ run(sys.argv[1], sys.argv[2])
diff --git a/crates/daemon/tests/support/qoder_native_context.py b/crates/daemon/tests/support/qoder_native_context.py
new file mode 100644
index 00000000..ebef9882
--- /dev/null
+++ b/crates/daemon/tests/support/qoder_native_context.py
@@ -0,0 +1,250 @@
+"""Qoder fixture facts; product lifecycle remains in the shared Worker journeys.
+
+Borrow an explicitly selected, normally logged-in context. Never copy authentication,
+rewrite user settings, or silently substitute the caller's daily HOME. The native
+history filename below is a pinned Qoder 1.1.65 fixture fact, not a product reader.
+"""
+import json
+import os
+from pathlib import Path
+import re
+import secrets
+import sqlite3
+import stat
+
+from native_context_fixture import NativeProxyTrap, digest, prepare, protect_configuration, write_new
+
+
+def selected_directory(name):
+ value = os.environ.get(name)
+ assert value, name + ' must explicitly select a normally logged-in Qoder context'
+ path = Path(value)
+ assert path.is_absolute() and path.is_dir(), name + ' must be an existing absolute directory'
+ return path.resolve(strict=True)
+
+
+def select_context(product):
+ home = selected_directory('HIROUTE_QODER_CONTEXT_HOME')
+ config = selected_directory('HIROUTE_QODER_CONFIG_DIR')
+ product.env.update(HOME=str(home), QODER_CONFIG_DIR=str(config))
+ # Qoder's own login state may refresh. Only native settings are part of the
+ # byte-preservation promise; no authentication file is opened by this fixture.
+ product.qoder_settings_before = settings_snapshot(config)
+
+
+def settings_snapshot(config):
+ result = {}
+ for name in ('settings.json', 'settings.local.json'):
+ path = Path(config) / name
+ assert not path.is_symlink(), 'linked Qoder settings need a separate explicit fixture'
+ result[name] = (dict(sha256=digest(path), mode=stat.S_IMODE(path.stat().st_mode))
+ if path.exists() else None)
+ return result
+
+
+def prepare_context(product):
+ config = Path(product.env['QODER_CONFIG_DIR'])
+ # Private, unique names let a real logged-in context be borrowed without
+ # replacing unrelated skills. Cleanup owns exactly these newly created files.
+ assert not (config / 'skills').is_symlink(), 'linked user skills are not fixture-owned'
+ product.qoder_owned_files = {}
+ fixture = prepare(Path(product.env['HOME']), config, product.project, 'qoder',
+ suffix='-' + secrets.token_hex(6), owned_files=product.qoder_owned_files)
+ fixture.update(product_storage=str(product.storage),
+ settings_before=product.qoder_settings_before,
+ native_context_setup='explicit-borrowed-login-context')
+ product.qoder_fixture = fixture
+ return fixture
+
+
+def assert_settings_preserved(fixture):
+ assert settings_snapshot(fixture['config']) == fixture['settings_before'], \
+ 'Qoder user settings or permissions changed'
+
+
+def directory_identity(path):
+ metadata = path.lstat()
+ assert stat.S_ISDIR(metadata.st_mode), 'collaboration Skill parent must be a real directory'
+ return (metadata.st_dev, metadata.st_ino, metadata.st_uid, stat.S_IMODE(metadata.st_mode))
+
+
+def prepare_collaboration_target(product):
+ """Own only a newly created empty leaf; the product must install the real Skill."""
+ directory = Path(product.env['QODER_CONFIG_DIR']) / 'skills/hiroute-collaboration'
+ try:
+ directory.mkdir(mode=0o700)
+ except FileExistsError:
+ # Existing directories belong to the user. Do not normalize permissions;
+ # the real settings operation must enforce its existing target guard.
+ directory_identity(directory)
+ else:
+ product.qoder_owned_collaboration_directory = (directory, directory_identity(directory))
+ return directory / 'SKILL.md'
+
+
+def cleanup_context(product):
+ fixture = getattr(product, 'qoder_fixture', None)
+ owned = getattr(product, 'qoder_owned_files', {})
+ collaboration_directory = getattr(product, 'qoder_owned_collaboration_directory', None)
+ if not owned and not collaboration_directory:
+ return
+ if fixture:
+ assert_settings_preserved(fixture)
+ config = Path(product.env['QODER_CONFIG_DIR'] if not fixture else fixture['config'])
+ # Never remove native history, auth, existing parent directories, or a changed
+ # file. Project receipts are already inside Product's private owned root.
+ parents = set()
+ for name, expected in owned.items():
+ path = Path(name)
+ if not path.is_relative_to(config):
+ continue
+ assert not path.is_symlink() and path.is_file() and digest(path) == expected, \
+ 'refusing cleanup of replaced Qoder fixture material'
+ path.unlink()
+ if path.parent.parent == config / 'skills':
+ parents.add(path.parent)
+ for parent in parents:
+ parent.rmdir()
+ if collaboration_directory:
+ directory, expected = collaboration_directory
+ if directory.exists() or directory.is_symlink():
+ assert directory_identity(directory) == expected and not any(directory.iterdir()), \
+ 'refusing cleanup of changed or nonempty collaboration Skill directory'
+ directory.rmdir()
+
+
+def task_session_root(fixture):
+ """Find one task only inside this Product's HiRoute-owned metadata."""
+ task_id = fixture['task_id']
+ sessions = Path(fixture['product_storage']) / 'delegation-workers/sessions'
+ found = []
+ for marker in sessions.glob('*/.hiroute-native-root-v1.json'):
+ assert not marker.is_symlink() and not marker.parent.is_symlink()
+ value = json.loads(marker.read_text())
+ if value['task_id'] != task_id:
+ continue
+ assert value['harness'] == 'qoder_cli'
+ descriptor = json.loads((marker.parent / 'borrowed-native-context.json').read_text())
+ assert descriptor['version'] == 1 and descriptor['harness'] == 'qoder_cli'
+ assert descriptor['context'] == {'home': fixture['home'], 'config_root': fixture['config'],
+ 'workspace': fixture['project']}
+ found.append(marker.parent)
+ assert len(found) == 1, 'expected one exact HiRoute task-owned native root'
+ return found[0]
+
+
+def task_binding(fixture):
+ binding = json.loads((task_session_root(fixture) / 'native-session-binding.json').read_text())
+ assert binding['version'] == 1
+ return binding['native_session_id']
+
+
+def history_directory(fixture):
+ """Pinned 1.1.65 layout for a short, fixture-owned canonical workspace only."""
+ workspace = str(Path(fixture['project']).resolve(strict=True))
+ assert len(workspace) <= 200, 'Qoder history fixture requires a short private workspace'
+ return Path(fixture['config']) / 'projects' / re.sub('[^a-zA-Z0-9]', '-', workspace)
+
+
+def exact_history(fixture):
+ return history_for_session(fixture, task_binding(fixture))
+
+
+def history_for_session(fixture, native_id):
+ assert re.fullmatch(r'[a-zA-Z0-9_-]+', native_id), 'unsafe native fixture session ID'
+ path = history_directory(fixture) / (native_id + '.jsonl')
+ assert not path.is_symlink() and path.is_file(), 'exact Qoder fixture transcript is absent'
+ assert fixture['receipt'] in path.read_text(), 'exact Qoder transcript lacks this task receipt'
+ return str(path), native_id
+
+
+def cancelled_history(fixture, run_id):
+ """Read only this fixture's exact cancelled task; this is not Continue eligibility.
+
+ Current runtime record_json is a registered test-only storage fact. Public
+ status exposes observation session links, not the opaque native session ID.
+ """
+ task_session_root(fixture) # Verify the task-owned descriptor and borrowed context.
+ database = Path(fixture['product_storage']) / 'live/runtime.db'
+ assert not database.is_symlink() and database.is_file()
+ with sqlite3.connect(database.as_uri() + '?mode=ro', uri=True) as connection:
+ task_row = connection.execute(
+ 'SELECT record_json FROM delegation_tasks WHERE workspace_id=? AND task_id=?',
+ ('personal/default', fixture['task_id'])).fetchone()
+ run_row = connection.execute(
+ 'SELECT record_json FROM delegation_runs WHERE workspace_id=? AND run_id=?',
+ ('personal/default', run_id)).fetchone()
+ assert task_row is not None and run_row is not None, 'exact cancelled task/run record is missing'
+ task, run = json.loads(task_row[0]), json.loads(run_row[0])
+ assert (task['task_id'] == run['task_id'] == fixture['task_id']
+ and task['latest_run_id'] == run['run_id'] == run_id
+ and task['plan']['harness'] == 'qoder_cli'
+ and run['progress']['state'] == 'cancelled'
+ and run['progress']['cleanup'] == 'complete'), 'exact cancelled task identity or cleanup mismatch'
+ session = task['session']
+ assert (session and isinstance(session.get('native_session_id'), str)
+ and session['native_session_id'] == session['acp_session_id']), \
+ 'cancelled Qoder task lacks one exact native session identity'
+ return history_for_session(fixture, session['native_session_id'])
+
+
+def assert_restricted_modes_unavailable(product, upstream):
+ """Unsupported native policies must fail before any real model/tool action."""
+ from delegation_product import worker_cli, wait_for_worker_result
+ events = upstream.controls / 'native-context-events.jsonl'
+ before = events.read_bytes() if events.exists() else b''
+ root = product.root / 'qoder-restricted-workspace'
+ root.mkdir(mode=0o700)
+ marker = root / 'must-not-exist'
+ for policy in ('approve-reads', 'deny-all'):
+ command = ('worker exec --plan ' + product.plan_id + ' --cwd ' + str(root) +
+ ' --permission-policy ' + policy + ' --run-timeout 30 --no-wait' +
+ ' --submission-key qoder-restricted-' + policy + ' --file - --output json')
+ status, response = worker_cli(product, command, 'Write must-not-exist then return done.', success=False)
+ if status == 0:
+ accepted = response['data']
+ result = wait_for_worker_result(product, accepted['run_id'], expected='failed', timeout=30)
+ assert not result.get('result'), 'unsupported Qoder policy returned a result'
+ else:
+ assert response.get('error', {}).get('code') == 'CAPABILITY_UNAVAILABLE', response
+ assert not marker.exists(), 'unsupported Qoder policy executed a tool'
+ assert (events.read_bytes() if events.exists() else b'') == before, \
+ 'unsupported Qoder policy sent a model prompt'
+ return ['approve-reads', 'deny-all']
+
+
+def replace_current_context(product):
+ """Continue must use its original descriptor, not this new unlogged-in context."""
+ home = product.root / 'replacement-qoder-home'
+ home.mkdir(mode=0o700)
+ config = home / '.qoder'
+ config.mkdir(mode=0o700)
+ product.env.update(HOME=str(home), QODER_CONFIG_DIR=str(config))
+
+
+def project_conflict_settings(endpoint):
+ """A native core-route override targeting an observable foreign loopback source."""
+ selected = 'fixture-foreign/wrong-project-model'
+ return {
+ 'general': {'enableAutoUpdate': False, 'sessionRetention': {'enabled': False},
+ 'plan': {'modelRouting': False}},
+ 'disableAllHooks': True, 'promptSuggestionEnabled': False,
+ 'model': {'name': selected},
+ 'modelConfigs': {'overrides': [
+ {'match': {'overrideScope': 'core'}, 'modelConfig': {'model': selected}}]},
+ 'providers': {'fixture-foreign': {'protocol': 'openai-responses', 'baseUrl': endpoint,
+ 'apiKey': 'synthetic-foreign-no-authority', 'model': 'wrong-project-model',
+ 'models': [{'model': 'wrong-project-model', 'capabilities': {'tools': True}}],
+ 'routing': {purpose: 'wrong-project-model' for purpose in (
+ 'utility', 'session_title', 'summary', 'compact', 'subagent')}}},
+ }
+
+
+def install_project_conflict(fixture, upstream):
+ assert upstream.proxy_trap is None
+ trap = NativeProxyTrap(upstream.controls / 'qoder-foreign-project-requests.log')
+ upstream.proxy_trap = trap
+ fixture['foreign_route_events'] = str(trap.path)
+ settings = Path(fixture['project']) / '.qoder/settings.json'
+ write_new(settings, json.dumps(project_conflict_settings(trap.url + '/v1')))
+ protect_configuration(fixture, [settings])
diff --git a/crates/daemon/tests/support/standalone_headless_product.py b/crates/daemon/tests/support/standalone_headless_product.py
index 97078c77..6f8fd4a2 100644
--- a/crates/daemon/tests/support/standalone_headless_product.py
+++ b/crates/daemon/tests/support/standalone_headless_product.py
@@ -206,7 +206,7 @@ finally:
import http.client, json, os, sys
from urllib.parse import urlparse
config = json.loads(os.environ['CODEX_CONFIG'])
-base = urlparse(config['model_providers']['hiroute']['base_url'])
+base = urlparse(config['model_providers'][config['model_provider']]['base_url'])
token = os.environ['HIROUTE_RUN_TOKEN']
session = 'headless-acp-session'
for line in sys.stdin:
@@ -217,7 +217,10 @@ for line in sys.stdin:
elif method == 'session/new':
result = {'sessionId': session, '_meta': {'agentSessionId': session}, 'modes': {
'currentModeId': 'agent-full-access',
- 'availableModes': [{'id': 'agent-full-access', 'name': 'Autonomous'}]}}
+ 'availableModes': [{'id': 'agent-full-access', 'name': 'Autonomous'}]},
+ 'configOptions': [{'id': 'model', 'name': 'Model', 'type': 'select',
+ 'currentValue': config['model'],
+ 'options': [{'value': config['model'], 'name': config['model']}]}]}
elif method == 'session/set_mode':
result = {}
elif method == 'session/prompt':
diff --git a/crates/domain/src/agents/emulator.rs b/crates/domain/src/agents/emulator.rs
index ecc2bcc7..6654213a 100644
--- a/crates/domain/src/agents/emulator.rs
+++ b/crates/domain/src/agents/emulator.rs
@@ -37,7 +37,11 @@ impl BuiltInAgentProbeV1 {
Ok(Self {
profile_id: profile.profile_id.clone(),
integration_profile_ref: profile.integration_profile_ref.clone(),
- protocol: profile.client_protocol(),
+ protocol: profile
+ .model_connection()
+ .map_err(|_| AgentEmulatorError::InvalidProfile)?
+ .ok_or(AgentEmulatorError::InvalidProfile)?
+ .ingress_protocol,
model_alias,
traffic_kind: AgentTrafficKindV1::ConnectivityProbe,
prompt: CONNECTIVITY_PROBE_PROMPT_V1.to_owned(),
@@ -51,7 +55,7 @@ impl BuiltInAgentProbeV1 {
.map_err(|_| AgentEmulatorError::InvalidProfile)?;
if self.profile_id != profile.profile_id
|| self.integration_profile_ref != profile.integration_profile_ref
- || self.protocol != profile.client_protocol()
+ || Some(self.protocol) != profile.client_protocol()
|| self.traffic_kind != AgentTrafficKindV1::ConnectivityProbe
|| self.prompt != CONNECTIVITY_PROBE_PROMPT_V1
|| self.allow_tools
diff --git a/crates/domain/src/agents/mod.rs b/crates/domain/src/agents/mod.rs
index 2d2287d9..1029b7f7 100644
--- a/crates/domain/src/agents/mod.rs
+++ b/crates/domain/src/agents/mod.rs
@@ -9,6 +9,7 @@ mod model_grant;
mod native_artifacts;
mod plan_references;
mod profile;
+mod qoder_model;
mod settings;
mod skill_installation;
mod surface_check;
@@ -22,9 +23,13 @@ pub use model_grant::*;
pub use native_artifacts::*;
pub use plan_references::*;
pub use profile::*;
+pub use qoder_model::*;
pub use settings::*;
pub use skill_installation::*;
pub use surface_check::*;
#[cfg(test)]
mod tests;
+
+#[cfg(test)]
+mod optional_model_tests;
diff --git a/crates/domain/src/agents/model_grant.rs b/crates/domain/src/agents/model_grant.rs
index 6a97ace9..93afe5d9 100644
--- a/crates/domain/src/agents/model_grant.rs
+++ b/crates/domain/src/agents/model_grant.rs
@@ -77,7 +77,8 @@ impl AgentModelGrantV2 {
if !matches!(
(selection, protocol),
(
- AgentModelSelectionV2::CodexDefault { .. },
+ AgentModelSelectionV2::CodexDefault { .. }
+ | AgentModelSelectionV2::QoderAdditional { .. },
AgentIngressProtocolV1::Responses
) | (
AgentModelSelectionV2::ClaudeLauncher { .. },
@@ -251,7 +252,8 @@ impl AgentModelGrantV2 {
if !matches!(
(selection, self.protocol),
(
- AgentModelSelectionV2::CodexDefault { .. },
+ AgentModelSelectionV2::CodexDefault { .. }
+ | AgentModelSelectionV2::QoderAdditional { .. },
AgentIngressProtocolV1::Responses
) | (
AgentModelSelectionV2::ClaudeLauncher { .. },
@@ -383,6 +385,38 @@ mod tests {
);
}
+ #[test]
+ fn qoder_additional_routes_authorize_only_selected_plans_without_native_defaults() {
+ let selection = AgentModelSelectionV2::QoderAdditional {
+ allowed_plan_ids: [AgentPlanId::parse("plan/example").unwrap()].into(),
+ };
+ let grant = grant();
+ assert!(grant.validate_selection(&selection).is_ok());
+ assert!(grant.codex_default_override(&selection).is_err());
+ assert!(selection.fixed_models().is_empty());
+ let other = AgentModelSelectionV2::QoderAdditional {
+ allowed_plan_ids: [AgentPlanId::parse("plan/other").unwrap()].into(),
+ };
+ assert!(grant.validate_selection(&other).is_err());
+ let wrong_protocol =
+ AgentModelGrantV2::seal(AgentIngressProtocolV1::Messages, grant.routes).unwrap();
+ assert!(wrong_protocol.validate_selection(&selection).is_err());
+ assert!(
+ AgentModelSelectionV2::QoderAdditional {
+ allowed_plan_ids: Default::default(),
+ }
+ .validate()
+ .is_err()
+ );
+ for forbidden in ["default_selection", "fixed_models", "native_model_mode"] {
+ let mut wire = serde_json::to_value(&selection).unwrap();
+ wire.as_object_mut()
+ .unwrap()
+ .insert(forbidden.into(), serde_json::Value::Null);
+ assert!(serde_json::from_value::<AgentModelSelectionV2>(wire).is_err());
+ }
+ }
+
#[test]
fn claude_presets_keep_absence_and_native_values_without_a_default() {
use crate::{
diff --git a/crates/domain/src/agents/native_artifacts.rs b/crates/domain/src/agents/native_artifacts.rs
index fb05834f..2594ae5d 100644
--- a/crates/domain/src/agents/native_artifacts.rs
+++ b/crates/domain/src/agents/native_artifacts.rs
@@ -36,6 +36,15 @@ pub trait NativeAgentArtifactPort: ExternalEffectPort {
intent: &ExternalEffectIntentV1,
) -> PortResult<bool>;
fn read_native_target(&self, target: &str) -> PortResult<Option<Zeroizing<Vec<u8>>>>;
+ /// Read a native file containing a local bearer only after verifying owner-only 0600
+ /// permissions on the same opened file used for reading. Import/restore of ordinary user
+ /// configuration remains on read_native_target; unsupported adapters must fail closed.
+ fn read_private_native_target(&self, _target: &str) -> PortResult<Option<Zeroizing<Vec<u8>>>> {
+ Err(crate::PortError::new(
+ crate::PortErrorCode::PermissionDenied,
+ "native.private_read.unsupported",
+ ))
+ }
fn save_native_restore(
&self,
operation: &OperationId,
diff --git a/crates/domain/src/agents/optional_model_tests.rs b/crates/domain/src/agents/optional_model_tests.rs
new file mode 100644
index 00000000..f112f97f
--- /dev/null
+++ b/crates/domain/src/agents/optional_model_tests.rs
@@ -0,0 +1,73 @@
+use super::*;
+
+#[test]
+fn existing_model_profiles_keep_their_serialized_bytes() {
+ for original in [
+ r#"{"schema":"hiroute.agent-profile/v1","profile_id":"codex.fixture","integration_profile_ref":"integration/codex/fixture","kind":"codex","exact_versions":["1.2.3"],"ingress_protocol":"responses","config_precedence":["process","launch","project","user","managed"],"owned_config_fields":[{"field_id":"model","path":"model","write_layer":"user"}],"dynamic_catalog":false,"static_catalog_fallback":false,"native_subagent_routing":false}"#,
+ r#"{"schema":"hiroute.agent-profile/v1","profile_id":"claude_code.fixture","integration_profile_ref":"integration/claude_code/fixture","kind":"claude_code","exact_versions":["1.2.3"],"ingress_protocol":"messages","config_precedence":["managed","process","launch","project","user"],"owned_config_fields":[{"field_id":"model","path":"model","write_layer":"user"}],"dynamic_catalog":false,"static_catalog_fallback":false,"native_subagent_routing":false}"#,
+ ] {
+ let profile: AgentProfileV1 = serde_json::from_str(original).unwrap();
+ profile.validate().unwrap();
+ assert!(profile.model_connection().unwrap().is_some());
+ assert_eq!(serde_json::to_string(&profile).unwrap(), original);
+ }
+}
+
+#[test]
+fn collaboration_only_profile_cannot_authorize_model_configuration_or_probe() {
+ let json = r#"{"schema":"hiroute.agent-profile/v1","profile_id":"qoder.native.v1","integration_profile_ref":"integration/qoder/v1","kind":"qoder","config_precedence":[],"owned_config_fields":[],"dynamic_catalog":false,"static_catalog_fallback":false,"native_subagent_routing":false}"#;
+ let profile: AgentProfileV1 = serde_json::from_str(json).unwrap();
+ assert!(profile.model_connection().unwrap().is_none());
+ assert_eq!(serde_json::to_string(&profile).unwrap(), json);
+ assert!(
+ BuiltInAgentProbeV1::for_profile(
+ &profile,
+ crate::ModelAlias::parse_custom("example").unwrap()
+ )
+ .is_err()
+ );
+ let mut forged = profile.clone();
+ forged.ingress_protocol = Some(AgentIngressProtocolV1::Responses);
+ assert!(forged.model_connection().is_err());
+ forged = profile.clone();
+ forged
+ .owned_config_fields
+ .push(OwnedConfigFieldV1::new("model", "model", ConfigLayerV1::User).unwrap());
+ assert!(forged.validate().is_err());
+ forged = profile;
+ forged.kind = AgentKindV1::Codex;
+ assert!(forged.validate().is_err());
+}
+
+#[test]
+fn qoder_model_capability_does_not_claim_native_catalog_or_default_ownership() {
+ let mut profile = AgentProfileV1 {
+ schema: AGENT_PROFILE_SCHEMA_V1.into(),
+ profile_id: "qoder-collaboration-v1".into(),
+ integration_profile_ref: "builtin/qoder-collaboration/v1".into(),
+ kind: AgentKindV1::Qoder,
+ legacy_exact_versions: Default::default(),
+ ingress_protocol: Some(AgentIngressProtocolV1::Responses),
+ config_precedence: AgentKindV1::Qoder.config_precedence().to_vec(),
+ owned_config_fields: vec![
+ OwnedConfigFieldV1::new(
+ "additional_provider",
+ "hiroute.additional_provider",
+ ConfigLayerV1::User,
+ )
+ .unwrap(),
+ ],
+ dynamic_catalog: false,
+ static_catalog_fallback: false,
+ native_subagent_routing: false,
+ spawn_guidance: None,
+ managed_launch: None,
+ };
+ assert!(profile.model_connection().unwrap().is_some());
+ assert_eq!(profile.catalog_delivery(true), None);
+ profile.dynamic_catalog = true;
+ assert!(profile.validate().is_err());
+ profile.dynamic_catalog = false;
+ profile.ingress_protocol = Some(AgentIngressProtocolV1::Messages);
+ assert!(profile.validate().is_err());
+}
diff --git a/crates/domain/src/agents/profile.rs b/crates/domain/src/agents/profile.rs
index 27b70a13..33757bdc 100644
--- a/crates/domain/src/agents/profile.rs
+++ b/crates/domain/src/agents/profile.rs
@@ -13,27 +13,34 @@ pub const AGENT_PROFILE_SCHEMA_V1: &str = "hiroute.agent-profile/v1";
pub enum AgentKindV1 {
Codex,
ClaudeCode,
+ Qoder,
}
impl AgentKindV1 {
/// Native adapter order, highest priority first. Managed Claude policy is a
/// constraint on every lower layer, including the caller's environment.
- pub const fn config_precedence(self) -> [ConfigLayerV1; 5] {
+ pub const fn config_precedence(self) -> &'static [ConfigLayerV1] {
match self {
- Self::Codex => [
+ Self::Codex => &[
ConfigLayerV1::Process,
ConfigLayerV1::Launch,
ConfigLayerV1::Project,
ConfigLayerV1::User,
ConfigLayerV1::Managed,
],
- Self::ClaudeCode => [
+ Self::ClaudeCode => &[
ConfigLayerV1::Managed,
ConfigLayerV1::Process,
ConfigLayerV1::Launch,
ConfigLayerV1::Project,
ConfigLayerV1::User,
],
+ Self::Qoder => &[
+ ConfigLayerV1::Process,
+ ConfigLayerV1::Local,
+ ConfigLayerV1::Project,
+ ConfigLayerV1::User,
+ ],
}
}
@@ -41,6 +48,7 @@ impl AgentKindV1 {
match self {
Self::Codex => "codex",
Self::ClaudeCode => "claude_code",
+ Self::Qoder => "qoder",
}
}
}
@@ -56,6 +64,7 @@ pub enum AgentIngressProtocolV1 {
#[serde(rename_all = "snake_case")]
pub enum ConfigLayerV1 {
Process,
+ Local,
Launch,
Project,
User,
@@ -63,18 +72,17 @@ pub enum ConfigLayerV1 {
}
impl ConfigLayerV1 {
- pub fn precedence_for(self, kind: AgentKindV1) -> usize {
+ pub fn precedence_for(self, kind: AgentKindV1) -> Option<usize> {
kind.config_precedence()
.iter()
.position(|layer| *layer == self)
- .expect("each native order contains every layer")
}
/// Smaller values have higher effective precedence.
pub const fn precedence(self) -> u8 {
match self {
Self::Process => 0,
- Self::Launch => 1,
+ Self::Launch | Self::Local => 1,
Self::Project => 2,
Self::User => 3,
Self::Managed => 4,
@@ -159,7 +167,8 @@ pub struct AgentProfileV1 {
skip_serializing_if = "BTreeSet::is_empty"
)]
pub legacy_exact_versions: BTreeSet<String>,
- pub ingress_protocol: AgentIngressProtocolV1,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub ingress_protocol: Option<AgentIngressProtocolV1>,
pub config_precedence: Vec<ConfigLayerV1>,
pub owned_config_fields: Vec<OwnedConfigFieldV1>,
pub dynamic_catalog: bool,
@@ -178,10 +187,33 @@ impl AgentProfileV1 {
}
validate_identifier(&self.profile_id)?;
validate_identifier(&self.integration_profile_ref)?;
- let expected_precedence = self.kind.config_precedence();
- if self.config_precedence.as_slice() != expected_precedence {
+ // Previously accepted collaboration-only Qoder profiles retain their original shape.
+ // Their empty capability must never be upgraded implicitly during journal recovery.
+ if self.kind == AgentKindV1::Qoder && self.ingress_protocol.is_none() {
+ if !self.config_precedence.is_empty()
+ || !self.owned_config_fields.is_empty()
+ || self.dynamic_catalog
+ || self.static_catalog_fallback
+ || self.native_subagent_routing
+ || self.spawn_guidance.is_some()
+ || self.managed_launch.is_some()
+ {
+ return Err(AgentProfileError::ProtocolKindMismatch);
+ }
+ return Ok(());
+ }
+ if self.config_precedence.as_slice() != self.kind.config_precedence() {
return Err(AgentProfileError::InvalidConfigPrecedence);
}
+ if self.kind == AgentKindV1::Qoder
+ && (self.dynamic_catalog
+ || self.static_catalog_fallback
+ || self.native_subagent_routing
+ || self.spawn_guidance.is_some()
+ || self.managed_launch.is_some())
+ {
+ return Err(AgentProfileError::InvalidCatalogCapability);
+ }
if self.owned_config_fields.is_empty() {
return Err(AgentProfileError::InvalidConfigField);
}
@@ -208,25 +240,39 @@ impl AgentProfileV1 {
}
if let Some(managed_launch) = &self.managed_launch
&& (self.kind != AgentKindV1::ClaudeCode
- || self.ingress_protocol != AgentIngressProtocolV1::Messages
+ || self.ingress_protocol != Some(AgentIngressProtocolV1::Messages)
|| managed_launch.validate().is_err())
{
return Err(AgentProfileError::InvalidManagedLaunch);
}
match (self.kind, self.ingress_protocol) {
- (AgentKindV1::Codex, AgentIngressProtocolV1::Responses)
- | (AgentKindV1::ClaudeCode, AgentIngressProtocolV1::Messages) => Ok(()),
+ (AgentKindV1::Codex | AgentKindV1::Qoder, Some(AgentIngressProtocolV1::Responses))
+ | (AgentKindV1::ClaudeCode, Some(AgentIngressProtocolV1::Messages)) => Ok(()),
_ => Err(AgentProfileError::ProtocolKindMismatch),
}
}
+ /// A validated model capability view. Collaboration-only profiles deliberately have none.
+ pub fn model_connection(
+ &self,
+ ) -> Result<Option<AgentModelConnectionProfileV1<'_>>, AgentProfileError> {
+ self.validate()?;
+ Ok(self
+ .ingress_protocol
+ .map(|ingress_protocol| AgentModelConnectionProfileV1 {
+ ingress_protocol,
+ config_precedence: &self.config_precedence,
+ owned_config_fields: &self.owned_config_fields,
+ }))
+ }
+
pub fn supports_managed_launch(&self) -> bool {
self.managed_launch
.as_ref()
.is_some_and(|capability| capability.validate().is_ok())
}
- pub const fn client_protocol(&self) -> AgentIngressProtocolV1 {
+ pub const fn client_protocol(&self) -> Option<AgentIngressProtocolV1> {
self.ingress_protocol
}
@@ -249,6 +295,14 @@ impl AgentProfileV1 {
}
}
+/// Borrowed, validated model configuration facts; never a second wire profile.
+#[derive(Clone, Copy, Debug)]
+pub struct AgentModelConnectionProfileV1<'a> {
+ pub ingress_protocol: AgentIngressProtocolV1,
+ pub config_precedence: &'a [ConfigLayerV1],
+ pub owned_config_fields: &'a [OwnedConfigFieldV1],
+}
+
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct EffectiveConfigFieldV1 {
@@ -296,6 +350,9 @@ impl SupportedAgentInstallationV1 {
&self,
desired: &BTreeMap<String, Option<Value>>,
) -> Result<BTreeMap<String, Option<Value>>, AgentDiscoveryError> {
+ self.profile
+ .validate()
+ .map_err(|_| AgentDiscoveryError::UnownedConfigField)?;
let owned = self
.profile
.owned_config_fields
diff --git a/crates/domain/src/agents/qoder_model.rs b/crates/domain/src/agents/qoder_model.rs
new file mode 100644
index 00000000..583cd244
--- /dev/null
+++ b/crates/domain/src/agents/qoder_model.rs
@@ -0,0 +1,78 @@
+//! Native budget and additional-model declarations shared by Qoder settings and Workers.
+use serde::{Deserialize, Serialize};
+
+/// Explicit local model-grant bearer channel for Qoder's fixed native auth headers.
+/// The ordinary Responses endpoint retains its independent X-HiRoute-Token channel.
+pub const QODER_MODEL_BASE_PATH: &str = "/_hiroute/qoder/v1";
+
+#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)]
+#[error("Qoder budget is invalid: {stage}")]
+pub struct QoderBudgetError {
+ pub stage: &'static str,
+}
+
+fn budget_error(stage: &'static str) -> QoderBudgetError {
+ QoderBudgetError { stage }
+}
+
+// Qoder 1.1.65's catalogue-backed gdA/Uce and Iwe reserve at most 20K output
+// tokens, then max(13K, 5% of the remaining window) for auto-compaction.
+// maxOutputTokens changes that catalogue; the ACP CLI output flag does not.
+const OUTPUT_RESERVATION_LIMIT: u64 = 20_000;
+const COMPACTION_MARGIN: u64 = 13_000;
+const MAX_NATIVE_INTEGER: u64 = (1 << 53) - 1;
+
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub struct QoderTokenBudget {
+ pub context_window_tokens: u64,
+ pub max_output_tokens: u64,
+}
+
+impl QoderTokenBudget {
+ pub fn new(
+ context_window_tokens: u64,
+ max_output_tokens: u64,
+ ) -> Result<Self, QoderBudgetError> {
+ validate_qoder_output_budget(max_output_tokens)?;
+ if context_window_tokens > MAX_NATIVE_INTEGER {
+ return Err(budget_error("native token budget"));
+ }
+ let available = context_window_tokens
+ .checked_sub(max_output_tokens.min(OUTPUT_RESERVATION_LIMIT))
+ .ok_or_else(|| budget_error("native token budget"))?;
+ if available <= COMPACTION_MARGIN.max(available / 20) {
+ return Err(budget_error("native token budget"));
+ }
+ // A positive threshold is not a promise that arbitrary skills or prompts fit.
+ Ok(Self {
+ context_window_tokens,
+ max_output_tokens,
+ })
+ }
+}
+
+pub fn validate_qoder_output_budget(tokens: u64) -> Result<(), QoderBudgetError> {
+ if tokens == 0 || tokens > MAX_NATIVE_INTEGER {
+ return Err(budget_error("native output budget"));
+ }
+ Ok(())
+}
+
+/// Non-secret native model declaration sealed in a settings Operation.
+#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
+#[serde(deny_unknown_fields)]
+pub struct QoderAdditionalModelV1 {
+ pub alias: String,
+ pub context_window_tokens: u64,
+ pub max_output_tokens: u64,
+}
+
+impl QoderAdditionalModelV1 {
+ pub fn validate(&self) -> Result<(), crate::AgentConnectionError> {
+ crate::ModelAlias::parse(&self.alias)
+ .map_err(|_| crate::AgentConnectionError::InvalidGrant)?;
+ QoderTokenBudget::new(self.context_window_tokens, self.max_output_tokens)
+ .map_err(|_| crate::AgentConnectionError::InvalidGrant)?;
+ Ok(())
+ }
+}
diff --git a/crates/domain/src/agents/settings.rs b/crates/domain/src/agents/settings.rs
index a40a4e95..17faff42 100644
--- a/crates/domain/src/agents/settings.rs
+++ b/crates/domain/src/agents/settings.rs
@@ -26,6 +26,9 @@ pub enum AgentModelSelectionV2 {
allowed_plan_ids: BTreeSet<AgentPlanId>,
default_selection: AgentModelDefaultSelectionV2,
},
+ QoderAdditional {
+ allowed_plan_ids: BTreeSet<AgentPlanId>,
+ },
ClaudeLauncher {
surfaces: BTreeSet<AgentModelSurfaceV2>,
fixed_models: Vec<AgentFixedModelSelectionV2>,
@@ -46,6 +49,7 @@ pub enum AgentModelSurfaceV2 {
CodexCli,
CodexDesktop,
ClaudeCli,
+ QoderCli,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
@@ -92,6 +96,7 @@ impl AgentModelSelectionV2 {
Self::CodexDefault { fixed_models, .. } | Self::ClaudeLauncher { fixed_models, .. } => {
fixed_models
}
+ Self::QoderAdditional { .. } => &[],
}
}
@@ -99,7 +104,8 @@ impl AgentModelSelectionV2 {
match self {
Self::CodexDefault {
allowed_plan_ids, ..
- } => allowed_plan_ids.clone(),
+ }
+ | Self::QoderAdditional { allowed_plan_ids } => allowed_plan_ids.clone(),
Self::ClaudeLauncher {
preset_mappings, ..
} => [
@@ -148,6 +154,7 @@ impl AgentModelSelectionV2 {
AgentModelDefaultSelectionV2::Plan { plan_id } if plans.contains(plan_id) => {}
_ => return Err(invalid),
},
+ Self::QoderAdditional { .. } => {}
Self::ClaudeLauncher { surfaces, .. } => {
if *surfaces != BTreeSet::from([AgentModelSurfaceV2::ClaudeCli]) {
return Err(invalid);
diff --git a/crates/domain/src/agents/tests.rs b/crates/domain/src/agents/tests.rs
index 9bd0224d..5cd82e68 100644
--- a/crates/domain/src/agents/tests.rs
+++ b/crates/domain/src/agents/tests.rs
@@ -12,7 +12,7 @@ fn profile(kind: AgentKindV1, protocol: AgentIngressProtocolV1) -> AgentProfileV
integration_profile_ref: format!("integration/{}/v1", kind.as_str()),
kind,
legacy_exact_versions: BTreeSet::from(["1.2.3".to_owned()]),
- ingress_protocol: protocol,
+ ingress_protocol: Some(protocol),
config_precedence: kind.config_precedence().to_vec(),
owned_config_fields: vec![
OwnedConfigFieldV1::new("provider", "model_provider", ConfigLayerV1::User).unwrap(),
@@ -39,7 +39,7 @@ fn agents_profiles_bind_protocol_to_exact_kind_and_version() {
assert!(codex.validate().is_ok());
let mut invalid = codex;
- invalid.ingress_protocol = AgentIngressProtocolV1::Messages;
+ invalid.ingress_protocol = Some(AgentIngressProtocolV1::Messages);
assert_eq!(
invalid.validate().unwrap_err(),
AgentProfileError::ProtocolKindMismatch
diff --git a/crates/domain/src/delegation/installation.rs b/crates/domain/src/delegation/installation.rs
new file mode 100644
index 00000000..5b0b60a0
--- /dev/null
+++ b/crates/domain/src/delegation/installation.rs
@@ -0,0 +1,50 @@
+//! Validated launch shape; paths remain caller-selected metadata, not execution authority.
+use super::WorkerHarnessV1;
+use crate::OperationValidationError;
+
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub enum WorkerLaunchFormV1<'a> {
+ AdapterAcp {
+ adapter: &'a str,
+ cli: &'a str,
+ node: Option<&'a str>,
+ },
+ NativeAcp {
+ cli: &'a str,
+ },
+}
+
+impl<'a> WorkerLaunchFormV1<'a> {
+ pub fn validate(
+ harness: WorkerHarnessV1,
+ adapter: Option<&'a str>,
+ cli: &'a str,
+ node: Option<&'a str>,
+ ) -> Result<Self, OperationValidationError> {
+ let invalid = || OperationValidationError::UnregisteredEffectPlan;
+ if !absolute_path(cli)
+ || adapter.is_some_and(|path| !absolute_path(path))
+ || node.is_some_and(|path| !absolute_path(path))
+ {
+ return Err(invalid());
+ }
+ match harness {
+ WorkerHarnessV1::CodexCli | WorkerHarnessV1::ClaudeCode => Ok(Self::AdapterAcp {
+ adapter: adapter.ok_or_else(invalid)?,
+ cli,
+ node,
+ }),
+ WorkerHarnessV1::QoderCli if adapter.is_none() && node.is_none() => {
+ Ok(Self::NativeAcp { cli })
+ }
+ WorkerHarnessV1::QoderCli => Err(invalid()),
+ }
+ }
+}
+
+fn absolute_path(value: &str) -> bool {
+ !value.is_empty()
+ && value.len() <= 4096
+ && !value.contains(char::is_control)
+ && std::path::Path::new(value).is_absolute()
+}
diff --git a/crates/domain/src/delegation/mod.rs b/crates/domain/src/delegation/mod.rs
index cb0d34d9..927a8871 100644
--- a/crates/domain/src/delegation/mod.rs
+++ b/crates/domain/src/delegation/mod.rs
@@ -2,6 +2,8 @@
use serde::{Deserialize, Serialize};
use thiserror::Error;
+mod installation;
+pub use installation::*;
mod progress;
pub use progress::*;
mod process;
@@ -45,6 +47,7 @@ impl WorkerConcurrencySettingsV1 {
pub enum WorkerHarnessV1 {
CodexCli,
ClaudeCode,
+ QoderCli,
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
diff --git a/crates/domain/src/operation/mod.rs b/crates/domain/src/operation/mod.rs
index 882cd04f..cbeb4f38 100644
--- a/crates/domain/src/operation/mod.rs
+++ b/crates/domain/src/operation/mod.rs
@@ -709,7 +709,8 @@ impl ExternalEffectIntentV1 {
#[serde(deny_unknown_fields)]
pub struct WorkerDependencySelectionRecordV1 {
pub harness: crate::delegation::WorkerHarnessV1,
- pub adapter_path: String,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub adapter_path: Option<String>,
pub cli_path: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub node_path: Option<String>,
@@ -718,27 +719,30 @@ pub struct WorkerDependencySelectionRecordV1 {
impl WorkerDependencySelectionRecordV1 {
pub fn new(
harness: crate::delegation::WorkerHarnessV1,
- adapter_path: impl Into<String>,
+ adapter_path: Option<String>,
cli_path: impl Into<String>,
node_path: Option<String>,
) -> Result<Self, OperationValidationError> {
let selection = Self {
harness,
- adapter_path: adapter_path.into(),
+ adapter_path,
cli_path: cli_path.into(),
node_path,
};
- if !valid_native_absolute_path(&selection.adapter_path)
- || !valid_native_absolute_path(&selection.cli_path)
- || selection
- .node_path
- .as_deref()
- .is_some_and(|path| !valid_native_absolute_path(path))
- {
- return Err(OperationValidationError::UnregisteredEffectPlan);
- }
+ selection.validated_launch()?;
Ok(selection)
}
+
+ pub fn validated_launch(
+ &self,
+ ) -> Result<crate::delegation::WorkerLaunchFormV1<'_>, OperationValidationError> {
+ crate::delegation::WorkerLaunchFormV1::validate(
+ self.harness,
+ self.adapter_path.as_deref(),
+ &self.cli_path,
+ self.node_path.as_deref(),
+ )
+ }
}
/// Compare-and-select input owned by the protected Worker dependency management operation.
@@ -768,14 +772,6 @@ impl WorkerDependencySelectionChangeV1 {
}
}
-fn valid_native_absolute_path(value: &str) -> bool {
- !value.is_empty()
- && value.len() <= 4096
- && !value.contains('\0')
- && !value.contains(char::is_control)
- && std::path::Path::new(value).is_absolute()
-}
-
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct TransactionPlanV1 {
spec: ChangeSpecV1,
@@ -841,8 +837,10 @@ impl TransactionPlanV1 {
spec: ChangeSpecV1,
change: WorkerDependencySelectionChangeV1,
) -> Result<Self, OperationValidationError> {
+ change.after_selection.validated_launch()?;
let harness = change.after_selection.harness;
let resource = match harness {
+ crate::delegation::WorkerHarnessV1::QoderCli => "worker-dependency-selection/qoder_cli",
crate::delegation::WorkerHarnessV1::CodexCli => "worker-dependency-selection/codex_cli",
crate::delegation::WorkerHarnessV1::ClaudeCode => {
"worker-dependency-selection/claude_code"
diff --git a/crates/gateway/README.md b/crates/gateway/README.md
new file mode 100644
index 00000000..6ab5984f
--- /dev/null
+++ b/crates/gateway/README.md
@@ -0,0 +1,73 @@
+# Gateway request and decision boundaries
+
+The production listener is composed in [server.rs](src/server.rs).
+[publication/compiler.rs](src/publication/compiler.rs) turns one accepted
+publication into immutable request authority. Read
+[core_runtime.rs](src/core_runtime.rs) for the real request path: authenticate and
+bind authority, prepare the canonical request and Replay, obtain a request-owned
+branch decision, plan and freeze candidates, then admit execution into
+`hiroute-gateway-core`. The core owns attempts, response commit, cancellation and
+resource cleanup; the Gateway does not run a second execution loop.
+
+## Decision operation
+
+[core_runtime/classification.rs](src/core_runtime/classification.rs) owns the
+current local/REST classifier operation. Its clock starts before history
+preparation in `core_runtime.rs`; preparation, Secret resolution, DNS, connection,
+write and read share the bounded operation. The earlier source deadline and
+source cancellation remain authoritative. A classifier failure can use the
+existing local fallback only while the source request remains active.
+
+[classification/protocol.rs](src/core_runtime/classification/protocol.rs)
+serializes the five-field Decision API request from Replay-backed current input
+and sealed execution history. It validates the returned branch against the
+publication's allowed set and handles an optional prior-segment assessment
+separately. It does not choose model candidates.
+
+`TargetResolver` in
+[runtime/driver/materialization.rs](src/runtime/driver/materialization.rs)
+owns only DNS and the optional controlled dial mapping. `ProductionProvider`
+captures it at construction; the classifier creates its own resolver at the same
+point where it previously created a full business-model provider. The resolver
+uses the caller's `ExecutionScope`, keeps the existing error categories, and
+does not read credentials or runtime-state stores. E2E configuration remains
+captured at construction, not reloaded on each resolution.
+
+[planner.rs](src/planner.rs) validates the selected branch and chooses eligible
+groups/candidates under the frozen policy. Selected branch and actual executed
+branch can differ after an authorized fallback; history and assessment must
+retain that distinction. They cannot be reconstructed from display names.
+
+## Extension ownership
+
+The existing [official Jev service](../../decision-extensions/extensions/jev-decider/README.md#code-and-responsibility-map)
+separates deterministic request/answer logic from its Python HTTP lifecycle.
+General inference, purpose policy, provider transport and execution authorization
+have different owners: a model/tool selection purpose defines its question and
+allowed IDs; a provider handles its wire protocol and credentials; only the
+calling product authorizes actual execution. The current smart-saving policy is
+not a universal inference or tool-routing contract.
+
+The Decision API can carry a generic branch map, but current published Gateway
+smart-saving policies remain binary. Future natural-language branch conditions
+need caller-owned stable IDs, a publication-pinned allowed set and explicit
+failure/default policy. Keep provider response interpretation outside candidate
+execution. This responsibility map adds no provider, branch or fallback behavior.
+See the shared [decision foundation map](../../docs/code-map/decision-foundation.md)
+for provider references and the separately owned future selection contracts.
+
+## Representative capability tests
+
+| User capability or invariant | Existing entry |
+| --- | --- |
+| One decision selects the actual business model across supported ingress protocols | `real_listener_rest_classifier_*` in [p0_gateway_runtime.rs](../../tools/e2e-harness/tests/p0_gateway_runtime.rs) |
+| Classifier timeout may fall back; source deadline or disconnect must not start a model | The three timeout/deadline/disconnect cases in the same target |
+| Decision diagnostics use the production transport/parser without running a business model | `classifier_diagnostic_uses_the_production_transport_and_exact_protocol` in [classification.rs](src/core_runtime/classification.rs) |
+| Accepted execution history survives client rewrite/compaction with observation disabled | [accepted_history.rs](../../tools/e2e-harness/tests/p0_gateway_runtime/accepted_history.rs) |
+| Tool continuation survives restart with authentication | [continuation.rs](../../tools/e2e-harness/tests/p0_gateway_protocol/continuation.rs) |
+| Live publication cutover pins each request and preserves the last good version | [p0_gateway_request_authority.rs](../../tools/e2e-harness/tests/p0_gateway_request_authority.rs) |
+
+Use the repository [test planner](../../scripts/test-plan.py) and
+[configured validation runner](../../scripts/validation.py). An isolated Jev or
+diagnostic success does not establish product routing success. Source-text
+assertions and private helper names are not substitutes for these behaviors.
diff --git a/crates/gateway/src/core_runtime.rs b/crates/gateway/src/core_runtime.rs
index 011439ec..f3e39c58 100644
--- a/crates/gateway/src/core_runtime.rs
+++ b/crates/gateway/src/core_runtime.rs
@@ -251,7 +251,10 @@ impl GatewayLifecycle for ProductionGatewayRuntime {
.get(CONTENT_LENGTH)
.and_then(|value| value.to_str().ok())
.and_then(|value| value.parse::<usize>().ok());
- if request.method == Method::GET && path == "/v1/models" {
+ if request.method == Method::GET
+ && (path == "/v1/models"
+ || path.strip_prefix(hiroute_domain::QODER_MODEL_BASE_PATH) == Some("/models"))
+ {
let if_none_match = request
.headers
.get(IF_NONE_MATCH)
@@ -1385,6 +1388,30 @@ fn inbound_authorization<'a>(
path: &str,
headers: &'a HeaderMap,
) -> Option<std::borrow::Cow<'a, str>> {
+ if path
+ .strip_prefix(hiroute_domain::QODER_MODEL_BASE_PATH)
+ .is_some_and(|resource| matches!(resource, "/responses" | "/models"))
+ {
+ // This explicit native entry consumes only local model-grant credentials.
+ // Normal publication authentication still rejects unissued/native account
+ // tokens; delegated run authority remains on its separate existing entry.
+ if headers.contains_key("x-hiroute-token")
+ || headers.get_all(AUTHORIZATION).iter().count() != 1
+ {
+ return None;
+ }
+ let authorization = headers.get(AUTHORIZATION)?.to_str().ok()?;
+ let token = authorization.strip_prefix("Bearer ")?;
+ if token.is_empty()
+ || token.starts_with("hr_run_")
+ || token
+ .bytes()
+ .any(|byte| byte.is_ascii_whitespace() || byte == b',')
+ {
+ return None;
+ }
+ return Some(std::borrow::Cow::Borrowed(authorization));
+ }
if headers.contains_key("x-hiroute-token") {
if !matches!(path, "/v1/responses" | "/v1/models")
|| headers.get_all("x-hiroute-token").iter().count() != 1
diff --git a/crates/gateway/src/core_runtime/classification.rs b/crates/gateway/src/core_runtime/classification.rs
index 2a6a6440..270c288d 100644
--- a/crates/gateway/src/core_runtime/classification.rs
+++ b/crates/gateway/src/core_runtime/classification.rs
@@ -33,7 +33,7 @@ use crate::agent_turn_history::{AgentTurnHistorySnapshot, AssessmentTarget};
use crate::content_ref::ContentValueExt;
use crate::ports::{ExecutionScope, HeaderSecretLeaseRequest};
use crate::replay::{ReplayError, ReplayStore};
-use crate::runtime::{ProductionProvider, resolve_target};
+use crate::runtime::TargetResolver;
use crate::server::request_plan::{
ClassifierAuthenticationAuthorityV1, IngressProtocol, RestBranchClassifierAuthorityV1,
};
@@ -410,20 +410,22 @@ impl ProductionGatewayRuntime {
}
}
- let provider = ProductionProvider::new(&self.ports);
- let target =
- match resolve_target(&provider, classifier.transport_target.clone(), &scope).await {
- Ok(target) => target,
- Err(_) => {
- return active_failure_or_abort(
- CallFailure::Unavailable,
- call_deadline,
- overall_deadline,
- fixed_timeout_wins,
- &cancellation,
- );
- }
- };
+ let resolver = TargetResolver::new();
+ let target = match resolver
+ .resolve(classifier.transport_target.clone(), &scope)
+ .await
+ {
+ Ok(target) => target,
+ Err(_) => {
+ return active_failure_or_abort(
+ CallFailure::Unavailable,
+ call_deadline,
+ overall_deadline,
+ fixed_timeout_wins,
+ &cancellation,
+ );
+ }
+ };
let body = sequential_replay_body(
template.clone(),
replay.clone(),
diff --git a/crates/gateway/src/core_runtime/inbound_auth_tests.rs b/crates/gateway/src/core_runtime/inbound_auth_tests.rs
index 5341d4a7..5495ffaf 100644
--- a/crates/gateway/src/core_runtime/inbound_auth_tests.rs
+++ b/crates/gateway/src/core_runtime/inbound_auth_tests.rs
@@ -1,5 +1,58 @@
use super::*;
+#[test]
+fn qoder_model_entry_is_explicit_and_never_adopts_worker_or_mixed_credentials() {
+ let path = format!("{}/responses", hiroute_domain::QODER_MODEL_BASE_PATH);
+ let catalog = format!("{}/models", hiroute_domain::QODER_MODEL_BASE_PATH);
+ assert_eq!(
+ IngressProtocol::from_path(&path),
+ Some(IngressProtocol::Responses)
+ );
+ let mut headers = HeaderMap::new();
+ for target in [&path, &catalog] {
+ headers.insert(
+ AUTHORIZATION,
+ HeaderValue::from_static("Bearer local-model-grant"),
+ );
+ assert_eq!(
+ inbound_authorization(target, &headers).as_deref(),
+ Some("Bearer local-model-grant")
+ );
+ assert!(inbound_authorization("/v1/responses", &headers).is_none());
+ headers.insert(
+ "x-hiroute-token",
+ HeaderValue::from_static("local-model-grant"),
+ );
+ assert!(inbound_authorization(target, &headers).is_none());
+ headers.remove("x-hiroute-token");
+ for invalid in [
+ "Bearer hr_run_model_fixture",
+ "Bearer hr_run_control_fixture",
+ "Bearer ",
+ "Bearer first,second",
+ "Bearer first second",
+ "Basic local-model-grant",
+ ] {
+ headers.insert(AUTHORIZATION, HeaderValue::from_static(invalid));
+ assert!(
+ inbound_authorization(target, &headers).is_none(),
+ "{invalid}"
+ );
+ }
+ headers.insert(AUTHORIZATION, HeaderValue::from_static("Bearer first"));
+ headers.append(AUTHORIZATION, HeaderValue::from_static("Bearer second"));
+ assert!(inbound_authorization(target, &headers).is_none());
+ headers.clear();
+ }
+ assert!(
+ IngressProtocol::from_path(&format!(
+ "{}/responses/extra",
+ hiroute_domain::QODER_MODEL_BASE_PATH
+ ))
+ .is_none()
+ );
+}
+
#[test]
fn x_api_key_never_authenticates_and_bearer_wins_when_both_are_present() {
let mut headers = HeaderMap::new();
diff --git a/crates/gateway/src/dispatch/run.rs b/crates/gateway/src/dispatch/run.rs
index 6fa92f7b..e957b1d4 100644
--- a/crates/gateway/src/dispatch/run.rs
+++ b/crates/gateway/src/dispatch/run.rs
@@ -62,7 +62,7 @@ impl RunObservationMetadata {
if value.plan_revision == 0
|| !valid_observation_reference(&value.plan_id)
|| !valid_observation_reference(&value.publication_ref)
- || !matches!(value.harness_id.as_str(), "codex" | "claude")
+ || !matches!(value.harness_id.as_str(), "codex" | "claude" | "qoder")
|| [
&value.native_session_id,
&value.parent_context_ref,
@@ -326,12 +326,12 @@ mod tests {
}
}
- fn observation_metadata() -> RunObservationMetadata {
+ fn observation_metadata(harness: &str) -> RunObservationMetadata {
RunObservationMetadata::new(
"plan/one",
7,
"publication/3/digest/sha256:abc",
- "codex",
+ harness,
Some("native/session-one".into()),
Some("task/root".into()),
Some("run/zero".into()),
@@ -340,6 +340,10 @@ mod tests {
}
fn verified(safety: Arc<Safety>) -> VerifiedRunRequestAuthority {
+ verified_for_harness(safety, "codex")
+ }
+
+ fn verified_for_harness(safety: Arc<Safety>, harness: &str) -> VerifiedRunRequestAuthority {
let snapshot = GatewayPublicationSnapshotV3::seal(
"workspace",
"delegation-run/run-one",
@@ -383,7 +387,7 @@ mod tests {
"run/one",
"lease/one",
"plan/one/revision/7/digest/sha256:abc",
- observation_metadata(),
+ observation_metadata(harness),
)
.unwrap(),
publication,
@@ -393,6 +397,24 @@ mod tests {
.unwrap()
}
+ #[test]
+ fn unknown_native_harness_cannot_enter_verified_run_observation() {
+ for harness in ["unknown", "", "qoder_cli", "Qoder"] {
+ assert!(matches!(
+ RunObservationMetadata::new(
+ "plan/one",
+ 7,
+ "publication/one",
+ harness,
+ None,
+ None,
+ None
+ ),
+ Err(RunRequestAuthorityError::Denied)
+ ));
+ }
+ }
+
#[test]
fn search_permission_is_derived_only_from_verified_run_network_access() {
for allowed in [false, true] {
@@ -435,49 +457,53 @@ mod tests {
}
}
- let authority = GatewayRequestAuthority::new(empty_global()).with_run_request_authority(
- Arc::new(Authority(verified(Arc::new(Safety(AtomicUsize::new(0)))))),
- );
- let request = authority
- .begin(IngressProtocol::Responses, Some(&format!("Bearer {TOKEN}")))
- .unwrap()
- .authorize_alias("worker-model", std::time::Instant::now())
- .unwrap();
- let (sender, receiver) = mpsc::channel();
- let mut sinks = GatewayObservationSinks::discard();
- sinks.run_relation = Arc::new(Capture(sender));
- let observation = GatewayObservation::with_sinks_and_policy_and_workspace_key(
- true,
- 64 * 1024,
- sinks,
- OtelContentPolicy::Disabled,
- [7_u8; 32],
- );
- let _request_observation = observation.begin_request_with_content(
- &request,
- IngressProtocol::Responses,
- &crate::context_hold::ContextIdentityFacts::request_scoped(),
- true,
- );
- let link: RunObservationLink =
- serde_json::from_slice(&receiver.recv_timeout(Duration::from_secs(1)).unwrap())
+ for harness in ["codex", "claude", "qoder"] {
+ let authority = GatewayRequestAuthority::new(empty_global())
+ .with_run_request_authority(Arc::new(Authority(verified_for_harness(
+ Arc::new(Safety(AtomicUsize::new(0))),
+ harness,
+ ))));
+ let request = authority
+ .begin(IngressProtocol::Responses, Some(&format!("Bearer {TOKEN}")))
+ .unwrap()
+ .authorize_alias("worker-model", std::time::Instant::now())
.unwrap();
- assert_eq!(link.workspace_id.as_str(), "workspace");
- assert_eq!(link.task_id, "task/one");
- assert_eq!(link.run_id, "run/one");
- assert_eq!(link.plan_id, "plan/one");
- assert_eq!(link.plan_revision, "7");
- assert_eq!(link.publication_ref, "publication/3/digest/sha256:abc");
- assert_eq!(link.harness_id, "codex");
- assert_eq!(link.protocol_kind, "responses");
- assert_eq!(
- link.native_session_id.as_deref(),
- Some("native/session-one")
- );
- assert_eq!(link.parent_context_ref.as_deref(), Some("task/root"));
- assert_eq!(link.continued_from_run_id.as_deref(), Some("run/zero"));
- assert!(!link.producer_epoch.is_empty());
- assert!(link.source_event_id.starts_with("relation-event-"));
+ let (sender, receiver) = mpsc::channel();
+ let mut sinks = GatewayObservationSinks::discard();
+ sinks.run_relation = Arc::new(Capture(sender));
+ let observation = GatewayObservation::with_sinks_and_policy_and_workspace_key(
+ true,
+ 64 * 1024,
+ sinks,
+ OtelContentPolicy::Disabled,
+ [7_u8; 32],
+ );
+ let _request_observation = observation.begin_request_with_content(
+ &request,
+ IngressProtocol::Responses,
+ &crate::context_hold::ContextIdentityFacts::request_scoped(),
+ true,
+ );
+ let link: RunObservationLink =
+ serde_json::from_slice(&receiver.recv_timeout(Duration::from_secs(1)).unwrap())
+ .unwrap();
+ assert_eq!(link.workspace_id.as_str(), "workspace");
+ assert_eq!(link.task_id, "task/one");
+ assert_eq!(link.run_id, "run/one");
+ assert_eq!(link.plan_id, "plan/one");
+ assert_eq!(link.plan_revision, "7");
+ assert_eq!(link.publication_ref, "publication/3/digest/sha256:abc");
+ assert_eq!(link.harness_id, harness);
+ assert_eq!(link.protocol_kind, "responses");
+ assert_eq!(
+ link.native_session_id.as_deref(),
+ Some("native/session-one")
+ );
+ assert_eq!(link.parent_context_ref.as_deref(), Some("task/root"));
+ assert_eq!(link.continued_from_run_id.as_deref(), Some("run/zero"));
+ assert!(!link.producer_epoch.is_empty());
+ assert!(link.source_event_id.starts_with("relation-event-"));
+ }
}
#[cfg(unix)]
diff --git a/crates/gateway/src/observation.rs b/crates/gateway/src/observation.rs
index 7560c0ae..6c6fad5b 100644
--- a/crates/gateway/src/observation.rs
+++ b/crates/gateway/src/observation.rs
@@ -104,6 +104,10 @@ pub enum NativeAgentObservationIdentityV1 {
CodexSession {
session_id: String,
},
+ /// Qoder 1.1.65 sends its native session UUID in the Responses `session-id` header.
+ QoderSession {
+ session_id: String,
+ },
CodexThreadSession {
thread_id: String,
session_id: String,
@@ -164,6 +168,15 @@ pub fn derive_native_agent_observation_session_id(
NativeAgentObservationIdentityV1::CodexSession { session_id } => {
("codex_session", vec![session_id.as_str()])
}
+ NativeAgentObservationIdentityV1::QoderSession { session_id } => {
+ if trust.ingress_protocol != hiroute_domain::IngressProtocolV1::Responses {
+ return Err(NativeAgentObservationSessionError::UnsupportedIngress);
+ }
+ // The existing wire producer already accepts this header independently of client
+ // branding. Retain its historical HMAC namespace; do not create another parser or
+ // relabel the native client as Codex merely to locate its receipt.
+ ("codex_session", vec![session_id.as_str()])
+ }
NativeAgentObservationIdentityV1::CodexThreadSession {
thread_id,
session_id,
diff --git a/crates/gateway/src/observation/tests.rs b/crates/gateway/src/observation/tests.rs
index d852fbd3..20a40e98 100644
--- a/crates/gateway/src/observation/tests.rs
+++ b/crates/gateway/src/observation/tests.rs
@@ -81,6 +81,31 @@ fn native_agent_session_derivation_reuses_the_producer_identity_formula() {
derive_native_agent_observation_session_id(&workspace, &[0; 32], &trust, &identity)
.is_err()
);
+ let qoder = NativeAgentObservationIdentityV1::QoderSession {
+ session_id: "qoder-session".into(),
+ };
+ let header_session = NativeAgentObservationIdentityV1::CodexSession {
+ session_id: "qoder-session".into(),
+ };
+ let session =
+ derive_native_agent_observation_session_id(&workspace, &key, &trust, &qoder).unwrap();
+ assert_eq!(
+ session,
+ derive_native_agent_observation_session_id(&workspace, &key, &trust, &header_session)
+ .unwrap()
+ );
+ let mut other_grant = trust.clone();
+ other_grant.grant_id = "grant/other".into();
+ assert_ne!(
+ session,
+ derive_native_agent_observation_session_id(&workspace, &key, &other_grant, &qoder).unwrap()
+ );
+ let mut wrong_protocol = trust;
+ wrong_protocol.ingress_protocol = hiroute_domain::IngressProtocolV1::Messages;
+ assert!(
+ derive_native_agent_observation_session_id(&workspace, &key, &wrong_protocol, &qoder)
+ .is_err()
+ );
}
fn request(policy: OtelContentPolicy) -> RequestObservation {
diff --git a/crates/gateway/src/publication/mod.rs b/crates/gateway/src/publication/mod.rs
index f010c793..060d7c45 100644
--- a/crates/gateway/src/publication/mod.rs
+++ b/crates/gateway/src/publication/mod.rs
@@ -5,6 +5,7 @@ mod compiler;
mod installer;
mod run;
mod schema;
+mod trust;
pub use catalog::{CatalogError, CatalogResponse, GatewayCatalog};
pub(crate) use compiler::{CompiledGrant, CompiledGrantRoute, compile_classifier_mode_authority};
diff --git a/crates/gateway/src/publication/trust.rs b/crates/gateway/src/publication/trust.rs
new file mode 100644
index 00000000..2aa5c1c6
--- /dev/null
+++ b/crates/gateway/src/publication/trust.rs
@@ -0,0 +1,231 @@
+//! Body-free native verification expectations from the actual Gateway compiler.
+use hiroute_domain::{
+ AgentPlanId, CanonicalDigest, FrozenExecutionTrustV1, IngressProtocolV1, ModelRequestRouteV2,
+ SelectorSourceV1,
+};
+
+use super::{CompiledGrantRoute, GatewayPublicationSnapshotV3, PublicationInstallError};
+use crate::server::core_runtime::profiles::PlannerRouteIdentityV2;
+use crate::server::request_plan::IngressProtocol;
+
+impl GatewayPublicationSnapshotV3 {
+ /// Derive the provenance a native call must prove, without publishing, authenticating,
+ /// acquiring a credential or calling a Provider. Plan/grant projection digests describe
+ /// a different object; receipts freeze the compiler's executable alias identity.
+ pub fn native_agent_execution_trust(
+ &self,
+ grant_id: &str,
+ served_model_id: &str,
+ ) -> Result<FrozenExecutionTrustV1, PublicationInstallError> {
+ let compiled = super::compiler::compile(self)?;
+ let invalid = || PublicationInstallError::InvalidDurableState;
+ let grant = compiled
+ .grants
+ .iter()
+ .find(|grant| grant.grant_id.as_ref() == grant_id)
+ .ok_or_else(invalid)?;
+ let projected = grant.routes.get(served_model_id).ok_or_else(invalid)?;
+ let (agent_plan_id, route, plan_display_name) = match projected {
+ CompiledGrantRoute::Plan { alias } => {
+ let alias = compiled.aliases.get(alias).ok_or_else(invalid)?;
+ let PlannerRouteIdentityV2::Plan { plan_id, .. } =
+ &alias.execution.planner_policy.identity
+ else {
+ return Err(invalid());
+ };
+ (
+ Some(AgentPlanId::parse(plan_id).map_err(|_| invalid())?),
+ ModelRequestRouteV2::Plan {
+ revision: alias.agent_plan_revision,
+ semantic_digest: CanonicalDigest::parse(
+ alias.agent_plan_semantic_digest.as_ref(),
+ )
+ .map_err(|_| invalid())?,
+ },
+ alias.plan_display_name.as_deref().map(str::to_owned),
+ )
+ }
+ CompiledGrantRoute::Fixed { binding_digest, .. } => (
+ None,
+ ModelRequestRouteV2::Fixed {
+ binding_digest: binding_digest.clone(),
+ },
+ None,
+ ),
+ };
+ let ingress_protocol = match grant.protocol {
+ IngressProtocol::Responses => IngressProtocolV1::Responses,
+ IngressProtocol::Messages => IngressProtocolV1::Messages,
+ IngressProtocol::ChatCompletions => IngressProtocolV1::ChatCompletions,
+ };
+ let trust = FrozenExecutionTrustV1 {
+ authority_id: self.authority_id.clone(),
+ authority_epoch: self.authority_epoch,
+ served_model_id: served_model_id.to_owned(),
+ selector_source: SelectorSourceV1::TrustedModelAlias,
+ agent_plan_id,
+ route,
+ plan_display_name,
+ gateway_publication_revision: self.publication_revision.to_string(),
+ gateway_publication_digest: CanonicalDigest::parse(&self.payload_digest)
+ .map_err(|_| invalid())?,
+ grant_id: grant.grant_id.to_string(),
+ grant_generation: grant.generation,
+ ingress_protocol,
+ };
+ trust.validate().map_err(|_| invalid())?;
+ Ok(trust)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use std::sync::Arc;
+
+ use super::*;
+ use crate::server::dispatch::GatewayRequestAuthority;
+ use crate::server::publication::tests::{TestDirectory, publish, snapshot};
+ use crate::server::publication::{
+ AliasCostPolicyV1, AliasGroupIdV1, AliasModelGroupV1, AliasRequestOwnedRouteV1,
+ AliasRoutingV1, GatewayPublicationInstaller, ModelRouteV2, exact_test_candidate,
+ };
+
+ #[test]
+ fn native_agent_execution_trust_matches_authorized_plan_and_fixed_receipts() {
+ let mut snapshot = snapshot(7, "native-live-check");
+ for (index, alias) in snapshot.aliases.iter_mut().enumerate() {
+ alias.routing = Some(AliasRoutingV1 {
+ agent_plan_id: format!("legacy/{}", alias.served_model_id),
+ plan_display_name: Some(format!("{} display", alias.served_model_id)),
+ request_owned: AliasRequestOwnedRouteV1::Ordered {
+ cost_policy: AliasCostPolicyV1::ApiEquivalent,
+ ordered_groups: vec![AliasGroupIdV1::Custom],
+ },
+ groups: vec![AliasModelGroupV1 {
+ group_id: AliasGroupIdV1::Custom,
+ candidate_local_ids: vec![index as u32 + 1],
+ }],
+ });
+ }
+ let binding = exact_test_candidate(3, IngressProtocol::Responses, None);
+ snapshot.grants[0].routes.insert(
+ "native".into(),
+ ModelRouteV2::Fixed {
+ binding_digest: CanonicalDigest::of(&binding).unwrap(),
+ binding: Box::new(binding),
+ overall_timeout_ms: 1000,
+ max_attempts: 1,
+ },
+ );
+ snapshot.payload_digest = snapshot.canonical_digest().unwrap();
+ let directory = TestDirectory::new();
+ let path = directory.path().join("publication.json");
+ let installer = Arc::new(GatewayPublicationInstaller::open(&path).unwrap());
+ let cases = [
+ (
+ "grant-alpha",
+ "alpha",
+ "token-alpha",
+ IngressProtocol::Responses,
+ ),
+ (
+ "grant-beta",
+ "beta",
+ "token-beta",
+ IngressProtocol::Messages,
+ ),
+ (
+ "grant-alpha",
+ "native",
+ "token-alpha",
+ IngressProtocol::Responses,
+ ),
+ ];
+ let expected: Vec<_> = cases
+ .iter()
+ .map(|(grant, model, _, _)| {
+ snapshot.native_agent_execution_trust(grant, model).unwrap()
+ })
+ .collect();
+ assert!(installer.active().is_none());
+ assert!(!path.exists(), "computing expected trust must not publish");
+ publish(&installer, snapshot.clone());
+ let authority = GatewayRequestAuthority::new(installer);
+ for ((grant, model, token, protocol), expected) in cases.into_iter().zip(expected) {
+ let body = serde_json::to_vec(&serde_json::json!({"model": model})).unwrap();
+ let authorized = authority
+ .authorize_bytes(
+ protocol,
+ Some(&format!("Bearer {token}")),
+ &body,
+ std::time::Instant::now(),
+ )
+ .unwrap();
+ let receipt = authorized.receipt();
+ let agent_plan_id = match &authorized.planner_policy().identity {
+ PlannerRouteIdentityV2::Plan { plan_id, .. } => {
+ Some(AgentPlanId::parse(plan_id).unwrap())
+ }
+ PlannerRouteIdentityV2::Fixed { .. } => None,
+ };
+ let actual = FrozenExecutionTrustV1 {
+ authority_id: receipt.authority_id.to_string(),
+ authority_epoch: receipt.authority_epoch,
+ served_model_id: receipt.served_model_id.to_string(),
+ selector_source: SelectorSourceV1::TrustedModelAlias,
+ agent_plan_id,
+ route: receipt.route.clone(),
+ plan_display_name: receipt.plan_display_name.as_deref().map(str::to_owned),
+ gateway_publication_revision: receipt.publication_revision.to_string(),
+ gateway_publication_digest: CanonicalDigest::parse(
+ receipt.publication_digest.as_ref(),
+ )
+ .unwrap(),
+ grant_id: receipt.grant_id.to_string(),
+ grant_generation: receipt.grant_generation,
+ ingress_protocol: match receipt.ingress_protocol {
+ IngressProtocol::Responses => IngressProtocolV1::Responses,
+ IngressProtocol::Messages => IngressProtocolV1::Messages,
+ IngressProtocol::ChatCompletions => IngressProtocolV1::ChatCompletions,
+ },
+ };
+ assert_eq!(expected, actual, "native route {model}");
+ if let ModelRouteV2::Plan {
+ semantic_digest, ..
+ } = &snapshot
+ .grants
+ .iter()
+ .find(|value| value.grant_id == grant)
+ .unwrap()
+ .routes[model]
+ {
+ let ModelRequestRouteV2::Plan {
+ semantic_digest: compiled_digest,
+ ..
+ } = actual.route
+ else {
+ panic!("expected Plan execution receipt");
+ };
+ assert_ne!(semantic_digest, &compiled_digest);
+ }
+ }
+ }
+
+ #[test]
+ fn native_agent_execution_trust_rejects_invalid_snapshot_or_ungranted_identity() {
+ let mut snapshot = snapshot(1, "native-live-check");
+ for (grant, model) in [
+ ("unknown-grant", "alpha"),
+ ("grant-alpha", "beta"),
+ ("grant-alpha", "missing"),
+ ] {
+ assert!(snapshot.native_agent_execution_trust(grant, model).is_err());
+ }
+ snapshot.aliases[0].purpose = "changed after sealing".into();
+ assert!(
+ snapshot
+ .native_agent_execution_trust("grant-alpha", "alpha")
+ .is_err()
+ );
+ }
+}
diff --git a/crates/gateway/src/request_plan/mod.rs b/crates/gateway/src/request_plan/mod.rs
index 89661203..41ea37b6 100644
--- a/crates/gateway/src/request_plan/mod.rs
+++ b/crates/gateway/src/request_plan/mod.rs
@@ -23,6 +23,9 @@ pub enum IngressProtocol {
impl IngressProtocol {
pub fn from_path(path: &str) -> Option<Self> {
+ if path.strip_prefix(hiroute_domain::QODER_MODEL_BASE_PATH) == Some("/responses") {
+ return Some(Self::Responses);
+ }
match path {
"/v1/responses" => Some(Self::Responses),
"/v1/chat/completions" => Some(Self::ChatCompletions),
diff --git a/crates/gateway/src/runtime/driver.rs b/crates/gateway/src/runtime/driver.rs
index 04bdbdde..a8b16624 100644
--- a/crates/gateway/src/runtime/driver.rs
+++ b/crates/gateway/src/runtime/driver.rs
@@ -43,7 +43,7 @@ mod response;
mod response_diagnostics;
mod selection;
-pub(crate) use materialization::resolve_target;
+pub(crate) use materialization::TargetResolver;
pub use selection::{ProductionDecisionSession, ProductionSelection};
const MATERIALIZATION_BINDING_UNAVAILABLE: &str = "binding_unavailable";
@@ -63,8 +63,7 @@ pub struct ProductionProvider {
credentials: Arc<dyn ProductionCredentialResolver>,
state: Arc<materialization::ProductionStateAdapter>,
cooldowns: RuntimeCooldownPolicy,
- #[cfg(feature = "e2e-test-control")]
- test_dial: Result<Option<crate::server::test_control::E2eDialMap>, ()>,
+ target_resolver: TargetResolver,
}
pub struct ProductionLogicalRequest {
diff --git a/crates/gateway/src/runtime/driver/materialization.rs b/crates/gateway/src/runtime/driver/materialization.rs
index 3c620f20..372da358 100644
--- a/crates/gateway/src/runtime/driver/materialization.rs
+++ b/crates/gateway/src/runtime/driver/materialization.rs
@@ -108,8 +108,7 @@ impl ProductionProvider {
inner: Arc::clone(&ports.runtime_state),
}),
cooldowns: RuntimeCooldownPolicy::default(),
- #[cfg(feature = "e2e-test-control")]
- test_dial: crate::server::test_control::E2eDialMap::from_environment(),
+ target_resolver: TargetResolver::new(),
}
}
}
@@ -429,7 +428,7 @@ pub(super) async fn materialize_attempt(
return Err(Arc::from(MATERIALIZATION_AUTHORITY_FAILED));
}
let target = transport_target_for_profile(plan, &lease_target)?;
- resolve_target(provider, target, &scope).await?
+ provider.target_resolver.resolve(target, &scope).await?
}
};
validate_attempt_permits(provider.state.as_ref(), permits.borrowed(), &scope)
@@ -800,51 +799,66 @@ async fn confirm_mechanical_state(
Ok(Some((classified, facts)))
}
-pub(crate) async fn resolve_target(
- provider: &ProductionProvider,
- target: TransportTarget,
- scope: &ExecutionScope,
-) -> Result<TransportTarget, Arc<str>> {
+/// DNS resolution and the optional controlled dial mapping. Constructed at the
+/// caller's original configuration boundary, independently of model credentials
+/// and runtime-state ownership.
+pub(crate) struct TargetResolver {
#[cfg(feature = "e2e-test-control")]
- {
- let test_dial = provider
- .test_dial
- .as_ref()
- .map_err(|_| Arc::from(MATERIALIZATION_PROTOCOL_FAILED))?;
- if test_dial
- .as_ref()
- .is_some_and(|dial| dial.fails_dns(&target))
- {
- return Err(Arc::from(MATERIALIZATION_DNS_FAILED));
+ test_dial: Result<Option<crate::server::test_control::E2eDialMap>, ()>,
+}
+
+impl TargetResolver {
+ pub(crate) fn new() -> Self {
+ Self {
+ #[cfg(feature = "e2e-test-control")]
+ test_dial: crate::server::test_control::E2eDialMap::from_environment(),
}
- if let Some(mapped) = test_dial
- .as_ref()
- .map(|dial| dial.apply(target.clone()))
- .transpose()
- .map_err(|_| Arc::from(MATERIALIZATION_PROTOCOL_FAILED))?
- .flatten()
+ }
+
+ pub(crate) async fn resolve(
+ &self,
+ target: TransportTarget,
+ scope: &ExecutionScope,
+ ) -> Result<TransportTarget, Arc<str>> {
+ #[cfg(feature = "e2e-test-control")]
{
- return Ok(mapped);
+ let test_dial = self
+ .test_dial
+ .as_ref()
+ .map_err(|_| Arc::from(MATERIALIZATION_PROTOCOL_FAILED))?;
+ if test_dial
+ .as_ref()
+ .is_some_and(|dial| dial.fails_dns(&target))
+ {
+ return Err(Arc::from(MATERIALIZATION_DNS_FAILED));
+ }
+ if let Some(mapped) = test_dial
+ .as_ref()
+ .map(|dial| dial.apply(target.clone()))
+ .transpose()
+ .map_err(|_| Arc::from(MATERIALIZATION_PROTOCOL_FAILED))?
+ .flatten()
+ {
+ return Ok(mapped);
+ }
}
+ let Some(authority) = target.unresolved_authority().map(ToOwned::to_owned) else {
+ return Ok(target);
+ };
+ let (host, port) = dns_lookup_target(&authority, target.scheme)?;
+ let addresses = scope
+ .run(tokio::net::lookup_host((host.as_str(), port)))
+ .await
+ .map_err(|_| Arc::from(MATERIALIZATION_DNS_FAILED))?
+ .map_err(|_| Arc::from(MATERIALIZATION_DNS_FAILED))?
+ .collect::<Vec<SocketAddr>>();
+ if addresses.is_empty() {
+ return Err(Arc::from(MATERIALIZATION_DNS_FAILED));
+ }
+ target
+ .with_resolved_addresses(addresses.into())
+ .map_err(|_| Arc::from(MATERIALIZATION_DNS_FAILED))
}
- #[cfg(not(feature = "e2e-test-control"))]
- let _ = provider;
- let Some(authority) = target.unresolved_authority().map(ToOwned::to_owned) else {
- return Ok(target);
- };
- let (host, port) = dns_lookup_target(&authority, target.scheme)?;
- let addresses = scope
- .run(tokio::net::lookup_host((host.as_str(), port)))
- .await
- .map_err(|_| Arc::from(MATERIALIZATION_DNS_FAILED))?
- .map_err(|_| Arc::from(MATERIALIZATION_DNS_FAILED))?
- .collect::<Vec<SocketAddr>>();
- if addresses.is_empty() {
- return Err(Arc::from(MATERIALIZATION_DNS_FAILED));
- }
- target
- .with_resolved_addresses(addresses.into())
- .map_err(|_| Arc::from(MATERIALIZATION_DNS_FAILED))
}
fn transport_target_for_profile(
diff --git a/crates/integrations/Cargo.toml b/crates/integrations/Cargo.toml
index 2c8313a6..bf3af8f8 100644
--- a/crates/integrations/Cargo.toml
+++ b/crates/integrations/Cargo.toml
@@ -22,3 +22,4 @@ tempfile.workspace = true
[target.'cfg(unix)'.dependencies]
nix = { workspace = true, features = ["process", "signal"] }
+rustix.workspace = true
diff --git a/crates/integrations/src/agents/discovery.rs b/crates/integrations/src/agents/discovery.rs
index d5b3487a..b4438938 100644
--- a/crates/integrations/src/agents/discovery.rs
+++ b/crates/integrations/src/agents/discovery.rs
@@ -164,7 +164,14 @@ fn select_effective<'a>(
values
.iter()
.copied()
- .min_by_key(|value| value.layer.precedence_for(kind))
+ .filter_map(|value| {
+ value
+ .layer
+ .precedence_for(kind)
+ .map(|precedence| (precedence, value))
+ })
+ .min_by_key(|(precedence, _)| *precedence)
+ .map(|(_, value)| value)
}
fn valid_agent_id(value: &str) -> bool {
diff --git a/crates/integrations/src/agents/emulator.rs b/crates/integrations/src/agents/emulator.rs
index 6a4c4221..2c584465 100644
--- a/crates/integrations/src/agents/emulator.rs
+++ b/crates/integrations/src/agents/emulator.rs
@@ -18,8 +18,9 @@ pub fn render_agent_probe(
profile: &AgentProfileV1,
probe: &BuiltInAgentProbeV1,
) -> Result<RenderedAgentProbeV1, AgentProbeAdapterError> {
+ let protocol = model_protocol(profile)?;
probe.validate_for(profile)?;
- let payload = match profile.client_protocol() {
+ let payload = match protocol {
AgentIngressProtocolV1::Responses => json!({
"input": [{
"content": [{"text": probe.prompt, "type": "input_text"}],
@@ -43,7 +44,7 @@ pub fn render_agent_probe(
}),
};
Ok(RenderedAgentProbeV1 {
- protocol: profile.client_protocol(),
+ protocol,
traffic_kind: AgentTrafficKindV1::ConnectivityProbe,
payload,
})
@@ -62,10 +63,8 @@ pub fn parse_agent_probe_response(
profile: &AgentProfileV1,
response: &Value,
) -> Result<AgentProbeResultV1, AgentProbeAdapterError> {
- profile
- .validate()
- .map_err(|_| AgentProbeAdapterError::UnexpectedResponse)?;
- let text = match profile.client_protocol() {
+ let protocol = model_protocol(profile)?;
+ let text = match protocol {
AgentIngressProtocolV1::Responses => response
.get("output")
.and_then(Value::as_array)
@@ -91,7 +90,7 @@ pub fn parse_agent_probe_response(
return Err(AgentProbeAdapterError::UnexpectedResponse);
}
Ok(AgentProbeResultV1 {
- protocol: profile.client_protocol(),
+ protocol,
traffic_kind: AgentTrafficKindV1::ConnectivityProbe,
ready: true,
response_digest: CanonicalDigest::of(response)
@@ -99,6 +98,16 @@ pub fn parse_agent_probe_response(
})
}
+fn model_protocol(
+ profile: &AgentProfileV1,
+) -> Result<AgentIngressProtocolV1, AgentProbeAdapterError> {
+ profile
+ .model_connection()
+ .map_err(|_| AgentEmulatorError::InvalidProfile)?
+ .map(|model| model.ingress_protocol)
+ .ok_or_else(|| AgentEmulatorError::InvalidProfile.into())
+}
+
fn contains_tool_result(value: &Value) -> bool {
match value {
Value::Array(values) => values.iter().any(contains_tool_result),
diff --git a/crates/integrations/src/agents/filesystem.rs b/crates/integrations/src/agents/filesystem.rs
index 9f5f756a..dfb96de5 100644
--- a/crates/integrations/src/agents/filesystem.rs
+++ b/crates/integrations/src/agents/filesystem.rs
@@ -33,6 +33,8 @@ use super::{
mod claude_settings;
#[path = "claude_observation.rs"]
mod main_observation;
+#[path = "qoder_discovery.rs"]
+mod qoder_discovery;
#[path = "settings_discovery.rs"]
mod settings_discovery;
@@ -120,6 +122,9 @@ pub struct AgentFilesystemLayoutV1 {
/// installed bundle through the operating system. `None` means that surface is unavailable.
pub codex_desktop_executable: Option<PathBuf>,
pub claude_executable: PathBuf,
+ pub qoder_executable: PathBuf,
+ pub qoder_home: PathBuf,
+ pub qoder_config_root: PathBuf,
pub codex_user_config: PathBuf,
pub claude_launch_settings: Option<PathBuf>,
pub claude_project_settings: Vec<PathBuf>,
@@ -160,6 +165,12 @@ impl AgentFilesystemLayoutV1 {
codex_executable: PathBuf::from("codex"),
codex_desktop_executable: None,
claude_executable: PathBuf::from("claude"),
+ qoder_executable: PathBuf::from("qoder"),
+ qoder_home: home.to_owned(),
+ qoder_config_root: std::env::var_os("QODER_CONFIG_DIR")
+ .filter(|value| !value.is_empty())
+ .map(PathBuf::from)
+ .unwrap_or_else(|| home.join(".qoder")),
codex_user_config: codex_config_path(home, std::env::var_os("CODEX_HOME").as_deref()),
claude_launch_settings: None,
claude_project_settings: vec![
@@ -192,6 +203,8 @@ pub struct FilesystemAgentScannerV1 {
codex_ingress: std::sync::Arc<std::sync::Mutex<Option<super::CodexIngressEvidence>>>,
#[cfg(unix)]
claude_ingress: std::sync::Arc<std::sync::Mutex<Option<super::ClaudeIngressEvidence>>>,
+ #[cfg(unix)]
+ qoder_collaboration: std::sync::Arc<std::sync::Mutex<super::qoder_probe::QoderProofCache>>,
}
impl FilesystemAgentScannerV1 {
@@ -247,6 +260,8 @@ impl FilesystemAgentScannerV1 {
codex_ingress: Default::default(),
#[cfg(unix)]
claude_ingress: Default::default(),
+ #[cfg(unix)]
+ qoder_collaboration: Default::default(),
}
}
@@ -350,7 +365,7 @@ impl FilesystemAgentScannerV1 {
}
pub fn scan(&self) -> Vec<FilesystemAgentDiscoveryV1> {
- let mut results = vec![self.scan_codex()];
+ let mut results = vec![self.scan_codex(), self.qoder_settings_discovery(false)];
match executable_probe(&self.layout.claude_executable) {
ExecutableProbe::Installed(executable) => {
results.push(self.scan_claude(Some(executable), None, false));
@@ -384,6 +399,7 @@ impl FilesystemAgentScannerV1 {
);
self.layout.claude_executable.clone()
}
+ AgentKindV1::Qoder => continue,
};
#[cfg(unix)]
if installation.profile.kind == AgentKindV1::Codex
@@ -513,7 +529,8 @@ impl FilesystemAgentScannerV1 {
hiroute_domain::AgentModelSurfaceV2::CodexDesktop => {
self.layout.codex_desktop_executable.clone()
}
- hiroute_domain::AgentModelSurfaceV2::ClaudeCli => None,
+ hiroute_domain::AgentModelSurfaceV2::ClaudeCli
+ | hiroute_domain::AgentModelSurfaceV2::QoderCli => None,
}
}
@@ -545,6 +562,11 @@ impl FilesystemAgentScannerV1 {
.into_iter()
.collect()
}
+ "agent_qoder_default" if self.qoder_executable_target().is_some() => {
+ [hiroute_domain::AgentModelSurfaceV2::QoderCli]
+ .into_iter()
+ .collect()
+ }
_ => BTreeSet::new(),
}
}
diff --git a/crates/integrations/src/agents/filesystem_config.rs b/crates/integrations/src/agents/filesystem_config.rs
index 6fe3f12d..e431e28b 100644
--- a/crates/integrations/src/agents/filesystem_config.rs
+++ b/crates/integrations/src/agents/filesystem_config.rs
@@ -773,6 +773,7 @@ fn display_path(layer: ConfigLayerV1, path: &Path) -> String {
ConfigLayerV1::Process => "process environment".to_owned(),
ConfigLayerV1::Launch => format!("launch/{name}"),
ConfigLayerV1::Project => format!(".claude/{name}"),
+ ConfigLayerV1::Local => format!("local/{name}"),
ConfigLayerV1::User => format!("~/.claude/{name}"),
ConfigLayerV1::Managed => format!("managed/{name}"),
}
diff --git a/crates/integrations/src/agents/filesystem_tests.rs b/crates/integrations/src/agents/filesystem_tests.rs
index 90426fe6..fcdb4a3a 100644
--- a/crates/integrations/src/agents/filesystem_tests.rs
+++ b/crates/integrations/src/agents/filesystem_tests.rs
@@ -11,6 +11,8 @@ use crate::agents::{
#[path = "filesystem_tests/claude_routing.rs"]
mod claude_routing;
+#[path = "filesystem_tests/qoder.rs"]
+mod qoder;
fn write_executable(path: &Path, version: &str) {
fs::write(path, format!("#!/bin/sh\nprintf '%s\\n' '{version}'\n")).unwrap();
@@ -78,6 +80,9 @@ fn layout_with_claude_version(root: &Path, claude_version: &str) -> AgentFilesys
codex_executable: codex,
codex_desktop_executable: None,
claude_executable: claude,
+ qoder_executable: bin.join("qoder-not-installed"),
+ qoder_home: home.clone(),
+ qoder_config_root: home.join(".qoder"),
codex_user_config: home.join(".codex/config.toml"),
claude_launch_settings: None,
claude_project_settings: vec![root.join("project/.claude/settings.json")],
@@ -103,7 +108,7 @@ fn filesystem_scanner_registers_claude_and_never_serializes_token() {
);
let scanner = FilesystemAgentScannerV1::new(layout, registry());
let results = scanner.scan();
- assert_eq!(results.len(), 2);
+ assert_eq!(results.len(), 3);
let claude = results
.iter()
.find(|result| outcome_agent_id(&result.outcome) == "agent_claude_default")
@@ -892,7 +897,7 @@ fn filesystem_scan_keeps_missing_installation_and_other_agent_result() {
let mut layout = layout(directory.path());
layout.codex_executable = directory.path().join("not-installed");
let results = FilesystemAgentScannerV1::new(layout, registry()).scan();
- assert_eq!(results.len(), 2);
+ assert_eq!(results.len(), 3);
assert!(results.iter().any(|result| matches!(
&result.outcome,
AgentDiscoveryOutcomeV1::ReportOnly {
diff --git a/crates/integrations/src/agents/filesystem_tests/qoder.rs b/crates/integrations/src/agents/filesystem_tests/qoder.rs
new file mode 100644
index 00000000..358076c7
--- /dev/null
+++ b/crates/integrations/src/agents/filesystem_tests/qoder.rs
@@ -0,0 +1,142 @@
+use super::*;
+
+#[test]
+fn qoder_discovery_does_not_launch_or_read_model_and_auth_configuration() {
+ let directory = tempfile::tempdir().unwrap();
+ let mut layout = layout(directory.path());
+ layout.qoder_executable = directory.path().join("bin/qoder");
+ write_executable(&layout.qoder_executable, "should never execute");
+ let launched = directory.path().join("unexpected-launch");
+ fs::write(
+ &layout.qoder_executable,
+ format!(
+ "#!/bin/sh\nprintf launched > '{}'\nexit 91\n",
+ launched.display()
+ ),
+ )
+ .unwrap();
+ fs::create_dir_all(&layout.qoder_config_root).unwrap();
+ // Deliberately invalid settings and an auth-shaped file cannot prevent collaboration
+ // discovery or become a model/source import. Neither needs parsing for this capability.
+ fs::write(
+ layout.qoder_config_root.join("settings.json"),
+ b"invalid model/provider secret-sentinel",
+ )
+ .unwrap();
+ fs::write(
+ layout.qoder_config_root.join("auth.json"),
+ b"auth-secret-sentinel",
+ )
+ .unwrap();
+ let expected_target = layout
+ .qoder_config_root
+ .join("skills/hiroute-collaboration/SKILL.md");
+ let scanner = FilesystemAgentScannerV1::new(layout, registry());
+ let found = scanner.qoder_settings_discovery(true);
+ assert!(
+ !launched.exists(),
+ "discovery must not run a behavior probe"
+ );
+ let AgentDiscoveryOutcomeV1::Supported { installation } = &found.outcome else {
+ panic!("Qoder path should be discovered: {:?}", found.outcome)
+ };
+ assert_eq!(installation.profile.kind, AgentKindV1::Qoder);
+ assert_eq!(
+ installation.profile.ingress_protocol,
+ Some(hiroute_domain::AgentIngressProtocolV1::Responses)
+ );
+ assert!(installation.effective_config.is_empty());
+ // A registered model adapter and a located CLI are not proof of configured access or
+ // model verification. Collaboration proof is independently absent until its actual probe.
+ for action in [
+ hiroute_domain::AgentAction::ConfigureModel,
+ hiroute_domain::AgentAction::VerifyModel,
+ ] {
+ assert!(installation.require_action(action).is_err());
+ }
+ assert!(
+ installation
+ .require_action(hiroute_domain::AgentAction::InstallCollaborationSkill)
+ .is_err()
+ );
+ assert!(found.discovered_credential.is_none());
+ assert_eq!(scanner.qoder_user_skill_target(), expected_target);
+ assert_eq!(
+ scanner.available_model_surfaces("agent_qoder_default"),
+ [hiroute_domain::AgentModelSurfaceV2::QoderCli]
+ .into_iter()
+ .collect()
+ );
+ assert!(
+ scanner
+ .codex_engine_target(hiroute_domain::AgentModelSurfaceV2::QoderCli)
+ .is_none()
+ );
+ assert!(!launched.exists());
+ assert!(
+ !serde_json::to_string(&found)
+ .unwrap()
+ .contains("secret-sentinel")
+ );
+}
+
+#[test]
+fn missing_selected_qoder_never_switches_to_a_different_installed_cli() {
+ let directory = tempfile::tempdir().unwrap();
+ let mut layout = layout(directory.path());
+ layout.qoder_executable = directory.path().join("missing-selected-qoder");
+ let alternate = layout.qoder_home.join(".local/bin");
+ fs::create_dir_all(&alternate).unwrap();
+ write_executable(&alternate.join("qodercli"), "not selected");
+ let scanner = FilesystemAgentScannerV1::new(layout, registry());
+ assert!(scanner.qoder_executable_target().is_none());
+ assert!(
+ scanner
+ .available_model_surfaces("agent_qoder_default")
+ .is_empty()
+ );
+ assert!(matches!(
+ scanner.qoder_settings_discovery(false).outcome,
+ AgentDiscoveryOutcomeV1::ReportOnly {
+ reason: AgentReportOnlyReasonV1::NotFoundInScope,
+ ..
+ }
+ ));
+}
+
+#[test]
+#[cfg(unix)]
+fn failed_explicit_reverification_invalidates_previous_installed_skill_proof() {
+ use crate::agents::{QoderCollaborationEvidence, QoderCollaborationProbeTarget};
+ let directory = tempfile::tempdir().unwrap();
+ let mut layout = layout(directory.path());
+ layout.qoder_executable = directory.path().join("bin/qoder");
+ write_executable(&layout.qoder_executable, "unused");
+ fs::write(&layout.qoder_executable, "#!/bin/sh\nexit 1\n").unwrap();
+ let cli = directory.path().join("bin/hiroute");
+ write_executable(
+ &cli,
+ r#"{"status":"succeeded","data":{"commands":[{"command_id":"schema.list"}]}}"#,
+ );
+ let target = layout
+ .qoder_config_root
+ .join("skills/hiroute-collaboration/SKILL.md");
+ fs::create_dir_all(target.parent().unwrap()).unwrap();
+ let content =
+ b"---\nname: hiroute-collaboration\ndescription: fixture\n---\nconfirmed fixture\n";
+ fs::write(&target, content).unwrap();
+ let scanner = FilesystemAgentScannerV1::new(layout, registry());
+ let target = QoderCollaborationProbeTarget::InstalledUserSkill {
+ expected_content: CanonicalDigest::of_bytes(content),
+ };
+ let evidence = QoderCollaborationEvidence::fixture(
+ &scanner.qoder_executable_target().unwrap(),
+ &scanner.qoder_native_context().unwrap(),
+ &cli,
+ target.clone(),
+ );
+ scanner.qoder_collaboration.lock().unwrap().evidence = Some(evidence);
+ assert!(scanner.qoder_installed_collaboration_verified());
+ assert!(scanner.check_qoder_collaboration(&cli, target).is_err());
+ assert!(!scanner.qoder_installed_collaboration_verified());
+}
diff --git a/crates/integrations/src/agents/mod.rs b/crates/integrations/src/agents/mod.rs
index 9b559167..4071da6c 100644
--- a/crates/integrations/src/agents/mod.rs
+++ b/crates/integrations/src/agents/mod.rs
@@ -25,7 +25,18 @@ mod native_claude_ingress_probe;
mod native_effects;
#[cfg(unix)]
mod native_ingress_probe;
+#[cfg(unix)]
+mod native_probe_process;
+#[cfg(unix)]
+pub use native_probe_process::NativeProbeProcess;
mod observed_capabilities;
+mod qoder;
+mod qoder_native;
+mod qoder_native_effects;
+mod qoder_provider;
+pub use qoder_native_effects::*;
+#[cfg(unix)]
+mod qoder_probe;
mod registration;
mod registry;
mod source_candidates;
@@ -50,6 +61,9 @@ pub use native_claude_ingress_probe::*;
pub use native_effects::*;
#[cfg(unix)]
pub use native_ingress_probe::*;
+pub use qoder::*;
+#[cfg(unix)]
+pub use qoder_probe::*;
pub use registration::*;
pub use registry::*;
pub use source_candidates::*;
diff --git a/crates/integrations/src/agents/native_probe_process.rs b/crates/integrations/src/agents/native_probe_process.rs
new file mode 100644
index 00000000..6ba63e12
--- /dev/null
+++ b/crates/integrations/src/agents/native_probe_process.rs
@@ -0,0 +1,181 @@
+//! Narrow ownership for a synchronous native check and its read-only CLI baseline.
+//! Exit observation retains the group leader until all mutating group signals are finished.
+use rustix::process::{
+ Pid, Signal, WaitId, WaitIdOptions, kill_process_group, test_kill_process_group, waitid,
+};
+use std::io::{self, Read};
+use std::path::Path;
+use std::process::Child;
+use std::time::{Duration, Instant};
+
+pub struct NativeProbeProcess {
+ child: Child,
+ group: Pid,
+ signals_closed: bool,
+ stopped: bool,
+}
+
+impl NativeProbeProcess {
+ /// The caller must spawn this child with process_group(0).
+ pub fn new(child: Child) -> Self {
+ Self {
+ group: Pid::from_child(&child),
+ child,
+ signals_closed: false,
+ stopped: false,
+ }
+ }
+
+ pub fn observe(&self) -> io::Result<Option<bool>> {
+ if self.signals_closed {
+ return Err(io::Error::other("native process ownership closed"));
+ }
+ waitid(
+ WaitId::Pid(self.group),
+ WaitIdOptions::EXITED | WaitIdOptions::NOHANG | WaitIdOptions::NOWAIT,
+ )
+ .map(|value| value.map(|status| status.exit_status() == Some(0)))
+ .map_err(Into::into)
+ }
+
+ fn signal(&self, signal: Signal) -> io::Result<()> {
+ let exited = self.observe()?.is_some();
+ match kill_process_group(self.group, signal) {
+ Ok(()) | Err(rustix::io::Errno::SRCH) => Ok(()),
+ // Darwin may refuse signalling an exited leader. Absence is checked after reap.
+ Err(rustix::io::Errno::PERM) if exited => Ok(()),
+ Err(error) => Err(error.into()),
+ }
+ }
+
+ pub fn stop(&mut self) -> io::Result<()> {
+ if self.stopped {
+ return Ok(());
+ }
+ if self.signals_closed {
+ return Err(io::Error::other("native process stop incomplete"));
+ }
+ self.signal(Signal::TERM)?;
+ std::thread::sleep(Duration::from_millis(100));
+ // The leader is still waitable even when it exited before a surviving tool.
+ self.signal(Signal::KILL)?;
+ self.signals_closed = true;
+ let start = Instant::now();
+ loop {
+ if self.child.try_wait()?.is_some() {
+ break;
+ }
+ if start.elapsed() > Duration::from_secs(1) {
+ return Err(io::Error::other("native process reap deadline"));
+ }
+ std::thread::sleep(Duration::from_millis(5));
+ }
+ // Never mutate this numeric PID/PGID again. A reused group yields conservative unknown.
+ loop {
+ if matches!(
+ test_kill_process_group(self.group),
+ Err(rustix::io::Errno::SRCH)
+ ) {
+ self.stopped = true;
+ return Ok(());
+ }
+ if start.elapsed() > Duration::from_secs(1) {
+ return Err(io::Error::other("native process scope remains"));
+ }
+ std::thread::sleep(Duration::from_millis(5));
+ }
+ }
+}
+
+impl Drop for NativeProbeProcess {
+ fn drop(&mut self) {
+ let _ = self.stop();
+ }
+}
+
+/// Rechecks the limit during the final read, including children that write and exit between polls.
+pub(super) fn read_bounded(path: &Path, limit: usize) -> io::Result<zeroize::Zeroizing<Vec<u8>>> {
+ let mut bytes = zeroize::Zeroizing::new(Vec::new());
+ std::fs::File::open(path)?
+ .take(limit as u64 + 1)
+ .read_to_end(&mut bytes)?;
+ if bytes.len() > limit {
+ return Err(io::Error::other("native output bound"));
+ }
+ Ok(bytes)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::os::unix::process::CommandExt;
+ use std::process::{Command, Stdio};
+
+ fn await_exit(child: &NativeProbeProcess) {
+ let start = Instant::now();
+ loop {
+ if child.observe().unwrap().is_some() {
+ return;
+ }
+ assert!(start.elapsed() < Duration::from_secs(2));
+ std::thread::sleep(Duration::from_millis(5));
+ }
+ }
+
+ #[test]
+ fn successful_probe_exit_remains_waitable_until_group_stop() {
+ let child = Command::new("/bin/sh")
+ .args(["-c", "exit 0"])
+ .process_group(0)
+ .spawn()
+ .unwrap();
+ let mut child = NativeProbeProcess::new(child);
+ await_exit(&child);
+ assert_eq!(child.observe().unwrap(), Some(true));
+ // A second WNOWAIT observation proves the first poll did not reap the leader.
+ assert_eq!(child.observe().unwrap(), Some(true));
+ child.stop().unwrap();
+ assert!(child.observe().is_err());
+ }
+
+ #[test]
+ fn leader_exit_does_not_abandon_term_ignoring_tool() {
+ let root = tempfile::tempdir().unwrap();
+ let pidfile = root.path().join("tool.pid");
+ let child = Command::new("/bin/sh")
+ .args([
+ "-c",
+ "trap '' TERM; sleep 90 & echo $! > \"$1\"; exit 0",
+ "probe",
+ ])
+ .arg(&pidfile)
+ .stdin(Stdio::null())
+ .stdout(Stdio::null())
+ .stderr(Stdio::null())
+ .process_group(0)
+ .spawn()
+ .unwrap();
+ let mut child = NativeProbeProcess::new(child);
+ await_exit(&child);
+ let tool = std::fs::read_to_string(pidfile).unwrap();
+ let _ = child.stop(); // An orphan zombie may conservatively leave scope unknown.
+ let state = Command::new("/bin/ps")
+ .args(["-p", tool.trim(), "-o", "stat="])
+ .output()
+ .unwrap();
+ let state = String::from_utf8_lossy(&state.stdout);
+ assert!(
+ state.trim().is_empty() || state.trim().starts_with('Z'),
+ "owned tool remains active: {state}"
+ );
+ }
+
+ #[test]
+ fn fast_exit_output_cannot_bypass_final_read_bound() {
+ let root = tempfile::tempdir().unwrap();
+ let path = root.path().join("out");
+ std::fs::write(&path, vec![b'x'; 1025]).unwrap();
+ assert!(read_bounded(&path, 1024).is_err());
+ assert_eq!(read_bounded(&path, 1025).unwrap().len(), 1025);
+ }
+}
diff --git a/crates/integrations/src/agents/qoder.rs b/crates/integrations/src/agents/qoder.rs
new file mode 100644
index 00000000..3ce90773
--- /dev/null
+++ b/crates/integrations/src/agents/qoder.rs
@@ -0,0 +1,208 @@
+//! Native Qoder context and transient routing. No account, model catalogue or auth file reads.
+//!
+//! The settings shape is an adapter detail, checked through real Responses requests. It is not
+//! a public Qoder configuration API or a persisted HiRoute producer contract.
+use std::path::{Component, Path, PathBuf};
+
+use serde_json::{Value, json};
+
+#[path = "qoder_budget.rs"]
+mod budget;
+pub use budget::{QoderTokenBudget, qoder_plan_token_budget};
+
+#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
+#[error("Qoder native check failed: {stage}")]
+pub struct QoderNativeError {
+ pub stage: &'static str,
+}
+
+impl From<hiroute_domain::QoderBudgetError> for QoderNativeError {
+ fn from(error: hiroute_domain::QoderBudgetError) -> Self {
+ qoder_error(error.stage)
+ }
+}
+
+pub(super) fn qoder_error(stage: &'static str) -> QoderNativeError {
+ QoderNativeError { stage }
+}
+
+/// The product instance chooses this context; the CLI location never chooses another HOME.
+#[derive(Clone, Debug, Eq, PartialEq)]
+pub struct QoderNativeContext {
+ pub home: PathBuf,
+ pub config_root: PathBuf,
+}
+
+impl QoderNativeContext {
+ pub fn from_selected(
+ home: &Path,
+ config_root: Option<&Path>,
+ ) -> Result<Self, QoderNativeError> {
+ let config_root = config_root
+ .map(Path::to_path_buf)
+ .unwrap_or_else(|| home.join(".qoder"));
+ for path in [home, config_root.as_path()] {
+ if !path.is_absolute()
+ || path.to_str().is_none_or(|value| value.contains('\0'))
+ || path.components().any(|part| part == Component::ParentDir)
+ {
+ return Err(qoder_error("selected native context"));
+ }
+ }
+ Ok(Self {
+ home: home.to_owned(),
+ config_root,
+ })
+ }
+
+ pub fn skill_target(&self) -> PathBuf {
+ self.config_root
+ .join("skills/hiroute-collaboration/SKILL.md")
+ }
+}
+
+pub struct QoderTransientRouteInput<'a> {
+ pub provider_id: &'a str,
+ /// Explicit numeric loopback origin followed by /v1, without query or credentials.
+ pub endpoint: &'a str,
+ pub alias: &'a str,
+ /// Environment variable name only. Credential bytes are never accepted by this renderer.
+ pub credential_env: &'a str,
+ pub context_window_tokens: Option<u64>,
+ /// Exact Worker Plan upper bound, or the independent probe's synthetic output budget.
+ pub max_output_tokens: u64,
+}
+
+pub struct QoderTransientRoute {
+ pub settings: Value,
+ /// Only the native selector receives this prefix; Gateway and Plan retain the raw alias.
+ pub native_model_id: String,
+}
+
+pub fn render_qoder_transient_route(
+ input: QoderTransientRouteInput<'_>,
+) -> Result<QoderTransientRoute, QoderNativeError> {
+ super::qoder_provider::validate_route(input.provider_id, input.endpoint)?;
+ if input.credential_env.is_empty()
+ || input.credential_env.len() > 128
+ || !input
+ .credential_env
+ .bytes()
+ .enumerate()
+ .all(|(index, byte)| {
+ byte == b'_' || byte.is_ascii_uppercase() || (index > 0 && byte.is_ascii_digit())
+ })
+ {
+ return Err(qoder_error("transient route input"));
+ }
+ let native_model_id = format!("{}/{}", input.provider_id, input.alias);
+ let model = super::qoder_provider::model(
+ input.alias,
+ input.context_window_tokens,
+ input.max_output_tokens,
+ )?;
+ let own_alias = json!({"modelConfig": {"model": native_model_id}});
+ let mut provider = super::qoder_provider::provider(
+ input.endpoint,
+ &format!("${{{}}}", input.credential_env),
+ vec![model],
+ );
+ provider["model"] = input.alias.into();
+ provider["routing"] = json!({
+ "utility":input.alias,"session_title":input.alias,"summary":input.alias,
+ "compact":input.alias,"subagent":input.alias,
+ });
+ let settings = json!({
+ "general": {
+ "enableAutoUpdate": false,
+ "sessionRetention": {"enabled": false},
+ "plan": {"modelRouting": false}
+ },
+ "disableAllHooks": true,
+ "agent": "",
+ "plugins": {"autoUpdate": false},
+ "autoMemoryEnabled": false,
+ "autoMemoryUserScopeEnabled": false,
+ "dream": {"enabled": false},
+ "promptSuggestionEnabled": false,
+ "model": {"name": native_model_id},
+ "modelConfigs": {
+ "aliases": {(native_model_id.clone()): own_alias},
+ "customAliases": {(native_model_id.clone()): own_alias},
+ "overrides": [],
+ "customOverrides": []
+ },
+ "providers": {(input.provider_id): provider}
+ });
+ Ok(QoderTransientRoute {
+ settings,
+ native_model_id,
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn frozen_alias_is_preserved_and_credentials_remain_environment_references() {
+ let route = render_qoder_transient_route(QoderTransientRouteInput {
+ provider_id: "hiroute-worker-123",
+ endpoint: "http://127.0.0.1:1234/v1",
+ alias: "plan/branch:cheap",
+ credential_env: "HIROUTE_RUN_TOKEN",
+ context_window_tokens: Some(100_000),
+ max_output_tokens: 4096,
+ })
+ .unwrap();
+ assert_eq!(
+ route.native_model_id,
+ "hiroute-worker-123/plan/branch:cheap"
+ );
+ let provider = &route.settings["providers"]["hiroute-worker-123"];
+ assert_eq!(provider["model"], "plan/branch:cheap");
+ assert_eq!(provider["apiKey"], "${HIROUTE_RUN_TOKEN}");
+ assert_eq!(provider["models"][0]["contextWindow"], 100_000);
+ assert_eq!(provider["models"][0]["maxOutputTokens"], 4096);
+ for purpose in ["utility", "session_title", "summary", "compact", "subagent"] {
+ assert_eq!(provider["routing"][purpose], "plan/branch:cheap");
+ }
+ }
+
+ #[test]
+ fn transient_route_rejects_foreign_origin_or_inline_credentials() {
+ for endpoint in [
+ "https://example.com/v1",
+ "http://localhost:1234/v1",
+ "http://[email protected]:1234/v1",
+ "http://127.0.0.1:1234/v1?token=x",
+ ] {
+ assert!(
+ render_qoder_transient_route(QoderTransientRouteInput {
+ provider_id: "hiroute",
+ endpoint,
+ alias: "plan/one",
+ credential_env: "HIROUTE_RUN_TOKEN",
+ context_window_tokens: None,
+ max_output_tokens: 2048,
+ })
+ .is_err()
+ );
+ }
+ }
+
+ #[test]
+ fn explicit_context_does_not_recover_another_home() {
+ let context = QoderNativeContext::from_selected(
+ Path::new("/pilot/home"),
+ Some(Path::new("/pilot/qoder-context")),
+ )
+ .unwrap();
+ assert_eq!(context.home, Path::new("/pilot/home"));
+ assert_eq!(
+ context.skill_target(),
+ Path::new("/pilot/qoder-context/skills/hiroute-collaboration/SKILL.md")
+ );
+ assert!(QoderNativeContext::from_selected(Path::new("relative"), None).is_err());
+ }
+}
diff --git a/crates/integrations/src/agents/qoder_budget.rs b/crates/integrations/src/agents/qoder_budget.rs
new file mode 100644
index 00000000..12f3ab6a
--- /dev/null
+++ b/crates/integrations/src/agents/qoder_budget.rs
@@ -0,0 +1,48 @@
+//! Frozen Worker token budgets projected into Qoder's native model catalogue.
+use hiroute_domain::MaterializedAgentPlanV1;
+
+use super::{QoderNativeError, qoder_error};
+
+pub use hiroute_domain::QoderTokenBudget;
+
+pub(super) fn validate_output(tokens: u64) -> Result<(), QoderNativeError> {
+ hiroute_domain::validate_qoder_output_budget(tokens).map_err(Into::into)
+}
+
+pub fn qoder_plan_token_budget(
+ plan: &MaterializedAgentPlanV1,
+) -> Result<QoderTokenBudget, QoderNativeError> {
+ // Reuse the Plan policy, including total/output/reasoning reservations and
+ // an explicitly chosen smaller window. Do not reconstruct an input capacity.
+ let context = plan
+ .context_window_tokens()
+ .map_err(|_| qoder_error("frozen Plan context budget"))?;
+ let mut output = None;
+ for candidate in plan
+ .attempt_owned
+ .groups
+ .iter()
+ .flat_map(|group| &group.candidates)
+ {
+ for profile in &candidate.protocol_profiles {
+ let current = profile
+ .capability
+ .context
+ .max_output_tokens
+ .exact()
+ .copied()
+ .ok_or_else(|| qoder_error("frozen Plan output budget"))?;
+ validate_output(current)?;
+ output = Some(output.map_or(current, |previous: u64| previous.min(current)));
+ }
+ }
+ QoderTokenBudget::new(
+ context,
+ output.ok_or_else(|| qoder_error("frozen Plan output budget"))?,
+ )
+ .map_err(Into::into)
+}
+
+#[cfg(test)]
+#[path = "qoder_budget_tests.rs"]
+mod tests;
diff --git a/crates/integrations/src/agents/qoder_budget_tests.rs b/crates/integrations/src/agents/qoder_budget_tests.rs
new file mode 100644
index 00000000..989dd66c
--- /dev/null
+++ b/crates/integrations/src/agents/qoder_budget_tests.rs
@@ -0,0 +1,145 @@
+use super::*;
+use hiroute_domain::{
+ GatewayCriticalFactV1 as Fact, GatewayPublicationV1, GatewayReasoningAccountingV1,
+};
+
+fn plan() -> MaterializedAgentPlanV1 {
+ let publication: GatewayPublicationV1 = serde_json::from_slice(include_bytes!(
+ "../../../../e2e/product/fixtures/routing/current-publication.v3.json"
+ ))
+ .unwrap();
+ publication.plans[0].body.materialized.clone()
+}
+
+#[test]
+fn mixed_candidates_and_protocols_share_the_smallest_exact_output() {
+ let mut plan = plan();
+ plan.attempt_owned.limits.context_window_tokens = Some(32_768);
+ let mut fallback = plan.attempt_owned.groups[0].clone();
+ // The tightest output belongs to a later group and a non-first protocol.
+ let profiles = &mut fallback.candidates.last_mut().unwrap().protocol_profiles;
+ assert!(profiles.len() > 1);
+ profiles
+ .last_mut()
+ .unwrap()
+ .capability
+ .context
+ .max_output_tokens = Fact::Exact(4096);
+ plan.attempt_owned.groups.push(fallback);
+ assert_eq!(
+ qoder_plan_token_budget(&plan).unwrap(),
+ QoderTokenBudget {
+ context_window_tokens: 32_768,
+ max_output_tokens: 4096
+ }
+ );
+}
+
+#[test]
+fn one_unknown_or_zero_output_cannot_be_skipped_in_a_mixed_plan() {
+ for invalid in [Fact::Unknown, Fact::Exact(0)] {
+ let mut plan = plan();
+ plan.attempt_owned
+ .groups
+ .last_mut()
+ .unwrap()
+ .candidates
+ .last_mut()
+ .unwrap()
+ .protocol_profiles
+ .last_mut()
+ .unwrap()
+ .capability
+ .context
+ .max_output_tokens = invalid;
+ assert!(qoder_plan_token_budget(&plan).is_err());
+ }
+}
+
+#[test]
+fn total_and_reasoning_reservations_and_the_selected_window_remain_authoritative() {
+ let mut plan = plan();
+ for candidate in plan
+ .attempt_owned
+ .groups
+ .iter_mut()
+ .flat_map(|g| &mut g.candidates)
+ {
+ for profile in &mut candidate.protocol_profiles {
+ profile.capability.context.max_input_tokens = Fact::Exact(100_000);
+ profile.capability.context.max_output_tokens = Fact::Exact(4096);
+ profile.capability.context.max_total_tokens = Fact::Exact(Some(50_000));
+ for reasoning in &mut profile.capability.reasoning_profiles {
+ reasoning.accounting = GatewayReasoningAccountingV1::Additive;
+ reasoning.additional_reservation_tokens = 8192;
+ }
+ }
+ }
+ assert_eq!(
+ qoder_plan_token_budget(&plan)
+ .unwrap()
+ .context_window_tokens,
+ 37_712
+ );
+ plan.attempt_owned.limits.context_window_tokens = Some(32_768);
+ assert_eq!(
+ qoder_plan_token_budget(&plan)
+ .unwrap()
+ .context_window_tokens,
+ 32_768
+ );
+ plan.attempt_owned.limits.context_window_tokens = Some(37_713);
+ assert!(qoder_plan_token_budget(&plan).is_err());
+}
+
+#[test]
+fn zero_native_compaction_threshold_is_rejected_without_rounding_up_the_window() {
+ for (context, output) in [
+ (0, 4096),
+ (32_768, 32_000),
+ (33_000, 32_000),
+ (17_096, 4096),
+ ] {
+ assert!(QoderTokenBudget::new(context, output).is_err());
+ }
+ for (context, output) in [(17_097, 4096), (32_768, 4096), (100_000, 32_000)] {
+ let budget = QoderTokenBudget::new(context, output).unwrap();
+ assert_eq!(
+ (budget.context_window_tokens, budget.max_output_tokens),
+ (context, output)
+ );
+ }
+ assert!(QoderTokenBudget::new(100_000, 0).is_err());
+ assert!(QoderTokenBudget::new(1 << 53, 4096).is_err());
+ assert!(QoderTokenBudget::new(100_000, 1 << 53).is_err());
+}
+
+#[test]
+fn renderer_requires_a_usable_worker_budget_and_keeps_probe_budget_separate() {
+ for (context, output, accepted) in [
+ (Some(32_768), 4096, true),
+ (Some(32_768), 32_000, false),
+ (Some(17_096), 4096, false),
+ (Some(100_000), 0, false),
+ (None, 2048, true),
+ ] {
+ let route =
+ crate::agents::render_qoder_transient_route(super::super::QoderTransientRouteInput {
+ provider_id: "hiroute-budget-test",
+ endpoint: "http://127.0.0.1:4321/v1",
+ alias: "plan/branch:cheap",
+ credential_env: "HIROUTE_RUN_TOKEN",
+ context_window_tokens: context,
+ max_output_tokens: output,
+ });
+ assert_eq!(route.is_ok(), accepted);
+ if let Ok(route) = route {
+ let model = &route.settings["providers"]["hiroute-budget-test"]["models"][0];
+ assert_eq!(model["maxOutputTokens"], output);
+ match context {
+ Some(context) => assert_eq!(model["contextWindow"], context),
+ None => assert!(model.get("contextWindow").is_none()),
+ }
+ }
+ }
+}
diff --git a/crates/integrations/src/agents/qoder_discovery.rs b/crates/integrations/src/agents/qoder_discovery.rs
new file mode 100644
index 00000000..3241692d
--- /dev/null
+++ b/crates/integrations/src/agents/qoder_discovery.rs
@@ -0,0 +1,205 @@
+//! Qoder discovery locates an executable and one user Skill target, never model/auth settings.
+use super::super::{QoderNativeContext, QoderNativeError, qoder::qoder_error};
+use super::*;
+
+impl FilesystemAgentScannerV1 {
+ pub fn qoder_native_context(&self) -> Result<QoderNativeContext, QoderNativeError> {
+ QoderNativeContext::from_selected(
+ &self.layout.qoder_home,
+ Some(&self.layout.qoder_config_root),
+ )
+ }
+
+ /// Identity only. Discovery does not read settings; explicit configuration effects own
+ /// one additional provider in this file, independently of collaboration discovery.
+ pub fn qoder_user_config_target(&self) -> PathBuf {
+ self.layout.qoder_config_root.join("settings.json")
+ }
+
+ pub fn qoder_user_skill_target(&self) -> PathBuf {
+ self.layout
+ .qoder_config_root
+ .join("skills/hiroute-collaboration/SKILL.md")
+ }
+
+ pub fn qoder_executable_target(&self) -> Option<PathBuf> {
+ self.located_qoder().ok().flatten()
+ }
+
+ fn located_qoder(&self) -> Result<Option<PathBuf>, super::super::executable::ProbeFailure> {
+ let selected = &self.layout.qoder_executable;
+ if selected.is_absolute() || selected.components().count() > 1 {
+ // A selected installation must fail visibly rather than switch to a PATH candidate.
+ return super::super::executable::resolve(selected);
+ }
+ let mut directories = std::env::var_os("PATH")
+ .map(|value| {
+ std::env::split_paths(&value)
+ .filter(|p| p.is_absolute())
+ .collect::<Vec<_>>()
+ })
+ .unwrap_or_default();
+ directories.extend([
+ self.layout.qoder_home.join(".local/bin"),
+ self.layout.qoder_home.join(".qoder/bin"),
+ PathBuf::from("/usr/local/bin"),
+ PathBuf::from("/usr/bin"),
+ ]);
+ #[cfg(target_os = "macos")]
+ directories.push(PathBuf::from("/opt/homebrew/bin"));
+ let mut first_failure = None;
+ for directory in directories.into_iter().take(128) {
+ for name in [selected.as_os_str(), std::ffi::OsStr::new("qodercli")] {
+ match super::super::executable::resolve(&directory.join(name)) {
+ Ok(Some(path)) => return Ok(Some(path)),
+ Ok(None) => {}
+ Err(error) => {
+ first_failure.get_or_insert(error);
+ }
+ }
+ }
+ }
+ // Standalone installations may expose only a versioned native binary. One bounded
+ // directory listing is sufficient; never recurse through HOME or inspect binary bytes.
+ let directory = self.layout.qoder_home.join(".qoder/bin/qodercli");
+ if let Ok(entries) = std::fs::read_dir(directory) {
+ let mut candidates = entries
+ .take(64)
+ .filter_map(Result::ok)
+ .filter(|entry| entry.file_name().to_string_lossy().starts_with("qodercli-"))
+ .map(|entry| entry.path())
+ .collect::<Vec<_>>();
+ candidates.sort();
+ for path in candidates.into_iter().rev() {
+ match super::super::executable::resolve(&path) {
+ Ok(Some(path)) => return Ok(Some(path)),
+ Ok(None) => {}
+ Err(error) => {
+ first_failure.get_or_insert(error);
+ }
+ }
+ }
+ }
+ first_failure.map_or(Ok(None), Err)
+ }
+
+ pub fn qoder_settings_discovery(
+ &self,
+ include_collaboration_evidence: bool,
+ ) -> FilesystemAgentDiscoveryV1 {
+ let executable = match self.located_qoder() {
+ Ok(Some(executable)) => executable,
+ Ok(None) => {
+ return probe_report(
+ "agent_qoder_default",
+ AgentKindV1::Qoder,
+ ExecutableProbe::NotFound,
+ );
+ }
+ Err(reason) => {
+ return probe_report(
+ "agent_qoder_default",
+ AgentKindV1::Qoder,
+ ExecutableProbe::Unknown(reason),
+ );
+ }
+ };
+ let Ok(context) = self.qoder_native_context() else {
+ return report_only_agent(
+ "agent_qoder_default",
+ AgentKindV1::Qoder,
+ "not-probed".into(),
+ AgentReportOnlyReasonV1::ConfigUnavailable,
+ );
+ };
+ let mut outcome = resolve_agent_observation(base_observation(
+ "agent_qoder_default",
+ AgentKindV1::Qoder,
+ "not-probed".into(),
+ ));
+ if let AgentDiscoveryOutcomeV1::Supported { installation } = &mut outcome {
+ super::super::observed_capabilities::attach_file_capabilities(
+ installation,
+ &executable,
+ &context.skill_target(),
+ );
+ installation.capability_evidence.retain(|proof| {
+ !matches!(
+ proof.capability,
+ hiroute_domain::AgentCapability::EffectiveConfiguration
+ | hiroute_domain::AgentCapability::IngressAuthentication
+ | hiroute_domain::AgentCapability::ModelCatalog
+ )
+ });
+ // This check borrows normal native login and Skills. Its controlled local request
+ // is not evidence that the entire HOME or native client environment was isolated.
+ for proof in &mut installation.capability_evidence {
+ if proof.capability == hiroute_domain::AgentCapability::IsolatedVerification {
+ proof.reason = Some(hiroute_domain::CapabilityReason::IsolationUnproven);
+ }
+ }
+ #[cfg(unix)]
+ if include_collaboration_evidence
+ && let Ok(cache) = self.qoder_collaboration.lock()
+ && let Some(evidence) = cache.evidence.as_ref()
+ {
+ evidence.attach(&executable, &context, installation);
+ }
+ #[cfg(not(unix))]
+ let _ = include_collaboration_evidence;
+ }
+ FilesystemAgentDiscoveryV1 {
+ outcome,
+ configuration_issue: None,
+ claude_configuration: None,
+ discovered_credential: None,
+ permission_hardening: None,
+ managed_launch: None,
+ }
+ }
+
+ #[cfg(unix)]
+ pub fn qoder_installed_collaboration_verified(&self) -> bool {
+ let (Some(executable), Ok(context)) =
+ (self.qoder_executable_target(), self.qoder_native_context())
+ else {
+ return false;
+ };
+ self.qoder_collaboration
+ .lock()
+ .ok()
+ .and_then(|cache| {
+ cache
+ .evidence
+ .as_ref()
+ .map(|evidence| evidence.installed_user_verified(&executable, &context))
+ })
+ .unwrap_or(false)
+ }
+
+ #[cfg(unix)]
+ pub fn check_qoder_collaboration(
+ &self,
+ cli: &Path,
+ target: super::super::QoderCollaborationProbeTarget,
+ ) -> Result<(), QoderNativeError> {
+ let generation = self
+ .qoder_collaboration
+ .lock()
+ .map_err(|_| qoder_error("evidence cache"))?
+ .begin()?;
+ let executable = self
+ .qoder_executable_target()
+ .ok_or_else(|| qoder_error("selected executable"))?;
+ let evidence = super::super::QoderCollaborationProbe::run(
+ &executable,
+ &self.qoder_native_context()?,
+ cli,
+ target,
+ )?;
+ self.qoder_collaboration
+ .lock()
+ .map_err(|_| qoder_error("evidence cache"))?
+ .finish(generation, evidence)
+ }
+}
diff --git a/crates/integrations/src/agents/qoder_jsonc.rs b/crates/integrations/src/agents/qoder_jsonc.rs
new file mode 100644
index 00000000..361abfc7
--- /dev/null
+++ b/crates/integrations/src/agents/qoder_jsonc.rs
@@ -0,0 +1,279 @@
+//! Bounded JSON-with-comments edits preserve every byte outside the selected object member.
+//! Qoder accepts comments. Duplicate keys and trailing commas are rejected, never normalized.
+use std::ops::Range;
+
+use serde_json::{Map, Value};
+use zeroize::Zeroizing;
+
+use super::super::{QoderNativeError, qoder_error};
+
+pub(super) const LIMIT: usize = 1024 * 1024;
+
+pub(super) struct Document<'a> {
+ bytes: &'a [u8],
+ pub root: Node,
+}
+
+pub(super) struct Node {
+ pub value: Value,
+ pub range: Range<usize>,
+ members: Vec<Member>,
+}
+
+struct Member {
+ key: String,
+ start: usize,
+ value: Range<usize>,
+ comma: Option<usize>,
+}
+
+impl<'a> Document<'a> {
+ pub fn parse(bytes: &'a [u8]) -> Result<Self, QoderNativeError> {
+ if bytes.len() > LIMIT || std::str::from_utf8(bytes).is_err() {
+ return Err(invalid());
+ }
+ let mut parser = Parser { bytes, pos: 0 };
+ // Match Qoder's BOM handling without changing the original bytes.
+ if bytes.starts_with(&[0xef, 0xbb, 0xbf]) {
+ parser.pos = 3;
+ }
+ let root = parser.value(0)?;
+ parser.skip()?;
+ if parser.pos != bytes.len() || !root.value.is_object() {
+ return Err(invalid());
+ }
+ Ok(Self { bytes, root })
+ }
+
+ pub fn object(&self, parent: &Node, key: &str) -> Result<Option<Node>, QoderNativeError> {
+ let Some(member) = parent.members.iter().find(|member| member.key == key) else {
+ return Ok(None);
+ };
+ let mut parser = Parser {
+ bytes: self.bytes,
+ pos: member.value.start,
+ };
+ let node = parser.value(0)?;
+ if !node.value.is_object() {
+ return Err(invalid());
+ }
+ Ok(Some(node))
+ }
+
+ pub fn edit(
+ &self,
+ object: &Node,
+ key: &str,
+ value: Option<&Value>,
+ ) -> Result<Zeroizing<Vec<u8>>, QoderNativeError> {
+ let mut edits: Vec<(Range<usize>, Vec<u8>)> = Vec::new();
+ if let Some((index, member)) = object
+ .members
+ .iter()
+ .enumerate()
+ .find(|(_, member)| member.key == key)
+ {
+ if let Some(value) = value {
+ edits.push((
+ member.value.clone(),
+ serde_json::to_vec(value).map_err(|_| invalid())?,
+ ));
+ } else {
+ edits.push((member.start..member.value.end, Vec::new()));
+ if let Some(comma) = member
+ .comma
+ .or_else(|| index.checked_sub(1).and_then(|i| object.members[i].comma))
+ {
+ edits.push((comma..comma + 1, Vec::new()));
+ }
+ }
+ } else if let Some(value) = value {
+ let mut insert = if object.members.is_empty() {
+ Vec::new()
+ } else {
+ b",".to_vec()
+ };
+ insert.push(b'\n');
+ insert.extend(serde_json::to_vec(key).map_err(|_| invalid())?);
+ insert.push(b':');
+ insert.extend(serde_json::to_vec(value).map_err(|_| invalid())?);
+ insert.push(b'\n');
+ edits.push((object.range.end - 1..object.range.end - 1, insert));
+ }
+ edits.sort_by_key(|(range, _)| std::cmp::Reverse(range.start));
+ let mut result = Zeroizing::new(self.bytes.to_vec());
+ for (range, replacement) in edits {
+ result.splice(range, replacement);
+ }
+ Document::parse(&result)?;
+ Ok(result)
+ }
+}
+
+struct Parser<'a> {
+ bytes: &'a [u8],
+ pos: usize,
+}
+
+impl Parser<'_> {
+ fn skip(&mut self) -> Result<(), QoderNativeError> {
+ loop {
+ while self
+ .bytes
+ .get(self.pos)
+ .is_some_and(|byte| matches!(byte, b' ' | b'\t' | b'\r' | b'\n'))
+ {
+ self.pos += 1;
+ }
+ match self.bytes.get(self.pos..self.pos.saturating_add(2)) {
+ Some(b"//") => {
+ self.pos += 2;
+ while self.bytes.get(self.pos).is_some_and(|byte| *byte != b'\n') {
+ // Qoder 1.1.65's settings readers disagree on these line endings:
+ // strip-comments accepts LF/CRLF, while persistence tokenization also
+ // ends comments on standalone CR and Unicode line separators. Never
+ // accept a document whose foreign fields one reader could hide.
+ if (self.bytes[self.pos] == b'\r'
+ && self.bytes.get(self.pos + 1) != Some(&b'\n'))
+ || self.bytes[self.pos..].starts_with(&[0xe2, 0x80, 0xa8])
+ || self.bytes[self.pos..].starts_with(&[0xe2, 0x80, 0xa9])
+ {
+ return Err(invalid());
+ }
+ self.pos += 1;
+ }
+ }
+ Some(b"/*") => {
+ self.pos += 2;
+ loop {
+ if self.bytes.get(self.pos..self.pos.saturating_add(2)) == Some(b"*/") {
+ self.pos += 2;
+ break;
+ }
+ if self.pos >= self.bytes.len() {
+ return Err(invalid());
+ }
+ self.pos += 1;
+ }
+ }
+ _ => return Ok(()),
+ }
+ }
+ }
+
+ fn string(&mut self) -> Result<String, QoderNativeError> {
+ let start = self.pos;
+ if self.bytes.get(self.pos) != Some(&b'"') {
+ return Err(invalid());
+ }
+ self.pos += 1;
+ loop {
+ match self.bytes.get(self.pos) {
+ Some(b'"') => {
+ self.pos += 1;
+ break;
+ }
+ Some(b'\\') => {
+ self.pos += 2;
+ }
+ Some(_) => self.pos += 1,
+ None => return Err(invalid()),
+ }
+ }
+ serde_json::from_slice(&self.bytes[start..self.pos]).map_err(|_| invalid())
+ }
+
+ fn value(&mut self, depth: usize) -> Result<Node, QoderNativeError> {
+ if depth > 64 {
+ return Err(invalid());
+ }
+ self.skip()?;
+ let start = self.pos;
+ let mut members = Vec::new();
+ let value = match self.bytes.get(self.pos) {
+ Some(b'{') => {
+ self.pos += 1;
+ self.skip()?;
+ let mut object = Map::new();
+ if self.bytes.get(self.pos) != Some(&b'}') {
+ loop {
+ self.skip()?;
+ let key_start = self.pos;
+ let key = self.string()?;
+ self.skip()?;
+ if self.bytes.get(self.pos) != Some(&b':') {
+ return Err(invalid());
+ }
+ self.pos += 1;
+ let child = self.value(depth + 1)?;
+ if object.insert(key.clone(), child.value).is_some() {
+ return Err(invalid());
+ }
+ self.skip()?;
+ let comma = (self.bytes.get(self.pos) == Some(&b',')).then_some(self.pos);
+ members.push(Member {
+ key,
+ start: key_start,
+ value: child.range,
+ comma,
+ });
+ if comma.is_none() {
+ break;
+ }
+ self.pos += 1;
+ }
+ }
+ if self.bytes.get(self.pos) != Some(&b'}') {
+ return Err(invalid());
+ }
+ self.pos += 1;
+ Value::Object(object)
+ }
+ Some(b'[') => {
+ self.pos += 1;
+ self.skip()?;
+ let mut array = Vec::new();
+ if self.bytes.get(self.pos) != Some(&b']') {
+ loop {
+ array.push(self.value(depth + 1)?.value);
+ self.skip()?;
+ if self.bytes.get(self.pos) != Some(&b',') {
+ break;
+ }
+ self.pos += 1;
+ }
+ }
+ if self.bytes.get(self.pos) != Some(&b']') {
+ return Err(invalid());
+ }
+ self.pos += 1;
+ Value::Array(array)
+ }
+ Some(b'"') => Value::String(self.string()?),
+ Some(_) => {
+ while self.bytes.get(self.pos).is_some_and(|byte| {
+ !matches!(
+ byte,
+ b' ' | b'\t' | b'\r' | b'\n' | b',' | b'}' | b']' | b'/'
+ )
+ }) {
+ self.pos += 1;
+ }
+ if self.pos == start {
+ return Err(invalid());
+ }
+ serde_json::from_slice(&self.bytes[start..self.pos]).map_err(|_| invalid())?
+ }
+ None => return Err(invalid()),
+ };
+ Ok(Node {
+ value,
+ range: start..self.pos,
+ members,
+ })
+ }
+}
+
+fn invalid() -> QoderNativeError {
+ qoder_error("native settings JSON")
+}
diff --git a/crates/integrations/src/agents/qoder_native.rs b/crates/integrations/src/agents/qoder_native.rs
new file mode 100644
index 00000000..bc54647b
--- /dev/null
+++ b/crates/integrations/src/agents/qoder_native.rs
@@ -0,0 +1,294 @@
+//! Additional main-Agent providers. No native catalog import or default/purpose takeover.
+use std::collections::BTreeSet;
+
+use hiroute_domain::{AgentAccessGrantMaterial, CanonicalDigest, QoderAdditionalModelV1};
+use serde::{Deserialize, Serialize};
+use serde_json::Value;
+use zeroize::{Zeroize, Zeroizing};
+
+use super::{QoderNativeError, qoder_error, qoder_provider};
+#[path = "qoder_jsonc.rs"]
+mod jsonc;
+use jsonc::Document;
+use jsonc::LIMIT;
+
+// This structure is serialized only into NativeAgentArtifactPort's encrypted restore envelope.
+// It deliberately has no Debug implementation or public JSON conversion.
+#[derive(Deserialize, Serialize)]
+#[serde(deny_unknown_fields)]
+pub(super) struct Restore {
+ schema: String,
+ provider_id: String,
+ provider_digest: CanonicalDigest,
+ rendered_digest: CanonicalDigest,
+ original_exists: bool,
+ #[serde(skip)]
+ original: Vec<u8>,
+}
+
+impl Drop for Restore {
+ fn drop(&mut self) {
+ self.original.zeroize();
+ }
+}
+
+pub(super) struct Edit {
+ pub bytes: Zeroizing<Vec<u8>>,
+ pub restore: Restore,
+}
+
+pub(super) fn validate_declaration(
+ provider_id: &str,
+ endpoint: &str,
+ models: &[QoderAdditionalModelV1],
+) -> Result<(), QoderNativeError> {
+ qoder_provider::validate_model_route(provider_id, endpoint)?;
+ if provider_id
+ .strip_prefix("hiroute-main-")
+ .is_none_or(|suffix| {
+ suffix.len() != 64
+ || !suffix
+ .bytes()
+ .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
+ })
+ {
+ return Err(qoder_error("main provider identity"));
+ }
+ let mut aliases = BTreeSet::new();
+ if models.is_empty() {
+ return Err(qoder_error("additional models"));
+ }
+ for model in models {
+ model
+ .validate()
+ .map_err(|_| qoder_error("additional model"))?;
+ if !aliases.insert(&model.alias) {
+ return Err(qoder_error("additional model alias"));
+ }
+ }
+ Ok(())
+}
+
+fn document(current: Option<&[u8]>) -> Result<Document<'_>, QoderNativeError> {
+ Document::parse(current.unwrap_or(b"{}"))
+}
+
+fn owned<'a>(
+ document: &'a Document<'_>,
+ provider: &str,
+) -> Result<Option<&'a Value>, QoderNativeError> {
+ let Some(providers) = document.root.value.get("providers") else {
+ return Ok(None);
+ };
+ Ok(providers
+ .as_object()
+ .ok_or_else(|| qoder_error("native providers object"))?
+ .get(provider))
+}
+
+pub(super) fn validate_configuration(
+ current: Option<&[u8]>,
+ provider_id: &str,
+ endpoint: &str,
+ models: &[QoderAdditionalModelV1],
+ previous: Option<&Restore>,
+) -> Result<(), QoderNativeError> {
+ validate_declaration(provider_id, endpoint, models)?;
+ let document = document(current)?;
+ if let Some(previous) = previous {
+ if previous.provider_id != provider_id || !previous.applied(current)? {
+ return Err(qoder_error("owned provider changed"));
+ }
+ let retain = models
+ .iter()
+ .map(|model| format!("{provider_id}/{}", model.alias))
+ .collect();
+ default_not_removed(&document, provider_id, &retain)?;
+ } else if owned(&document, provider_id)?.is_some() {
+ return Err(qoder_error("provider already exists"));
+ }
+ Ok(())
+}
+
+fn default_not_removed(
+ document: &Document<'_>,
+ provider: &str,
+ retain: &BTreeSet<String>,
+) -> Result<(), QoderNativeError> {
+ let Some(model) = document.root.value.get("model") else {
+ return Ok(());
+ };
+ let model = model
+ .as_object()
+ .ok_or_else(|| qoder_error("native model object"))?;
+ if let Some(default) = model.get("name") {
+ let default = default
+ .as_str()
+ .ok_or_else(|| qoder_error("native default model"))?;
+ // Every selector inside our owned provider disappears when it is removed, including a
+ // stale alias no longer present in its declared models. Never choose a replacement.
+ if default.starts_with(&format!("{provider}/")) && !retain.contains(default) {
+ return Err(qoder_error("default in use"));
+ }
+ }
+ Ok(())
+}
+
+pub(super) fn configure(
+ current: Option<&[u8]>,
+ provider_id: &str,
+ endpoint: &str,
+ models: &[QoderAdditionalModelV1],
+ material: &AgentAccessGrantMaterial,
+ previous: Option<&Restore>,
+) -> Result<Edit, QoderNativeError> {
+ validate_configuration(current, provider_id, endpoint, models, previous)?;
+ let base = match previous {
+ Some(previous) => previous.remove_owned(current, false)?,
+ None => current.map(|bytes| Zeroizing::new(bytes.to_vec())),
+ };
+ let credential =
+ std::str::from_utf8(material.expose()).map_err(|_| qoder_error("local grant encoding"))?;
+ let models = models
+ .iter()
+ .map(|model| {
+ qoder_provider::model(
+ &model.alias,
+ Some(model.context_window_tokens),
+ model.max_output_tokens,
+ )
+ })
+ .collect::<Result<Vec<_>, _>>()?;
+ // Omit provider.model and routing. Qoder retains the selected model for auxiliary purposes;
+ // a multi-model provider must not redirect every purpose to its first entry.
+ let provider = qoder_provider::provider(endpoint, credential, models);
+ let document = document(base.as_deref().map(Vec::as_slice))?;
+ let bytes = if let Some(providers) = document.object(&document.root, "providers")? {
+ document.edit(&providers, provider_id, Some(&provider))?
+ } else {
+ document.edit(
+ &document.root,
+ "providers",
+ Some(&serde_json::json!({(provider_id):provider})),
+ )?
+ };
+ let restore = Restore {
+ schema: "hiroute.qoder-native-restore/v1".into(),
+ provider_id: provider_id.into(),
+ provider_digest: digest(&provider)?,
+ rendered_digest: CanonicalDigest::of_bytes(&bytes),
+ original_exists: base.is_some(),
+ original: base.map_or_else(Vec::new, |bytes| bytes.to_vec()),
+ };
+ Ok(Edit { bytes, restore })
+}
+
+impl Restore {
+ pub fn encode(&self) -> Result<Zeroizing<Vec<u8>>, QoderNativeError> {
+ let header = serde_json::to_vec(self).map_err(|_| qoder_error("restore encoding"))?;
+ let size = header
+ .len()
+ .checked_add(self.original.len())
+ .and_then(|size| size.checked_add(4))
+ .filter(|size| *size <= LIMIT)
+ .ok_or_else(|| qoder_error("restore bound"))?;
+ let mut bytes = Zeroizing::new(Vec::with_capacity(size));
+ bytes.extend_from_slice(&(header.len() as u32).to_le_bytes());
+ bytes.extend_from_slice(&header);
+ bytes.extend_from_slice(&self.original);
+ Ok(bytes)
+ }
+
+ pub fn decode(bytes: &[u8]) -> Result<Self, QoderNativeError> {
+ if bytes.len() < 5 || bytes.len() > LIMIT {
+ return Err(qoder_error("restore bound"));
+ }
+ let length = u32::from_le_bytes(bytes[..4].try_into().expect("bounded header")) as usize;
+ let end = 4usize
+ .checked_add(length)
+ .filter(|end| *end <= bytes.len())
+ .ok_or_else(|| qoder_error("restore bound"))?;
+ let mut record: Self =
+ serde_json::from_slice(&bytes[4..end]).map_err(|_| qoder_error("restore encoding"))?;
+ record.original = bytes[end..].to_vec();
+ if record.schema != "hiroute.qoder-native-restore/v1"
+ || record
+ .provider_id
+ .strip_prefix("hiroute-main-")
+ .is_none_or(|s| {
+ s.len() != 64
+ || !s
+ .bytes()
+ .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
+ })
+ || (!record.original_exists && !record.original.is_empty())
+ {
+ return Err(qoder_error("restore schema"));
+ }
+ CanonicalDigest::parse(record.provider_digest.as_str())
+ .map_err(|_| qoder_error("restore digest"))?;
+ CanonicalDigest::parse(record.rendered_digest.as_str())
+ .map_err(|_| qoder_error("restore digest"))?;
+ let original = document(record.original_exists.then_some(record.original.as_slice()))?;
+ if owned(&original, &record.provider_id)?.is_some() {
+ return Err(qoder_error("restore ownership"));
+ }
+ Ok(record)
+ }
+
+ pub fn applied(&self, current: Option<&[u8]>) -> Result<bool, QoderNativeError> {
+ let document = document(current)?;
+ Ok(owned(&document, &self.provider_id)?
+ .map(digest)
+ .transpose()?
+ .as_ref()
+ == Some(&self.provider_digest))
+ }
+
+ pub fn validate_restoration(&self, current: Option<&[u8]>) -> Result<(), QoderNativeError> {
+ self.remove_owned(current, true).map(|_| ())
+ }
+
+ pub fn restore(
+ &self,
+ current: Option<&[u8]>,
+ ) -> Result<Option<Zeroizing<Vec<u8>>>, QoderNativeError> {
+ self.remove_owned(current, true)
+ }
+
+ fn remove_owned(
+ &self,
+ current: Option<&[u8]>,
+ check_default: bool,
+ ) -> Result<Option<Zeroizing<Vec<u8>>>, QoderNativeError> {
+ let document = document(current)?;
+ if check_default {
+ default_not_removed(&document, &self.provider_id, &BTreeSet::new())?;
+ }
+ if current.is_none() && !self.original_exists {
+ return Ok(None);
+ }
+ if !self.applied(current)? {
+ return Err(qoder_error("owned provider changed"));
+ }
+ if current.is_some_and(|bytes| CanonicalDigest::of_bytes(bytes) == self.rendered_digest) {
+ return Ok(self
+ .original_exists
+ .then(|| Zeroizing::new(self.original.clone())));
+ }
+ let providers = document
+ .object(&document.root, "providers")?
+ .ok_or_else(|| qoder_error("owned provider missing"))?;
+ // A user may have added comments/foreign members since Apply. Preserve those exact bytes,
+ // including an empty providers container, instead of replaying a whole-file backup.
+ Ok(Some(document.edit(&providers, &self.provider_id, None)?))
+ }
+}
+
+fn digest(value: &Value) -> Result<CanonicalDigest, QoderNativeError> {
+ CanonicalDigest::of(value).map_err(|_| qoder_error("provider digest"))
+}
+
+#[cfg(test)]
+#[path = "qoder_native_tests.rs"]
+mod tests;
diff --git a/crates/integrations/src/agents/qoder_native/README.md b/crates/integrations/src/agents/qoder_native/README.md
new file mode 100644
index 00000000..ec9e2c5c
--- /dev/null
+++ b/crates/integrations/src/agents/qoder_native/README.md
@@ -0,0 +1,94 @@
+# Qoder additional model routes
+
+This adapter owns one `providers.hiroute-main-<context digest>` entry in the
+selected Qoder user settings file. It adds the selected HiRoute Plan aliases to
+Qoder's native model selector. It does not import native accounts/models or write
+`model.name`, model overrides, purpose routing, hooks, MCP, or Skills.
+
+See the [Agent capability map](../../../../../docs/code-map/README.md) for production owners and representative tests.
+The native `providers` shape is tested against Qoder 1.1.65; its public CLI docs
+direct users to the `/model` wizard. Treat an upgraded native release as a real
+capability/verification boundary, not an automatically compatible configuration API.
+
+## Responsibilities
+
+- [Provider projection](../qoder_provider.rs) shares only the actual provider/model
+ fields with the transient Worker/probe renderer. Main-Agent configuration omits
+ the Worker's default model, fixed purpose mapping and extension restrictions.
+- [Native edits](../qoder_native.rs) enforce the independent provider namespace,
+ exact model budgets, semantic ownership and default-reference conflicts.
+- [JSON-with-comments edits](../qoder_jsonc.rs) preserve unrelated bytes, including
+ comments. Ambiguous duplicate keys, invalid JSON and oversized files fail closed.
+ Line comments support LF and CRLF. Standalone CR and Unicode line separators
+ inside line comments are rejected because Qoder's settings readers disagree on
+ their interpretation; no foreign field may be hidden by that disagreement.
+- [Operation effects](../qoder_native_effects.rs) use the existing protected
+ artifact port for snapshot comparison, encrypted restore records, replay and
+ sensitive staging. The application owns authorization, grants, publication and
+ restore-first ordering; these functions do not start their own transaction.
+
+`QoderFileConfiguration` receives the prepared connection grant only during
+execution. Native `apiKey` contains that local bearer because ordinary Qoder
+launches do not inherit a HiRoute token environment variable. The target mode is
+0600. Status and reconfiguration use the artifact port’s private reader, which checks
+0600 on the same opened file descriptor; restoration may still remove an owned
+secret after a permission change. Public Operation payloads contain only the provider, endpoint, aliases and
+budgets. Protected restore records must never enter public diagnostics or journals.
+
+Qoder's provider supports fixed native authentication headers, not arbitrary
+headers. Its persistent provider therefore uses the explicit local base path
+`/_hiroute/qoder/v1`: standard bearer authenticates the current model grant on
+`responses` and `models`. This entry reuses Gateway publication, execution and
+receipts; it rejects unissued account tokens, run credentials and mixed headers.
+The ordinary `/v1/responses` entry retains its separate `X-HiRoute-Token` channel.
+Transient Worker and capability-probe settings still use `/v1` with their existing
+run/challenge authority. Do not replace this distinction with a global bearer
+fallback or a new proxy service.
+
+## Adjustment and recovery
+
+An existing provider cannot be adopted by matching its name. Reconfiguration
+requires the preceding Operation's authenticated restore record and unchanged
+owned provider semantics. Unrelated user edits survive adjustment and restoration.
+An untouched file returns to its exact previous bytes; a changed file loses only
+the owned provider member. A harmless empty `providers` container may remain to
+preserve user comments. Newly created, untouched files are removed on restoration.
+
+If `model.name` selects an alias being removed, Preview returns
+`qoder.default.in-use`. The user must select a different native default first.
+Keeping that alias while adjusting other routes or rotating the token is allowed.
+Foreign changes inside the owned provider return `qoder.native.fields`; no user
+value is included in that diagnostic.
+
+The daemon must bind installed model declarations to the exact settings Operation
+and grant, and apply the publication budget compatibility check. These static
+native declarations do not refresh themselves when a Plan changes. The pure
+`QoderTokenBudget` rule is domain-owned; `qoder_plan_token_budget` projects the
+exact compiled Plan, including all active candidate/protocol bounds and existing
+context/reasoning reservations. A positive compaction threshold is not a promise
+that every prompt or Skill fits.
+
+Backend ownership follows the existing settings transaction; start here when
+changing a model route or diagnosing a parked native write:
+
+| Behavior | Owner | Representative evidence |
+| --- | --- | --- |
+| Preview, independent facets and current installed declaration | [Qoder settings facts](../../../../daemon/src/control/runtime/settings_facts/qoder_model.rs) | Public configure / independent Restore in [settings journeys](../../../../daemon/src/control/runtime/settings_entry_qoder_model_tests.rs) |
+| Protected native file execution and original Operation binding | [Qoder native effects](../../../../daemon/src/control/runtime/native_qoder_model.rs) | Journal secrecy, permission drift and conditional restoration in the same journeys |
+| Installed budgets constrain publication admission and Install; parked tails retain Control ownership | [Budget and pending-operation guards](../../../../daemon/src/control/runtime/qoder_model_budget.rs) | Budget shrink rollback and exact parked-operation retry in the same journeys |
+| Retry the original authorized settings Operation | [Settings retry](../../../../daemon/src/control/runtime/settings_retry.rs) | A second mutation is refused until the original tail completes |
+| Real native session matched to Gateway receipts | [Qoder live checks](../../../../daemon/src/control/runtime/agent_live_check_qoder.rs) | [Ordinary startup product journey](../../../../daemon/tests/support/qoder_model_product.py), independent of Worker overlays |
+| Persist the verified client surface without rewriting earlier results | [Current surface storage](../../../../local-storage/src/control/surface_check_tests.rs), [surface migration](../../../../local-storage/src/migrations/agent_surface_checks_v25.rs) | Every supported native surface is written through the real repository port; production startup retains earlier raw rows and the key |
+
+## Representative checks
+
+[Native contract tests](../qoder_native_tests.rs) cover preserving native defaults
+and foreign providers, two selectable aliases, token rotation with unrelated edits,
+conditional restoration, selected-default removal refusal, foreign provider
+collision, and malformed/ambiguous JSON. [Plan budget tests](../qoder_budget_tests.rs)
+retain the mixed-route, unknown-output and reservation contracts.
+
+These tests do not prove native model calls. Product verification must launch the
+installed Qoder against the saved settings without a transient provider/token
+overlay, match its session identity to actual Gateway receipts, and preserve the
+independent collaboration facet. Login and account capability remain Qoder-owned.
diff --git a/crates/integrations/src/agents/qoder_native_effects.rs b/crates/integrations/src/agents/qoder_native_effects.rs
new file mode 100644
index 00000000..ef93cce9
--- /dev/null
+++ b/crates/integrations/src/agents/qoder_native_effects.rs
@@ -0,0 +1,215 @@
+//! Qoder's additional provider uses the existing protected Operation artifact lifecycle.
+use hiroute_domain::{
+ AgentAccessGrantMaterial, CanonicalDigest, ExternalEffectIntentV1, NativeAgentArtifactPort,
+ OperationId, OwnedEffectV1, PortError, PortErrorCode, PortResult, QoderAdditionalModelV1,
+};
+
+use super::{
+ QoderNativeError,
+ native_effects::replay,
+ qoder_native::{self, Restore},
+};
+
+/// Only the executor receives material; this input deliberately cannot be serialized or logged.
+pub struct QoderFileConfiguration<'a> {
+ pub expected_content: &'a CanonicalDigest,
+ pub provider_id: &'a str,
+ pub endpoint: &'a str,
+ pub models: &'a [QoderAdditionalModelV1],
+ pub local_grant: &'a AgentAccessGrantMaterial,
+}
+
+/// Preview is read-only and never requires bearer bytes. The protected previous intent proves
+/// ownership; an identifier found in an arbitrary user document does not.
+pub fn validate_qoder_configuration(
+ port: &dyn NativeAgentArtifactPort,
+ target: &str,
+ provider_id: &str,
+ endpoint: &str,
+ models: &[QoderAdditionalModelV1],
+ previous: Option<(&OperationId, &ExternalEffectIntentV1)>,
+) -> PortResult<()> {
+ let previous = previous
+ .map(|(operation, intent)| {
+ if intent.target() != target {
+ return Err(error(PortErrorCode::InvalidData, "qoder.previous.target"));
+ }
+ load(port, operation, intent)
+ })
+ .transpose()?;
+ let current = if previous.is_some() {
+ port.read_private_native_target(target)?
+ } else {
+ port.read_native_target(target)?
+ };
+ qoder_native::validate_configuration(
+ current.as_deref().map(Vec::as_slice),
+ provider_id,
+ endpoint,
+ models,
+ previous.as_ref(),
+ )
+ .map_err(fields_error)
+}
+
+pub fn validate_qoder_restoration(
+ port: &dyn NativeAgentArtifactPort,
+ target: &str,
+ original_operation: &OperationId,
+ original_intent: &ExternalEffectIntentV1,
+) -> PortResult<()> {
+ if original_intent.target() != target {
+ return Err(error(PortErrorCode::InvalidData, "qoder.original.target"));
+ }
+ let restore = load(port, original_operation, original_intent)?;
+ let current = port.read_native_target(target)?;
+ restore
+ .validate_restoration(current.as_deref().map(Vec::as_slice))
+ .map_err(fields_error)
+}
+
+pub fn qoder_native_configuration_is_applied(
+ port: &dyn NativeAgentArtifactPort,
+ operation: &OperationId,
+ intent: &ExternalEffectIntentV1,
+) -> PortResult<bool> {
+ let restore = load(port, operation, intent)?;
+ let current = match port.read_private_native_target(intent.target()) {
+ Ok(current) => current,
+ Err(error) if error.code == PortErrorCode::PermissionDenied => return Ok(false),
+ Err(error) => return Err(error),
+ };
+ // Malformed/edited user configuration is drift. A corrupt protected record is not softened.
+ Ok(restore
+ .applied(current.as_deref().map(Vec::as_slice))
+ .unwrap_or(false))
+}
+
+pub fn stage_qoder_configuration(
+ port: &dyn NativeAgentArtifactPort,
+ operation: &OperationId,
+ intent: &ExternalEffectIntentV1,
+ configuration: QoderFileConfiguration<'_>,
+) -> PortResult<OwnedEffectV1> {
+ stage(port, operation, intent, configuration, None)
+}
+
+pub fn stage_qoder_reconfiguration(
+ port: &dyn NativeAgentArtifactPort,
+ operation: &OperationId,
+ intent: &ExternalEffectIntentV1,
+ previous_operation: &OperationId,
+ previous_intent: &ExternalEffectIntentV1,
+ configuration: QoderFileConfiguration<'_>,
+) -> PortResult<OwnedEffectV1> {
+ validate_binding(operation, intent, previous_operation, previous_intent)?;
+ // Do not require an obsolete previous record for an already staged/applied replay.
+ if let Some(effect) = replay(port, operation, intent)? {
+ return Ok(effect);
+ }
+ let previous = load(port, previous_operation, previous_intent)?;
+ stage(port, operation, intent, configuration, Some(&previous))
+}
+
+fn stage(
+ port: &dyn NativeAgentArtifactPort,
+ operation: &OperationId,
+ intent: &ExternalEffectIntentV1,
+ configuration: QoderFileConfiguration<'_>,
+ previous: Option<&Restore>,
+) -> PortResult<OwnedEffectV1> {
+ if intent.desired_mode() != 0o600 {
+ return Err(error(PortErrorCode::InvalidData, "qoder.native.mode"));
+ }
+ if let Some(effect) = replay(port, operation, intent)? {
+ return Ok(effect);
+ }
+ let current = if previous.is_some() {
+ port.read_private_native_target(intent.target())?
+ } else {
+ port.read_native_target(intent.target())?
+ };
+ if CanonicalDigest::of_bytes(current.as_deref().map_or(&[], Vec::as_slice))
+ != *configuration.expected_content
+ {
+ return Err(error(PortErrorCode::Conflict, "qoder.preview.changed"));
+ }
+ let edit = qoder_native::configure(
+ current.as_deref().map(Vec::as_slice),
+ configuration.provider_id,
+ configuration.endpoint,
+ configuration.models,
+ configuration.local_grant,
+ previous,
+ )
+ .map_err(fields_error)?;
+ let record = edit
+ .restore
+ .encode()
+ .map_err(|_| error(PortErrorCode::InvalidData, "qoder.restore.encode"))?;
+ port.save_native_restore(operation, intent, &record)?;
+ port.stage_native_target(operation, intent, Some(&edit.bytes), true)
+}
+
+pub fn stage_qoder_restoration(
+ port: &dyn NativeAgentArtifactPort,
+ operation: &OperationId,
+ intent: &ExternalEffectIntentV1,
+ original_operation: &OperationId,
+ original_intent: &ExternalEffectIntentV1,
+) -> PortResult<OwnedEffectV1> {
+ validate_binding(operation, intent, original_operation, original_intent)?;
+ if intent.desired_mode() != 0o600 {
+ return Err(error(PortErrorCode::InvalidData, "qoder.native.mode"));
+ }
+ if let Some(effect) = replay(port, operation, intent)? {
+ return Ok(effect);
+ }
+ let restore = load(port, original_operation, original_intent)?;
+ let current = port.read_native_target(intent.target())?;
+ let restored = restore
+ .restore(current.as_deref().map(Vec::as_slice))
+ .map_err(fields_error)?;
+ port.stage_native_target(
+ operation,
+ intent,
+ restored.as_deref().map(Vec::as_slice),
+ true,
+ )
+}
+
+fn validate_binding(
+ operation: &OperationId,
+ intent: &ExternalEffectIntentV1,
+ previous_operation: &OperationId,
+ previous_intent: &ExternalEffectIntentV1,
+) -> PortResult<()> {
+ if operation == previous_operation || intent.target() != previous_intent.target() {
+ return Err(error(PortErrorCode::InvalidData, "qoder.previous.binding"));
+ }
+ Ok(())
+}
+
+fn load(
+ port: &dyn NativeAgentArtifactPort,
+ operation: &OperationId,
+ intent: &ExternalEffectIntentV1,
+) -> PortResult<Restore> {
+ let bytes = port
+ .load_native_restore(operation, intent)?
+ .ok_or_else(|| error(PortErrorCode::NotFound, "qoder.restore.record"))?;
+ Restore::decode(&bytes).map_err(|_| error(PortErrorCode::Corrupt, "qoder.restore.record"))
+}
+
+fn fields_error(error: QoderNativeError) -> PortError {
+ let context = if error.stage == "default in use" {
+ "qoder.default.in-use"
+ } else {
+ "qoder.native.fields"
+ };
+ PortError::new(PortErrorCode::Conflict, context)
+}
+
+fn error(code: PortErrorCode, context: &'static str) -> PortError {
+ PortError::new(code, context)
+}
diff --git a/crates/integrations/src/agents/qoder_native_tests.rs b/crates/integrations/src/agents/qoder_native_tests.rs
new file mode 100644
index 00000000..c5c2d15e
--- /dev/null
+++ b/crates/integrations/src/agents/qoder_native_tests.rs
@@ -0,0 +1,329 @@
+use super::*;
+use serde_json::json;
+
+const PROVIDER: &str =
+ "hiroute-main-0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
+const ENDPOINT: &str = "http://127.0.0.1:4321/_hiroute/qoder/v1";
+
+fn models() -> Vec<QoderAdditionalModelV1> {
+ ["plan-branch-cheap", "hiroute/0011223344556677"]
+ .into_iter()
+ .map(|alias| QoderAdditionalModelV1 {
+ alias: alias.into(),
+ context_window_tokens: 32_768,
+ max_output_tokens: 4096,
+ })
+ .collect()
+}
+
+fn token(byte: u8) -> AgentAccessGrantMaterial {
+ AgentAccessGrantMaterial::from_csprng_entropy([byte; 32])
+}
+
+fn install(bytes: Option<&[u8]>) -> Edit {
+ configure(bytes, PROVIDER, ENDPOINT, &models(), &token(3), None).unwrap()
+}
+
+fn value(bytes: &[u8]) -> Value {
+ Document::parse(bytes).unwrap().root.value
+}
+
+#[test]
+fn two_additional_routes_keep_native_default_extensions_and_foreign_provider_bytes() {
+ let original = br#"{
+// user's preferred native model
+"model": { "name": "auto", "reasoningEffort": "high" },
+"providers": { "user-models": {"apiKey":"native-secret", "unknown": [1,2]} },
+"hooks":{"SessionEnd":[]},"mcpServers":{"local":{"command":"my-tool"}},
+"unknown": "keep // this string"
+}"#;
+ let edit = install(Some(original));
+ let configured = value(&edit.bytes);
+ let before = value(original);
+ for key in ["model", "hooks", "mcpServers", "unknown"] {
+ assert_eq!(configured[key], before[key]);
+ }
+ assert_eq!(
+ configured["providers"]["user-models"],
+ before["providers"]["user-models"]
+ );
+ let text = std::str::from_utf8(&edit.bytes).unwrap();
+ assert!(text.contains("// user's preferred native model"));
+ assert!(text.contains("\"user-models\": {\"apiKey\":\"native-secret\", \"unknown\": [1,2]}"));
+ let provider = &configured["providers"][PROVIDER];
+ assert_eq!(provider["protocol"], "openai-responses");
+ assert_eq!(provider["baseUrl"], ENDPOINT);
+ assert_eq!(
+ provider["apiKey"],
+ std::str::from_utf8(token(3).expose()).unwrap()
+ );
+ let native_models = provider["models"].as_array().unwrap();
+ assert_eq!(native_models.len(), models().len());
+ for (native, model) in native_models.iter().zip(models()) {
+ assert_eq!(native["model"], model.alias);
+ assert_eq!(native["contextWindow"], 32_768);
+ assert_eq!(native["maxOutputTokens"], 4096);
+ }
+ assert!(provider.get("model").is_none());
+ assert!(provider.get("routing").is_none());
+ assert!(configured.get("modelConfigs").is_none());
+ assert_eq!(
+ edit.restore
+ .restore(Some(&edit.bytes))
+ .unwrap()
+ .unwrap()
+ .as_slice(),
+ original
+ );
+}
+
+#[test]
+fn unrelated_edits_survive_rotation_and_final_restore_without_adopting_owned_drift() {
+ let original = br#"{"model":{"name":"auto"},"unrelated":1}"#;
+ let first = install(Some(original));
+ let edited = std::str::from_utf8(&first.bytes)
+ .unwrap()
+ .replace("\"unrelated\":1", "\"unrelated\":2 /* user changed this */");
+ assert!(first.restore.applied(Some(edited.as_bytes())).unwrap());
+ let rotated = configure(
+ Some(edited.as_bytes()),
+ PROVIDER,
+ ENDPOINT,
+ &models()[..1],
+ &token(4),
+ Some(&first.restore),
+ )
+ .unwrap();
+ assert_ne!(
+ value(&rotated.bytes)["providers"][PROVIDER]["apiKey"],
+ value(&first.bytes)["providers"][PROVIDER]["apiKey"]
+ );
+ let restored = rotated
+ .restore
+ .restore(Some(&rotated.bytes))
+ .unwrap()
+ .unwrap();
+ assert_eq!(value(&restored)["unrelated"], 2);
+ assert!(
+ std::str::from_utf8(&restored)
+ .unwrap()
+ .contains("/* user changed this */")
+ );
+ assert!(value(&restored)["providers"].get(PROVIDER).is_none());
+ // A user edit within the owned node remains a conflict even if all declared routes survive.
+ let mut drift = value(&rotated.bytes);
+ drift["providers"][PROVIDER]["routing"] = json!({"compact":"user-selected"});
+ let drift = serde_json::to_vec(&drift).unwrap();
+ assert!(!rotated.restore.applied(Some(&drift)).unwrap());
+ assert!(rotated.restore.restore(Some(&drift)).is_err());
+ assert!(
+ configure(
+ Some(&drift),
+ PROVIDER,
+ ENDPOINT,
+ &models(),
+ &token(5),
+ Some(&rotated.restore)
+ )
+ .is_err()
+ );
+}
+
+#[test]
+fn removing_selected_native_default_requires_user_switch_but_retaining_it_is_allowed() {
+ let first = install(Some(br#"{"model":{"name":"auto"}}"#));
+ let mut current = value(&first.bytes);
+ current["model"]["name"] = format!("{PROVIDER}/plan-branch-cheap").into();
+ let current = serde_json::to_vec(&current).unwrap();
+ assert_eq!(
+ first
+ .restore
+ .validate_restoration(Some(&current))
+ .unwrap_err()
+ .stage,
+ "default in use"
+ );
+ assert_eq!(
+ validate_configuration(
+ Some(&current),
+ PROVIDER,
+ ENDPOINT,
+ &models()[1..],
+ Some(&first.restore)
+ )
+ .unwrap_err()
+ .stage,
+ "default in use"
+ );
+ let adjusted = configure(
+ Some(&current),
+ PROVIDER,
+ ENDPOINT,
+ &models()[..1],
+ &token(4),
+ Some(&first.restore),
+ )
+ .unwrap();
+ assert_eq!(
+ value(&adjusted.bytes)["model"]["name"],
+ format!("{PROVIDER}/plan-branch-cheap")
+ );
+ let mut switched = value(&adjusted.bytes);
+ switched["model"]["name"] = "user-provider/user-model".into();
+ let restored = adjusted
+ .restore
+ .restore(Some(&serde_json::to_vec(&switched).unwrap()))
+ .unwrap()
+ .unwrap();
+ assert_eq!(
+ value(&restored)["model"]["name"],
+ "user-provider/user-model"
+ );
+}
+
+#[test]
+fn existing_provider_is_never_claimed_by_name_and_missing_original_is_removed_exactly() {
+ let first = install(None);
+ assert!(
+ configure(
+ Some(&first.bytes),
+ PROVIDER,
+ ENDPOINT,
+ &models(),
+ &token(3),
+ None
+ )
+ .is_err()
+ );
+ assert!(first.restore.restore(Some(&first.bytes)).unwrap().is_none());
+ assert!(first.restore.restore(None).unwrap().is_none());
+ let protected = first.restore.encode().unwrap();
+ let recovered = Restore::decode(&protected).unwrap();
+ assert!(recovered.applied(Some(&first.bytes)).unwrap());
+ // Root-level credentials/config cannot be smuggled into the protected ownership baseline.
+ let mut invalid = recovered;
+ invalid.original_exists = true;
+ invalid.original = first.bytes.to_vec();
+ assert!(Restore::decode(&invalid.encode().unwrap()).is_err());
+}
+
+#[test]
+fn restore_only_removes_owned_member_at_every_position_preserving_other_jsonc_bytes() {
+ for original in [
+ br#"{"providers":{},"note":"keep"}"#.as_slice(),
+ br#"{/* leading */"providers":{"a":{"v":1},"z":{"v":2}},"note":"keep"}"#,
+ ] {
+ let first = install(Some(original));
+ let mut current = value(&first.bytes);
+ current["unrelated"] = true.into();
+ let rendered = serde_json::to_vec_pretty(&current).unwrap();
+ let restored = first.restore.restore(Some(&rendered)).unwrap().unwrap();
+ let mut expected = current;
+ expected["providers"]
+ .as_object_mut()
+ .unwrap()
+ .remove(PROVIDER);
+ assert_eq!(value(&restored), expected);
+ }
+ // A changed file must take the conditional removal path, preserving the complete foreign
+ // byte sequence even when the user reordered the owned provider among other members.
+ let first = install(Some(br#"{"model":{"name":"auto"},"providers":{}}"#));
+ let provider = serde_json::to_string(&value(&first.bytes)["providers"][PROVIDER]).unwrap();
+ let owned = format!("\"{PROVIDER}\" : {provider}");
+ for (members, expected) in [
+ (
+ " $OWNED /* own */ ,\n \"a\" : 1 ,\t\"z\":2 ",
+ " /* own */ \n \"a\" : 1 ,\t\"z\":2 ",
+ ),
+ (
+ " \"a\" : 1 , /* middle */ $OWNED ,\t\"z\":2 ",
+ " \"a\" : 1 , /* middle */ \t\"z\":2 ",
+ ),
+ (
+ " \"a\" : 1 ,\t\"z\":2 , /* last */ $OWNED /* end */ ",
+ " \"a\" : 1 ,\t\"z\":2 /* last */ /* end */ ",
+ ),
+ ] {
+ let wrap = |members: &str| {
+ format!("{{\r\n \"providers\" : {{{members}}}, // user\r\n \"outside\":true\r\n}}")
+ };
+ let current = wrap(&members.replace("$OWNED", &owned));
+ assert_ne!(
+ CanonicalDigest::of_bytes(current.as_bytes()),
+ first.restore.rendered_digest
+ );
+ let restored = first
+ .restore
+ .restore(Some(current.as_bytes()))
+ .unwrap()
+ .unwrap();
+ assert_eq!(restored.as_slice(), wrap(expected).as_bytes());
+ }
+ // The parser also accepts comments after the last value before its comma.
+ let source = br#"{"a":1/*a*/,"b":2/*b*/,"c":3/*c*/}"#;
+ for key in ["a", "b", "c"] {
+ let doc = Document::parse(source).unwrap();
+ let edited = doc.edit(&doc.root, key, None).unwrap();
+ assert!(value(&edited).get(key).is_none());
+ assert!(std::str::from_utf8(&edited).unwrap().contains("/*b*/"));
+ }
+}
+
+#[test]
+fn ambiguous_or_malformed_documents_fail_without_normalizing_foreign_settings() {
+ for bytes in [
+ br#"{"providers":{},"providers":{}}"#.as_slice(),
+ br#"{"foreign":{"same":1,"same":2}}"#,
+ br#"{"foreign":{"same":1,"\u0073ame":2}}"#,
+ br#"{"foreign":[1,]}"#,
+ br#"{"providers":{ /* unfinished}"#,
+ br#"{"providers":[]}"#,
+ br#"{"model":{"name":"auto"}} trailing"#,
+ ] {
+ assert!(configure(Some(bytes), PROVIDER, ENDPOINT, &models(), &token(3), None).is_err());
+ }
+ for separator in ["\r", "\u{2028}", "\u{2029}"] {
+ let ambiguous = format!(
+ "{{\"model\":{{\"name\":\"auto\"}} // c{separator},\"providers\":{{\"user\":{{}}}}\n}}"
+ );
+ assert!(
+ configure(
+ Some(ambiguous.as_bytes()),
+ PROVIDER,
+ ENDPOINT,
+ &models(),
+ &token(3),
+ None
+ )
+ .is_err()
+ );
+ }
+ let unicode = "\u{feff}{\"标签\":\"值 \\\" // /*\", /* 注释 */ \"providers\":{}}";
+ let edit = install(Some(unicode.as_bytes()));
+ assert_eq!(
+ edit.restore
+ .restore(Some(&edit.bytes))
+ .unwrap()
+ .unwrap()
+ .as_slice(),
+ unicode.as_bytes()
+ );
+ let mut bounded = b"{}".to_vec();
+ bounded.resize(LIMIT, b' ');
+ assert!(Document::parse(&bounded).is_ok());
+ bounded.push(b' ');
+ assert!(Document::parse(&bounded).is_err());
+}
+
+#[test]
+fn declarations_reject_unknown_budget_duplicate_alias_and_unowned_namespace() {
+ let mut selected = models();
+ selected.push(selected[0].clone());
+ assert!(validate_declaration(PROVIDER, ENDPOINT, &selected).is_err());
+ assert!(validate_declaration("hiroute-worker-123", ENDPOINT, &models()).is_err());
+ assert!(validate_declaration(PROVIDER, "https://external.example/v1", &models()).is_err());
+ selected = models();
+ selected[0].max_output_tokens = 32_000; // the exact 32K/32K zero-threshold regression
+ assert!(validate_declaration(PROVIDER, ENDPOINT, &selected).is_err());
+ assert!(validate_declaration(PROVIDER, ENDPOINT, &[]).is_err());
+}
diff --git a/crates/integrations/src/agents/qoder_probe.rs b/crates/integrations/src/agents/qoder_probe.rs
new file mode 100644
index 00000000..c7fe4bfe
--- /dev/null
+++ b/crates/integrations/src/agents/qoder_probe.rs
@@ -0,0 +1,619 @@
+//! Explicit collaboration checks in the selected, normally logged-in Qoder context.
+//! Auth is read only by Qoder. HiRoute owns the private workspace and local challenge, not HOME.
+use std::fs::{self, File, OpenOptions};
+use std::io::{Read, Write};
+use std::os::unix::fs::{DirBuilderExt, MetadataExt, OpenOptionsExt, PermissionsExt};
+use std::os::unix::process::CommandExt;
+use std::path::{Path, PathBuf};
+use std::process::{Command, Stdio};
+use std::time::{Duration, Instant};
+
+use super::native_probe_process::{NativeProbeProcess, read_bounded};
+use super::qoder::{
+ QoderNativeContext, QoderNativeError, QoderTransientRouteInput, qoder_error,
+ render_qoder_transient_route,
+};
+use hiroute_domain::{
+ AgentCapability, CanonicalDigest, CapabilityState, SupportedAgentInstallationV1,
+};
+use serde_json::Value;
+
+#[path = "qoder_probe_http.rs"]
+mod http;
+
+const CONTRACT: &str = "hiroute.qoder-borrowed-context-collaboration/v1";
+const MARKER: &str = "hiroute-local-challenge-no-authority";
+const MODEL: &str = "hiroute/collaboration-probe";
+
+#[derive(Clone, Debug, Eq, PartialEq)]
+pub enum QoderCollaborationProbeTarget {
+ PreinstallCapability,
+ InstalledUserSkill { expected_content: CanonicalDigest },
+}
+
+#[derive(Clone)]
+pub struct QoderCollaborationEvidence {
+ executable: PathBuf,
+ cli: PathBuf,
+ dependencies: CanonicalDigest,
+ target: QoderCollaborationProbeTarget,
+ proof: CanonicalDigest,
+ observed: Instant,
+ observed_at: u64,
+}
+
+/// A new explicit attempt invalidates old success before discovery or launch can fail.
+#[derive(Default)]
+pub(super) struct QoderProofCache {
+ generation: u64,
+ pub(super) evidence: Option<QoderCollaborationEvidence>,
+}
+
+impl QoderProofCache {
+ pub(super) fn begin(&mut self) -> Result<u64, QoderNativeError> {
+ self.evidence = None;
+ self.generation = self
+ .generation
+ .checked_add(1)
+ .ok_or_else(|| qoder_error("evidence generation"))?;
+ Ok(self.generation)
+ }
+ pub(super) fn finish(
+ &mut self,
+ generation: u64,
+ evidence: QoderCollaborationEvidence,
+ ) -> Result<(), QoderNativeError> {
+ if generation != self.generation {
+ return Err(qoder_error("native check superseded"));
+ }
+ self.evidence = Some(evidence);
+ Ok(())
+ }
+}
+
+impl QoderCollaborationEvidence {
+ #[cfg(test)]
+ pub(crate) fn fixture(
+ executable: &Path,
+ context: &QoderNativeContext,
+ cli: &Path,
+ target: QoderCollaborationProbeTarget,
+ ) -> Self {
+ Self {
+ executable: executable.to_owned(),
+ cli: cli.to_owned(),
+ dependencies: dependencies(executable, context, cli, &target).unwrap(),
+ target,
+ proof: CanonicalDigest::of_bytes(b"fixture"),
+ observed: Instant::now(),
+ observed_at: 1,
+ }
+ }
+ fn current(&self, executable: &Path, context: &QoderNativeContext) -> bool {
+ self.observed.elapsed() <= Duration::from_secs(300)
+ && executable == self.executable
+ && dependencies(executable, context, &self.cli, &self.target)
+ .ok()
+ .as_ref()
+ == Some(&self.dependencies)
+ }
+
+ pub(super) fn installed_user_verified(
+ &self,
+ executable: &Path,
+ context: &QoderNativeContext,
+ ) -> bool {
+ matches!(
+ self.target,
+ QoderCollaborationProbeTarget::InstalledUserSkill { .. }
+ ) && self.current(executable, context)
+ }
+
+ pub(super) fn attach(
+ &self,
+ executable: &Path,
+ context: &QoderNativeContext,
+ installation: &mut SupportedAgentInstallationV1,
+ ) {
+ if !self.current(executable, context) {
+ return;
+ }
+ installation.observation_digest = CanonicalDigest::of(&(
+ CONTRACT,
+ &installation.observation_digest,
+ &self.proof,
+ self.observed_at,
+ ))
+ .expect("bounded native proof");
+ for proof in &mut installation.capability_evidence {
+ proof.dependency_digest = installation.observation_digest.clone();
+ if matches!(
+ proof.capability,
+ AgentCapability::SkillLoading | AgentCapability::TrustedCliExecution
+ ) {
+ proof.state = CapabilityState::Proven;
+ proof.reason = None;
+ proof.adapter_contract = CONTRACT.into();
+ proof.observed_at_unix_ms = self.observed_at;
+ }
+ }
+ }
+}
+
+pub struct QoderCollaborationProbe;
+
+impl QoderCollaborationProbe {
+ pub fn run(
+ executable: &Path,
+ context: &QoderNativeContext,
+ cli: &Path,
+ target: QoderCollaborationProbeTarget,
+ ) -> Result<QoderCollaborationEvidence, QoderNativeError> {
+ let executable = super::executable::resolve(executable)
+ .map_err(|_| qoder_error("selected executable"))?
+ .ok_or_else(|| qoder_error("selected executable"))?;
+ let cli = super::executable::resolve(cli)
+ .map_err(|_| qoder_error("trusted CLI"))?
+ .ok_or_else(|| qoder_error("trusted CLI"))?;
+ let before = dependencies(&executable, context, &cli, &target)?;
+ let settings_before = settings_receipt(context)?;
+ let root = tempfile::Builder::new()
+ .prefix("hiroute-qoder-check-")
+ .permissions(fs::Permissions::from_mode(0o700))
+ .tempdir()
+ .map_err(|_| qoder_error("private workspace"))?;
+ let root_path =
+ fs::canonicalize(root.path()).map_err(|_| qoder_error("private workspace"))?;
+ let workspace = root_path.join("workspace");
+ let temporary = root_path.join("tmp");
+ for path in [&workspace, &temporary] {
+ private_dir(path)?;
+ }
+ let (skill_path, content, sources) = match &target {
+ QoderCollaborationProbeTarget::PreinstallCapability => {
+ let mut entropy = [0u8; 16];
+ getrandom::fill(&mut entropy).map_err(|_| qoder_error("challenge entropy"))?;
+ let suffix = entropy
+ .iter()
+ .map(|byte| format!("{byte:02x}"))
+ .collect::<String>();
+ let path = workspace.join(format!(".qoder/skills/hiroute-probe-{suffix}/SKILL.md"));
+ let text = format!(
+ "---\nname: hiroute-probe-{suffix}\ndescription: HiRoute native discovery {suffix}\n---\n\nPrivate content receipt: {suffix}\nFollow only this local compatibility check.\n"
+ );
+ fs::DirBuilder::new()
+ .recursive(true)
+ .mode(0o700)
+ .create(path.parent().unwrap())
+ .map_err(|_| qoder_error("private Skill"))?;
+ write_private(&path, text.as_bytes())?;
+ (path, text, "user,project,local")
+ }
+ QoderCollaborationProbeTarget::InstalledUserSkill { expected_content } => {
+ let path = context.skill_target();
+ let content = confirmed_skill(&path, expected_content)?;
+ (path, content, "user")
+ }
+ };
+ let skill_directory = fs::canonicalize(
+ skill_path
+ .parent()
+ .ok_or_else(|| qoder_error("Skill target"))?,
+ )
+ .map_err(|_| qoder_error("Skill target"))?;
+ let skill_name = skill_directory
+ .file_name()
+ .and_then(|name| name.to_str())
+ .ok_or_else(|| qoder_error("Skill target encoding"))?
+ .to_owned();
+ let body = skill_body(&content)?;
+ let expected_cli = cli_baseline(&cli, &root_path)?;
+ let command = format!("{} schema list --output json", shell_quote(&cli)?);
+ let mut challenge = http::Challenge {
+ skill_name,
+ skill_directory: skill_directory
+ .to_str()
+ .ok_or_else(|| qoder_error("Skill target encoding"))?
+ .into(),
+ skill_body: body,
+ command,
+ expected_cli,
+ step: 0,
+ };
+ let listener =
+ std::net::TcpListener::bind("127.0.0.1:0").map_err(|_| qoder_error("loopback bind"))?;
+ listener
+ .set_nonblocking(true)
+ .map_err(|_| qoder_error("loopback mode"))?;
+ let endpoint = format!(
+ "http://{}/v1",
+ listener
+ .local_addr()
+ .map_err(|_| qoder_error("loopback address"))?
+ );
+ let route = render_qoder_transient_route(QoderTransientRouteInput {
+ provider_id: "hiroute-native-probe",
+ endpoint: &endpoint,
+ alias: MODEL,
+ credential_env: "HIROUTE_QODER_PROBE_TOKEN",
+ context_window_tokens: None,
+ max_output_tokens: 2048,
+ })?;
+ let settings = root_path.join("settings.json");
+ write_private(
+ &settings,
+ &serde_json::to_vec(&route.settings).map_err(|_| qoder_error("transient settings"))?,
+ )?;
+ let output = private_file(&root_path.join("output.private"))?;
+ let observer = output
+ .try_clone()
+ .map_err(|_| qoder_error("private output"))?;
+ let mut command = Command::new(&executable);
+ command
+ .args(["--cwd"])
+ .arg(&workspace)
+ .arg("--config-dir")
+ .arg(&context.config_root)
+ .args(["--setting-sources", sources, "--settings"])
+ .arg(&settings)
+ .args([
+ "--model",
+ &route.native_model_id,
+ "--print",
+ "--no-session-persistence",
+ "--output-format",
+ "stream-json",
+ "--strict-mcp-config",
+ "--mcp-config",
+ "{\"mcpServers\":{}}",
+ "--tools",
+ "Skill,Read,Bash",
+ "--allowed-tools",
+ "Skill,Bash",
+ "--permission-mode",
+ "dont_ask",
+ "--max-model-request-retries",
+ "0",
+ "--max-output-tokens",
+ "128",
+ "-p",
+ "Complete the local compatibility check; follow the local tool requests.",
+ ])
+ .env_clear()
+ .env("HOME", &context.home)
+ .env("QODER_CONFIG_DIR", &context.config_root)
+ .env("TMPDIR", &temporary)
+ .env("PATH", "/usr/local/bin:/usr/bin:/bin:/opt/homebrew/bin")
+ .env("HIROUTE_QODER_PROBE_TOKEN", MARKER)
+ .stdin(Stdio::null())
+ .stdout(Stdio::from(output))
+ .stderr(Stdio::null())
+ .current_dir(&workspace)
+ .process_group(0);
+ let mut child =
+ NativeProbeProcess::new(command.spawn().map_err(|_| qoder_error("native launch"))?);
+ let started = Instant::now();
+ let status = loop {
+ if started.elapsed() > Duration::from_secs(45) {
+ return Err(qoder_error("native check deadline"));
+ }
+ if observer
+ .metadata()
+ .map_err(|_| qoder_error("private output"))?
+ .len()
+ > 512 * 1024
+ {
+ return Err(qoder_error("native output bound"));
+ }
+ match listener.accept() {
+ Ok((mut stream, _)) => {
+ http::serve(&mut stream, MARKER, MODEL, &mut challenge).map_err(qoder_error)?
+ }
+ Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {}
+ Err(_) => return Err(qoder_error("loopback accept")),
+ }
+ if let Some(status) = child.observe().map_err(|_| qoder_error("native wait"))? {
+ break status;
+ }
+ std::thread::sleep(Duration::from_millis(10));
+ };
+ child
+ .stop()
+ .map_err(|_| qoder_error("native process scope"))?;
+ let output = read_bounded(&root_path.join("output.private"), 512 * 1024)
+ .map_err(|_| qoder_error("native output bound"))?;
+ let result = output
+ .split(|byte| *byte == b'\n')
+ .filter_map(|line| serde_json::from_slice::<Value>(line).ok())
+ .find(|value| value["type"] == "result");
+ if !status
+ || !challenge.complete()
+ || result
+ .as_ref()
+ .is_none_or(|result| result["is_error"] != false)
+ {
+ let login = result.as_ref().is_some_and(|value| {
+ let text = value.to_string().to_ascii_lowercase();
+ text.contains("authentication") || text.contains("login") || text.contains("log in")
+ });
+ return Err(qoder_error(if login {
+ "native login required"
+ } else {
+ "native collaboration execution"
+ }));
+ }
+ if before != dependencies(&executable, context, &cli, &target)?
+ || settings_before != settings_receipt(context)?
+ {
+ return Err(qoder_error("native context changed"));
+ }
+ let phase = match target {
+ QoderCollaborationProbeTarget::PreinstallCapability => "preinstall",
+ QoderCollaborationProbeTarget::InstalledUserSkill { .. } => "installed-user",
+ };
+ let proof = CanonicalDigest::of(&(
+ CONTRACT,
+ "borrowed-logged-in-context",
+ phase,
+ &before,
+ &skill_path,
+ CanonicalDigest::of_bytes(content.as_bytes()),
+ ))
+ .map_err(|_| qoder_error("evidence digest"))?;
+ Ok(QoderCollaborationEvidence {
+ executable,
+ cli,
+ dependencies: before,
+ target,
+ proof,
+ observed: Instant::now(),
+ observed_at: super::native_ingress_probe::now(),
+ })
+ }
+}
+
+fn confirmed_skill(path: &Path, expected: &CanonicalDigest) -> Result<String, QoderNativeError> {
+ let metadata =
+ fs::symlink_metadata(path).map_err(|_| qoder_error("installed user Skill missing"))?;
+ if !metadata.is_file() || metadata.file_type().is_symlink() || metadata.len() > 128 * 1024 {
+ return Err(qoder_error("installed user Skill target"));
+ }
+ let bytes =
+ read_bounded(path, 128 * 1024).map_err(|_| qoder_error("installed user Skill read"))?;
+ if &CanonicalDigest::of_bytes(&bytes) != expected {
+ return Err(qoder_error("installed user Skill changed"));
+ }
+ std::str::from_utf8(&bytes)
+ .map(str::to_owned)
+ .map_err(|_| qoder_error("installed user Skill encoding"))
+}
+
+fn skill_body(content: &str) -> Result<String, QoderNativeError> {
+ content
+ .strip_prefix("---\n")
+ .and_then(|text| text.split_once("\n---\n"))
+ .map(|(_, body)| body.trim().to_owned())
+ .filter(|body| !body.is_empty())
+ .ok_or_else(|| qoder_error("Skill front matter"))
+}
+
+fn dependencies(
+ executable: &Path,
+ context: &QoderNativeContext,
+ cli: &Path,
+ target: &QoderCollaborationProbeTarget,
+) -> Result<CanonicalDigest, QoderNativeError> {
+ let binary = super::native_ingress_probe::binary_identity(executable)
+ .map_err(|_| qoder_error("native executable identity"))?;
+ let cli = super::native_ingress_probe::binary_identity(cli)
+ .map_err(|_| qoder_error("trusted CLI identity"))?;
+ let root_identity = |path: &Path| -> Result<_, QoderNativeError> {
+ let path = fs::canonicalize(path).map_err(|_| qoder_error("selected native context"))?;
+ let m = fs::metadata(&path).map_err(|_| qoder_error("selected native context"))?;
+ if !m.is_dir() {
+ return Err(qoder_error("selected native context"));
+ }
+ Ok((path, m.dev(), m.ino(), m.uid(), m.gid(), m.mode()))
+ };
+ let settings = match fs::symlink_metadata(context.config_root.join("settings.json")) {
+ Ok(m) => Some((
+ m.dev(),
+ m.ino(),
+ m.mode(),
+ m.len(),
+ m.mtime(),
+ m.mtime_nsec(),
+ m.ctime(),
+ m.ctime_nsec(),
+ )),
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
+ Err(_) => return Err(qoder_error("native settings metadata")),
+ };
+ let content = match target {
+ QoderCollaborationProbeTarget::PreinstallCapability => None,
+ QoderCollaborationProbeTarget::InstalledUserSkill { expected_content } => {
+ confirmed_skill(&context.skill_target(), expected_content)?;
+ Some(expected_content)
+ }
+ };
+ CanonicalDigest::of(&(
+ CONTRACT,
+ root_identity(&context.home)?,
+ root_identity(&context.config_root)?,
+ settings,
+ binary,
+ cli,
+ context.skill_target(),
+ content,
+ ))
+ .map_err(|_| qoder_error("native context identity"))
+}
+
+fn settings_receipt(
+ context: &QoderNativeContext,
+) -> Result<Option<CanonicalDigest>, QoderNativeError> {
+ let path = context.config_root.join("settings.json");
+ let metadata = match fs::metadata(&path) {
+ Ok(value) => value,
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
+ Err(_) => return Err(qoder_error("native settings receipt")),
+ };
+ if !metadata.is_file() || metadata.len() > 1024 * 1024 {
+ return Err(qoder_error("native settings bound"));
+ }
+ let mut bytes = zeroize::Zeroizing::new(Vec::new());
+ File::open(path)
+ .and_then(|file| file.take(1024 * 1024 + 1).read_to_end(&mut bytes))
+ .map_err(|_| qoder_error("native settings receipt"))?;
+ if bytes.len() > 1024 * 1024 {
+ return Err(qoder_error("native settings bound"));
+ }
+ Ok(Some(CanonicalDigest::of_bytes(&bytes)))
+}
+
+fn private_dir(path: &Path) -> Result<(), QoderNativeError> {
+ fs::DirBuilder::new()
+ .mode(0o700)
+ .create(path)
+ .map_err(|_| qoder_error("private directory"))
+}
+fn private_file(path: &Path) -> Result<File, QoderNativeError> {
+ OpenOptions::new()
+ .create_new(true)
+ .read(true)
+ .write(true)
+ .mode(0o600)
+ .open(path)
+ .map_err(|_| qoder_error("private file"))
+}
+fn write_private(path: &Path, bytes: &[u8]) -> Result<(), QoderNativeError> {
+ private_file(path)?
+ .write_all(bytes)
+ .map_err(|_| qoder_error("private file"))
+}
+fn shell_quote(path: &Path) -> Result<String, QoderNativeError> {
+ Ok(format!(
+ "'{}'",
+ path.to_str()
+ .ok_or_else(|| qoder_error("trusted CLI path"))?
+ .replace('\'', "'\\''")
+ ))
+}
+
+fn cli_baseline(cli: &Path, root: &Path) -> Result<String, QoderNativeError> {
+ let output = private_file(&root.join("cli.private"))?;
+ let observer = output
+ .try_clone()
+ .map_err(|_| qoder_error("trusted CLI baseline"))?;
+ let mut child = NativeProbeProcess::new(
+ Command::new(cli)
+ .args(["schema", "list", "--output", "json"])
+ .env_clear()
+ .env("HOME", root)
+ .env("PATH", "/usr/bin:/bin")
+ .stdin(Stdio::null())
+ .stdout(output)
+ .stderr(Stdio::null())
+ .process_group(0)
+ .spawn()
+ .map_err(|_| qoder_error("trusted CLI baseline"))?,
+ );
+ let start = Instant::now();
+ loop {
+ if start.elapsed() > Duration::from_secs(10)
+ || observer
+ .metadata()
+ .map_err(|_| qoder_error("trusted CLI output"))?
+ .len()
+ > 128 * 1024
+ {
+ return Err(qoder_error("trusted CLI bound"));
+ }
+ if let Some(status) = child
+ .observe()
+ .map_err(|_| qoder_error("trusted CLI wait"))?
+ {
+ if !status {
+ return Err(qoder_error("trusted CLI baseline"));
+ }
+ break;
+ }
+ std::thread::sleep(Duration::from_millis(10));
+ }
+ child
+ .stop()
+ .map_err(|_| qoder_error("trusted CLI process scope"))?;
+ let bytes = read_bounded(&root.join("cli.private"), 128 * 1024)
+ .map_err(|_| qoder_error("trusted CLI output"))?;
+ let text = std::str::from_utf8(&bytes).map_err(|_| qoder_error("trusted CLI output"))?;
+ let body: Value =
+ serde_json::from_str(text).map_err(|_| qoder_error("trusted CLI contract"))?;
+ if body["status"] != "succeeded"
+ || !body["data"]["commands"].as_array().is_some_and(|commands| {
+ commands
+ .iter()
+ .any(|command| command["command_id"] == "schema.list")
+ })
+ {
+ return Err(qoder_error("trusted CLI contract"));
+ }
+ Ok(text.trim().to_owned())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn older_completion_cannot_replace_a_newer_explicit_check() {
+ let mut cache = QoderProofCache::default();
+ let older = cache.begin().unwrap();
+ let newer = cache.begin().unwrap();
+ let evidence = QoderCollaborationEvidence {
+ executable: "/fixture".into(),
+ cli: "/fixture-cli".into(),
+ dependencies: CanonicalDigest::of_bytes(b"fixture"),
+ target: QoderCollaborationProbeTarget::PreinstallCapability,
+ proof: CanonicalDigest::of_bytes(b"fixture"),
+ observed: Instant::now(),
+ observed_at: 1,
+ };
+ cache.finish(newer, evidence.clone()).unwrap();
+ assert!(cache.finish(older, evidence).is_err());
+ assert!(cache.evidence.is_some());
+ cache.begin().unwrap();
+ assert!(
+ cache.evidence.is_none(),
+ "a failed new attempt must not reuse prior success"
+ );
+ }
+
+ #[test]
+ fn installed_skill_drift_is_not_an_installation_or_proof() {
+ let root = tempfile::tempdir().unwrap();
+ let path = root.path().join("SKILL.md");
+ fs::write(&path, b"confirmed").unwrap();
+ let digest = CanonicalDigest::of_bytes(b"confirmed");
+ assert!(confirmed_skill(&path, &digest).is_ok());
+ fs::write(&path, b"changed").unwrap();
+ assert!(confirmed_skill(&path, &digest).is_err());
+ }
+
+ #[test]
+ #[ignore = "requires explicitly selected normally logged-in Qoder context and trusted HiRoute CLI"]
+ fn real_qoder_discovers_skill_and_runs_read_only_cli_in_selected_context() {
+ let path = |key| PathBuf::from(std::env::var_os(key).expect("explicit native check input"));
+ let context = QoderNativeContext::from_selected(
+ &path("HIROUTE_NATIVE_QODER_HOME"),
+ Some(&path("HIROUTE_NATIVE_QODER_CONFIG")),
+ )
+ .unwrap();
+ QoderCollaborationProbe::run(
+ &path("HIROUTE_NATIVE_QODER"),
+ &context,
+ &path("HIROUTE_NATIVE_HIROUTE_CLI"),
+ QoderCollaborationProbeTarget::PreinstallCapability,
+ )
+ .unwrap();
+ }
+}
diff --git a/crates/integrations/src/agents/qoder_probe_http.rs b/crates/integrations/src/agents/qoder_probe_http.rs
new file mode 100644
index 00000000..26aa990e
--- /dev/null
+++ b/crates/integrations/src/agents/qoder_probe_http.rs
@@ -0,0 +1,282 @@
+//! A deterministic Responses peer: native Skill discovery, exact user path/body, then one CLI.
+//! Requests stay in memory and are never forwarded or included in diagnostics.
+use serde_json::{Value, json};
+use std::io::{Read, Write};
+use std::net::TcpStream;
+use std::time::{Duration, Instant};
+
+pub(super) struct Challenge {
+ pub skill_name: String,
+ pub skill_directory: String,
+ pub skill_body: String,
+ pub command: String,
+ pub expected_cli: String,
+ pub step: usize,
+}
+
+impl Challenge {
+ pub fn complete(&self) -> bool {
+ self.step == 3
+ }
+
+ fn reply(&mut self, body: &Value) -> Result<Value, &'static str> {
+ let input = body["input"].as_array().ok_or("native input contract")?;
+ let tool_declared = |name| {
+ body["tools"]
+ .as_array()
+ .is_some_and(|tools| tools.iter().any(|tool| tool["name"] == name))
+ };
+ let tool_result = |call: &str| {
+ input
+ .iter()
+ .find(|item| item["type"] == "function_call_output" && item["call_id"] == call)
+ .and_then(|item| item["output"].as_str())
+ };
+ let item = match self.step {
+ 0 => {
+ if !body.to_string().contains(&self.skill_name)
+ || !tool_declared("Skill")
+ || !tool_declared("Bash")
+ {
+ return Err("native Skill discovery");
+ }
+ function("skill", "Skill", json!({"skill": self.skill_name}))
+ }
+ 1 => {
+ if tool_result("call_hiroute_skill")
+ != Some(format!("Launching skill: {}", self.skill_name).as_str())
+ {
+ return Err("native Skill call result");
+ }
+ let prefix = format!(
+ "Base directory for this skill: {}\n\n",
+ self.skill_directory
+ );
+ let loaded = input
+ .iter()
+ .filter(|item| item["type"] == "message" && item["role"] == "user")
+ .filter_map(|item| item["content"].as_array())
+ .flatten()
+ .filter_map(|item| item["text"].as_str())
+ .any(|text| {
+ text.strip_prefix(&prefix)
+ .is_some_and(|body| body.trim() == self.skill_body.trim())
+ });
+ if !loaded {
+ return Err("actual native Skill path and contents");
+ }
+ function(
+ "cli",
+ "Bash",
+ json!({"command": self.command, "timeout": 10_000}),
+ )
+ }
+ 2 => {
+ let output = tool_result("call_hiroute_cli").ok_or("trusted CLI call result")?;
+ if output.trim() != self.expected_cli.trim() {
+ return Err("trusted CLI result mismatch");
+ }
+ json!({"id":"msg_hiroute_probe", "type":"message", "status":"completed", "role":"assistant", "content":[{"type":"output_text", "text":"OK", "annotations":[]}]})
+ }
+ _ => return Err("native request limit"),
+ };
+ self.step += 1;
+ Ok(item)
+ }
+}
+
+fn function(suffix: &str, name: &str, args: Value) -> Value {
+ json!({"id":format!("fc_hiroute_{suffix}"), "type":"function_call", "status":"completed", "call_id":format!("call_hiroute_{suffix}"), "name":name, "arguments":args.to_string()})
+}
+
+pub(super) fn serve(
+ stream: &mut TcpStream,
+ token: &str,
+ model: &str,
+ challenge: &mut Challenge,
+) -> Result<(), &'static str> {
+ let body = read_request(stream, token, model)?;
+ let item = challenge.reply(&body)?;
+ let response = json!({"id":"resp_hiroute_probe", "object":"response", "created_at":1, "status":"completed", "model":model, "output":[item], "usage":{"input_tokens":1,"output_tokens":1,"total_tokens":2}});
+ let mut started = response.clone();
+ started["status"] = "in_progress".into();
+ started["output"] = json!([]);
+ let mut added = item.clone();
+ added["status"] = "in_progress".into();
+ let mut events = vec![("response.created", json!({"response":started}))];
+ if item["type"] == "function_call" {
+ // Qoder validates streaming argument consistency; adding the final arguments and then
+ // appending a delta would duplicate them and fail before any tool executes.
+ added["arguments"] = "".into();
+ events.push((
+ "response.output_item.added",
+ json!({"output_index":0,"item":added}),
+ ));
+ events.push((
+ "response.function_call_arguments.delta",
+ json!({"output_index":0,"item_id":item["id"],"delta":item["arguments"]}),
+ ));
+ events.push((
+ "response.function_call_arguments.done",
+ json!({"output_index":0,"item_id":item["id"],"arguments":item["arguments"]}),
+ ));
+ } else {
+ added["content"] = json!([]);
+ events.push((
+ "response.output_item.added",
+ json!({"output_index":0,"item":added}),
+ ));
+ events.push((
+ "response.output_text.delta",
+ json!({"output_index":0,"content_index":0,"item_id":item["id"],"delta":"OK"}),
+ ));
+ }
+ events.push((
+ "response.output_item.done",
+ json!({"output_index":0,"item":item}),
+ ));
+ events.push(("response.completed", json!({"response":response})));
+ let mut payload = String::new();
+ for (index, (kind, mut event)) in events.into_iter().enumerate() {
+ event["type"] = kind.into();
+ event["sequence_number"] = index.into();
+ payload.push_str(&format!("event: {kind}\ndata: {event}\n\n"));
+ }
+ write!(stream,"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{payload}",payload.len()).map_err(|_| "loopback response")
+}
+
+fn read_request(stream: &mut TcpStream, token: &str, model: &str) -> Result<Value, &'static str> {
+ stream.set_nonblocking(false).map_err(|_| "socket mode")?;
+ stream
+ .set_read_timeout(Some(Duration::from_millis(500)))
+ .map_err(|_| "socket timeout")?;
+ stream
+ .set_write_timeout(Some(Duration::from_millis(500)))
+ .map_err(|_| "socket timeout")?;
+ let started = Instant::now();
+ let mut bytes = zeroize::Zeroizing::new(Vec::new());
+ let (header_end, length) = loop {
+ if bytes.len() > 128 * 1024 || started.elapsed() > Duration::from_secs(2) {
+ return Err("request bound");
+ }
+ if let Some(end) = bytes.windows(4).position(|part| part == b"\r\n\r\n") {
+ let header = std::str::from_utf8(&bytes[..end]).map_err(|_| "request header")?;
+ if header.lines().next() != Some("POST /v1/responses HTTP/1.1") {
+ return Err("request path");
+ }
+ let mut auth = None;
+ let mut length = None;
+ for line in header.lines().skip(1) {
+ let (name, value) = line.split_once(':').ok_or("request header")?;
+ if name.eq_ignore_ascii_case("authorization")
+ && auth.replace(value.trim()).is_some()
+ {
+ return Err("duplicate auth");
+ }
+ if name.eq_ignore_ascii_case("content-length")
+ && length
+ .replace(
+ value
+ .trim()
+ .parse::<usize>()
+ .map_err(|_| "request length")?,
+ )
+ .is_some()
+ {
+ return Err("duplicate length");
+ }
+ if name.eq_ignore_ascii_case("transfer-encoding") {
+ return Err("request framing");
+ }
+ }
+ if auth.and_then(|value| value.strip_prefix("Bearer ")) != Some(token) {
+ return Err("request credential");
+ }
+ break (
+ end + 4,
+ length
+ .filter(|value| *value <= 128 * 1024)
+ .ok_or("request length")?,
+ );
+ }
+ let mut chunk = [0; 4096];
+ let size = stream.read(&mut chunk).map_err(|_| "request header read")?;
+ if size == 0 {
+ return Err("short request");
+ }
+ bytes.extend_from_slice(&chunk[..size]);
+ };
+ while bytes.len() < header_end + length {
+ if started.elapsed() > Duration::from_secs(2) {
+ return Err("request deadline");
+ }
+ let mut chunk = [0; 4096];
+ let size = stream.read(&mut chunk).map_err(|_| "request body read")?;
+ if size == 0 {
+ return Err("short request");
+ }
+ bytes.extend_from_slice(&chunk[..size]);
+ }
+ let body: Value = serde_json::from_slice(&bytes[header_end..header_end + length])
+ .map_err(|_| "request json")?;
+ if body["model"] != model {
+ return Err("request model");
+ }
+ Ok(body)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn challenge() -> Challenge {
+ Challenge {
+ skill_name: "hiroute-collaboration".into(),
+ skill_directory: "/user/.qoder/skills/hiroute-collaboration".into(),
+ skill_body: "confirmed Skill body".into(),
+ command: "trusted cli".into(),
+ expected_cli: "trusted result".into(),
+ step: 1,
+ }
+ }
+
+ #[test]
+ fn installed_skill_requires_correlated_call_and_actual_user_source() {
+ let body = |directory, call| {
+ json!({"input":[
+ {"type":"function_call_output","call_id":call,"output":"Launching skill: hiroute-collaboration"},
+ {"type":"message","role":"user","content":[{"type":"input_text","text":format!("Base directory for this skill: {directory}\n\nconfirmed Skill body")}]}]})
+ };
+ assert!(
+ challenge()
+ .reply(&body(
+ "/project/.qoder/skills/hiroute-collaboration",
+ "call_hiroute_skill"
+ ))
+ .is_err()
+ );
+ assert!(
+ challenge()
+ .reply(&body(
+ "/user/.qoder/skills/hiroute-collaboration",
+ "unrelated_call"
+ ))
+ .is_err()
+ );
+ assert!(
+ challenge()
+ .reply(&body(
+ "/user/.qoder/skills/hiroute-collaboration",
+ "call_hiroute_skill"
+ ))
+ .is_ok()
+ );
+ }
+
+ #[test]
+ fn model_claim_cannot_replace_cli_tool_evidence() {
+ let mut check = challenge();
+ check.step = 2;
+ assert!(check.reply(&json!({"input":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"trusted result"}]}]})).is_err());
+ }
+}
diff --git a/crates/integrations/src/agents/qoder_provider.rs b/crates/integrations/src/agents/qoder_provider.rs
new file mode 100644
index 00000000..8a0ec991
--- /dev/null
+++ b/crates/integrations/src/agents/qoder_provider.rs
@@ -0,0 +1,77 @@
+//! Shared native provider/model wire projection; no settings-scope or token ownership policy.
+use super::{QoderNativeError, QoderTokenBudget, qoder_error};
+use serde_json::{Value, json};
+
+pub(super) fn validate_route(provider_id: &str, endpoint: &str) -> Result<(), QoderNativeError> {
+ validate_route_at(provider_id, endpoint, "/v1")
+}
+
+pub(super) fn validate_model_route(
+ provider_id: &str,
+ endpoint: &str,
+) -> Result<(), QoderNativeError> {
+ validate_route_at(provider_id, endpoint, hiroute_domain::QODER_MODEL_BASE_PATH)
+}
+
+fn validate_route_at(
+ provider_id: &str,
+ endpoint: &str,
+ path: &str,
+) -> Result<(), QoderNativeError> {
+ if provider_id.is_empty()
+ || provider_id.len() > 128
+ || provider_id == "qoder"
+ || !provider_id.as_bytes()[0].is_ascii_alphanumeric()
+ || !provider_id
+ .bytes()
+ .all(|b| b.is_ascii_alphanumeric() || b"._-".contains(&b))
+ {
+ return Err(qoder_error("provider identity"));
+ }
+ let endpoint: reqwest::Url = endpoint
+ .parse()
+ .map_err(|_| qoder_error("loopback route"))?;
+ if endpoint.scheme() != "http"
+ || !endpoint.username().is_empty()
+ || endpoint.password().is_some()
+ || endpoint.query().is_some()
+ || endpoint.fragment().is_some()
+ || endpoint.path() != path
+ || !endpoint
+ .host_str()
+ .and_then(|h| h.trim_matches(['[', ']']).parse::<std::net::IpAddr>().ok())
+ .is_some_and(|h| h.is_loopback())
+ {
+ return Err(qoder_error("loopback route"));
+ }
+ Ok(())
+}
+
+pub(super) fn model(
+ alias: &str,
+ context: Option<u64>,
+ output: u64,
+) -> Result<Value, QoderNativeError> {
+ if alias.is_empty()
+ || alias.len() > 512
+ || alias.chars().any(char::is_control)
+ || alias.contains("${")
+ || alias.trim() != alias
+ {
+ return Err(qoder_error("model alias"));
+ }
+ hiroute_domain::validate_qoder_output_budget(output)?;
+ if let Some(context) = context {
+ QoderTokenBudget::new(context, output)?;
+ }
+ let mut model = json!({"model":alias,"capabilities":{"tools":true},"maxOutputTokens":output});
+ if let Some(context) = context {
+ model["contextWindow"] = context.into();
+ }
+ Ok(model)
+}
+
+pub(super) fn provider(endpoint: &str, credential: &str, models: Vec<Value>) -> Value {
+ json!({"type":"openai-compatible", "protocol":"openai-responses", "authType":"bearer",
+ "baseUrl":endpoint, "apiKey":credential, "models":models})
+}
diff --git a/crates/integrations/src/agents/registry.rs b/crates/integrations/src/agents/registry.rs
index b6e0dd12..d9370228 100644
--- a/crates/integrations/src/agents/registry.rs
+++ b/crates/integrations/src/agents/registry.rs
@@ -12,11 +12,17 @@ pub const CLAUDE_CODE_VERIFIED_VERSION_V1: &str = "2.1.0";
pub const CLAUDE_CODE_VERIFIED_VERSION_2_1_231_V1: &str = "2.1.231";
pub const CODEX_PROFILE_ID_V1: &str = "codex-responses-v1";
pub const CLAUDE_PROFILE_ID_V1: &str = "claude-messages-v1";
+pub const QODER_PROFILE_ID_V1: &str = "qoder-collaboration-v1";
pub const CODEX_INTEGRATION_PROFILE_REF_V1: &str = "builtin/codex-responses/v1";
pub const CLAUDE_INTEGRATION_PROFILE_REF_V1: &str = "builtin/claude-messages/v1";
+pub const QODER_INTEGRATION_PROFILE_REF_V1: &str = "builtin/qoder-collaboration/v1";
pub fn builtin_agent_profiles() -> Vec<AgentProfileV1> {
- vec![codex_profile_v1(), claude_code_profile_v1()]
+ vec![
+ codex_profile_v1(),
+ claude_code_profile_v1(),
+ qoder_collaboration_profile_v1(),
+ ]
}
pub fn codex_profile_v1() -> AgentProfileV1 {
@@ -29,7 +35,7 @@ pub fn codex_profile_v1() -> AgentProfileV1 {
// Codex versions are diagnostic only. MVP admission never uses a binary-version
// allowlist; concrete Desktop and CLI surfaces locate and launch their actual engine.
legacy_exact_versions: BTreeSet::new(),
- ingress_protocol: AgentIngressProtocolV1::Responses,
+ ingress_protocol: Some(AgentIngressProtocolV1::Responses),
config_precedence: AgentKindV1::Codex.config_precedence().to_vec(),
owned_config_fields: vec![
field("provider", "model_provider"),
@@ -63,7 +69,7 @@ pub fn claude_code_profile_v1() -> AgentProfileV1 {
integration_profile_ref: CLAUDE_INTEGRATION_PROFILE_REF_V1.to_owned(),
kind: AgentKindV1::ClaudeCode,
legacy_exact_versions: BTreeSet::new(),
- ingress_protocol: AgentIngressProtocolV1::Messages,
+ ingress_protocol: Some(AgentIngressProtocolV1::Messages),
config_precedence: AgentKindV1::ClaudeCode.config_precedence().to_vec(),
owned_config_fields: vec![
field("base_endpoint", "env.ANTHROPIC_BASE_URL"),
@@ -86,6 +92,27 @@ pub fn claude_code_profile_v1() -> AgentProfileV1 {
}
}
+/// Keep the original collaboration identity so accepted Skill ownership remains valid.
+/// Model routing adds one scoped provider; it never claims native defaults or account auth.
+pub fn qoder_collaboration_profile_v1() -> AgentProfileV1 {
+ AgentProfileV1 {
+ schema: AGENT_PROFILE_SCHEMA_V1.to_owned(),
+ profile_id: QODER_PROFILE_ID_V1.to_owned(),
+ integration_profile_ref: QODER_INTEGRATION_PROFILE_REF_V1.to_owned(),
+ kind: AgentKindV1::Qoder,
+ legacy_exact_versions: BTreeSet::new(),
+ ingress_protocol: Some(AgentIngressProtocolV1::Responses),
+ config_precedence: AgentKindV1::Qoder.config_precedence().to_vec(),
+ // Adapter-semantic ownership: only the context-specific provider inside this map.
+ owned_config_fields: vec![field("additional_provider", "hiroute.additional_provider")],
+ dynamic_catalog: false,
+ static_catalog_fallback: false,
+ native_subagent_routing: false,
+ spawn_guidance: None,
+ managed_launch: None,
+ }
+}
+
pub fn codex_spawn_agent_tool_v1() -> FunctionToolV1 {
FunctionToolV1 {
registration_id: "codex.builtin.spawn-agent.v1".to_owned(),
diff --git a/crates/integrations/src/agents/tests.rs b/crates/integrations/src/agents/tests.rs
index ed22cc23..e5d707c6 100644
--- a/crates/integrations/src/agents/tests.rs
+++ b/crates/integrations/src/agents/tests.rs
@@ -21,17 +21,17 @@ fn observation(kind: AgentKindV1, version: &str) -> AgentScanObservationV1 {
#[test]
fn agents_registry_binds_codex_to_responses_and_claude_to_messages() {
let profiles = builtin_agent_profiles();
- assert_eq!(profiles.len(), 2);
+ assert_eq!(profiles.len(), 3);
for profile in &profiles {
profile.validate().unwrap();
}
assert_eq!(
codex_profile_v1().client_protocol(),
- AgentIngressProtocolV1::Responses
+ Some(AgentIngressProtocolV1::Responses)
);
assert_eq!(
claude_code_profile_v1().client_protocol(),
- AgentIngressProtocolV1::Messages
+ Some(AgentIngressProtocolV1::Messages)
);
if std::env::var_os("HIROUTE_PRINT_AGENT_DIGESTS").is_some() {
println!(
@@ -113,7 +113,7 @@ fn agents_codex_and_claude_emulators_have_closed_native_shapes() {
)
.unwrap();
let rendered = render_agent_probe(&profile, &probe).unwrap();
- assert_eq!(rendered.protocol, profile.client_protocol());
+ assert_eq!(Some(rendered.protocol), profile.client_protocol());
assert_eq!(
rendered.payload["metadata"]["traffic_kind"],
"connectivity_probe"
@@ -300,3 +300,38 @@ fn agents_emulator_response_parser_is_protocol_exact_and_rejects_tools() {
});
assert!(parse_agent_probe_response(&codex, &with_tool).is_err());
}
+
+#[test]
+fn collaboration_only_installation_cannot_render_or_accept_a_model_connectivity_probe() {
+ let profile: hiroute_domain::AgentProfileV1 = serde_json::from_value(json!({
+ "schema":"hiroute.agent-profile/v1", "profile_id":"qoder-collaboration-v1",
+ "integration_profile_ref":"builtin/qoder-collaboration/v1", "kind":"qoder",
+ "config_precedence":[], "owned_config_fields":[], "dynamic_catalog":false,
+ "static_catalog_fallback":false, "native_subagent_routing":false,
+ }))
+ .unwrap();
+ let mut forged = BuiltInAgentProbeV1::for_profile(
+ &codex_profile_v1(),
+ ModelAlias::parse("hiroute/0011223344556677").unwrap(),
+ )
+ .unwrap();
+ forged.profile_id = profile.profile_id.clone();
+ forged.integration_profile_ref = profile.integration_profile_ref.clone();
+ assert!(matches!(
+ render_agent_probe(&profile, &forged),
+ Err(AgentProbeAdapterError::Contract(
+ hiroute_domain::AgentEmulatorError::InvalidProfile
+ ))
+ ));
+ // Even a valid Responses challenge receipt cannot create model verification evidence for
+ // an installation which only supports collaboration.
+ let response = json!({"output":[{"type":"message","content":[{
+ "type":"output_text", "text":hiroute_domain::CONNECTIVITY_PROBE_RESPONSE_V1,
+ }]}]});
+ assert!(matches!(
+ parse_agent_probe_response(&profile, &response),
+ Err(AgentProbeAdapterError::Contract(
+ hiroute_domain::AgentEmulatorError::InvalidProfile
+ ))
+ ));
+}
diff --git a/crates/integrations/tests/agent_profiles.rs b/crates/integrations/tests/agent_profiles.rs
index 4c0fe848..ac013d52 100644
--- a/crates/integrations/tests/agent_profiles.rs
+++ b/crates/integrations/tests/agent_profiles.rs
@@ -26,7 +26,10 @@ fn agent_profiles_freeze_protocol_precedence_and_owned_fields_without_version_ga
.find(|profile| profile.kind == AgentKindV1::Codex)
.unwrap();
assert!(codex.legacy_exact_versions.is_empty());
- assert_eq!(codex.ingress_protocol, AgentIngressProtocolV1::Responses);
+ assert_eq!(
+ codex.ingress_protocol,
+ Some(AgentIngressProtocolV1::Responses)
+ );
assert_eq!(
codex.config_precedence,
[
@@ -46,7 +49,10 @@ fn agent_profiles_freeze_protocol_precedence_and_owned_fields_without_version_ga
.find(|profile| profile.kind == AgentKindV1::ClaudeCode)
.unwrap();
assert!(claude.legacy_exact_versions.is_empty());
- assert_eq!(claude.ingress_protocol, AgentIngressProtocolV1::Messages);
+ assert_eq!(
+ claude.ingress_protocol,
+ Some(AgentIngressProtocolV1::Messages)
+ );
assert!(claude.field("base_endpoint").is_some());
assert!(claude.supports_managed_launch());
assert_eq!(
diff --git a/crates/local-storage/Cargo.toml b/crates/local-storage/Cargo.toml
index 925a096c..fc4a2a1d 100644
--- a/crates/local-storage/Cargo.toml
+++ b/crates/local-storage/Cargo.toml
@@ -16,7 +16,7 @@ hiroute-domain = { path = "../domain" }
rusqlite.workspace = true
rustix = { workspace = true, features = ["fs"] }
serde.workspace = true
-serde_json.workspace = true
+serde_json = { workspace = true, features = ["raw_value"] }
sha2.workspace = true
thiserror.workspace = true
zeroize.workspace = true
diff --git a/crates/local-storage/src/agents/native_artifacts.rs b/crates/local-storage/src/agents/native_artifacts.rs
index 4921a73f..884ebec6 100644
--- a/crates/local-storage/src/agents/native_artifacts.rs
+++ b/crates/local-storage/src/agents/native_artifacts.rs
@@ -58,7 +58,7 @@ impl NativeAgentArtifactPort for ManagedArtifactStore {
let path = self
.target_path(intent.target())
.map_err(|_| port(PortErrorCode::PermissionDenied, "native.restoration.target"))?;
- let current = read_native_file(&path, MAX_NATIVE_BYTES)
+ let current = read_native_file(&path, MAX_NATIVE_BYTES, None)
.map_err(|_| port(PortErrorCode::Conflict, "native.restoration.file"))?;
if current.as_deref().map(|b| b.as_slice()) != expected {
return Err(port(PortErrorCode::Conflict, "native.restoration.changed"));
@@ -159,18 +159,10 @@ impl NativeAgentArtifactPort for ManagedArtifactStore {
.map_err(|_| port(PortErrorCode::PermissionDenied, "native.parents.cleanup"))
}
fn read_native_target(&self, target: &str) -> PortResult<Option<Zeroizing<Vec<u8>>>> {
- let path = self
- .target_path(target)
- .map_err(|_| port(PortErrorCode::PermissionDenied, "native.target"))?;
- let bytes = read_native_file(&path, MAX_NATIVE_BYTES)
- .map_err(|_| port(PortErrorCode::PermissionDenied, "native.read"))?;
- if bytes
- .as_ref()
- .is_some_and(|bytes| bytes.len() > MAX_NATIVE_BYTES)
- {
- return Err(port(PortErrorCode::InvalidData, "native.size"));
- }
- Ok(bytes)
+ self.read_native_target_with_mode(target, None)
+ }
+ fn read_private_native_target(&self, target: &str) -> PortResult<Option<Zeroizing<Vec<u8>>>> {
+ self.read_native_target_with_mode(target, Some(0o600))
}
fn native_target_path(&self, target: &str) -> PortResult<std::path::PathBuf> {
self.target_path(target)
@@ -226,6 +218,7 @@ impl NativeAgentArtifactPort for ManagedArtifactStore {
let Some(encoded) = read_native_file(
&self.native_restore_path(operation, intent),
MAX_NATIVE_BYTES + 64,
+ None,
)
.map_err(|_| port(PortErrorCode::Corrupt, "native.restore.read"))?
else {
@@ -274,10 +267,11 @@ impl NativeAgentArtifactPort for ManagedArtifactStore {
pub(super) fn read_native_file(
path: &Path,
limit: usize,
+ required_mode: Option<u32>,
) -> Result<Option<Zeroizing<Vec<u8>>>, LocalStorageError> {
#[cfg(not(unix))]
{
- let _ = (path, limit);
+ let _ = (path, limit, required_mode);
Err(LocalStorageError::Permission)
}
#[cfg(unix)]
@@ -299,6 +293,7 @@ pub(super) fn read_native_file(
|| before.nlink() != 1
|| before.uid() != rustix::process::getuid().as_raw()
|| !supported_artifact_mode(before.mode() & 0o777)
+ || required_mode.is_some_and(|mode| before.mode() & 0o7777 != mode)
|| before.len() > limit as u64
{
return Err(LocalStorageError::Permission);
@@ -330,6 +325,25 @@ pub(super) fn read_native_file(
}
}
impl ManagedArtifactStore {
+ fn read_native_target_with_mode(
+ &self,
+ target: &str,
+ required_mode: Option<u32>,
+ ) -> PortResult<Option<Zeroizing<Vec<u8>>>> {
+ let path = self
+ .target_path(target)
+ .map_err(|_| port(PortErrorCode::PermissionDenied, "native.target"))?;
+ let bytes = read_native_file(&path, MAX_NATIVE_BYTES, required_mode)
+ .map_err(|_| port(PortErrorCode::PermissionDenied, "native.read"))?;
+ if bytes
+ .as_ref()
+ .is_some_and(|bytes| bytes.len() > MAX_NATIVE_BYTES)
+ {
+ return Err(port(PortErrorCode::InvalidData, "native.size"));
+ }
+ Ok(bytes)
+ }
+
fn native_restore_path(
&self,
operation: &OperationId,
diff --git a/crates/local-storage/src/agents/native_file_tests.rs b/crates/local-storage/src/agents/native_file_tests.rs
index 100d692c..10c89ce8 100644
--- a/crates/local-storage/src/agents/native_file_tests.rs
+++ b/crates/local-storage/src/agents/native_file_tests.rs
@@ -19,6 +19,8 @@ mod native_claude_file_tests;
mod native_codex_catalog_tests;
#[path = "native_codex_test.rs"]
mod native_codex_test;
+#[path = "native_registration_tests.rs"]
+mod native_registration_tests;
#[path = "settings_skill_journal_tests.rs"]
mod settings_skill_journal_tests;
#[path = "skill_parent_tests.rs"]
diff --git a/crates/local-storage/src/agents/native_registration_tests.rs b/crates/local-storage/src/agents/native_registration_tests.rs
new file mode 100644
index 00000000..f5ce8a25
--- /dev/null
+++ b/crates/local-storage/src/agents/native_registration_tests.rs
@@ -0,0 +1,123 @@
+//! Registering an unused native target is not permission to read, write or recover it.
+use super::*;
+
+#[test]
+fn unused_unsafe_target_does_not_block_a_safe_neighbor_but_cannot_be_used() {
+ let root = crate::test_tempdir().unwrap();
+ let unsafe_parent = root.path().join("unsafe-native");
+ let safe_parent = root.path().join("safe-native");
+ fs::create_dir(&unsafe_parent).unwrap();
+ fs::create_dir(&safe_parent).unwrap();
+ fs::set_permissions(&unsafe_parent, fs::Permissions::from_mode(0o775)).unwrap();
+ fs::set_permissions(&safe_parent, fs::Permissions::from_mode(0o700)).unwrap();
+ let paths = [
+ unsafe_parent.join("settings.json"),
+ safe_parent.join("settings.json"),
+ ];
+ let intents = ["agent.unselected", "agent.selected"].map(|agent| {
+ intent_for_agent(
+ AgentConnectionTransactionKindV1::Apply,
+ AgentConnectionEffectRoleV1::ManagedConfiguration,
+ None,
+ agent,
+ "profile.fixture",
+ )
+ });
+ let mut store = ManagedArtifactStore::open_with_external_targets(
+ &crate::test_storage_authority(),
+ root.path().join("artifacts"),
+ root.path().join("restore"),
+ intents
+ .iter()
+ .zip(&paths)
+ .map(|(intent, path)| (intent.target().to_owned(), path.clone())),
+ )
+ .unwrap();
+ let operation = OperationId::parse("op_00112233445566778899aabbccddeeff").unwrap();
+ assert_eq!(
+ store
+ .read_native_target(intents[0].target())
+ .unwrap_err()
+ .code,
+ PortErrorCode::PermissionDenied
+ );
+ assert!(
+ store
+ .stage_native_target(&operation, &intents[0], Some(b"must not write"), false)
+ .is_err()
+ );
+ assert!(
+ store
+ .load_marker(&operation, intents[0].effect_id())
+ .unwrap()
+ .is_none()
+ );
+ assert!(!paths[0].exists());
+ // Explicit later binding remains an admission check, unlike startup enumeration.
+ assert!(matches!(
+ store.bind_external_target("another-target", unsafe_parent.join("other-settings.json")),
+ Err(LocalStorageError::Permission)
+ ));
+ let effect = store
+ .stage_native_target(&operation, &intents[1], Some(b"safe neighbor"), false)
+ .unwrap();
+ store.activate_artifact(&effect).unwrap();
+ assert_eq!(fs::read(&paths[1]).unwrap(), b"safe neighbor");
+ assert_eq!(
+ fs::metadata(&unsafe_parent).unwrap().permissions().mode() & 0o777,
+ 0o775
+ );
+ assert_eq!(fs::read_dir(&unsafe_parent).unwrap().count(), 0);
+}
+
+#[test]
+fn unsafe_durable_native_target_blocks_activation_restoration_and_recovery_without_changes() {
+ for activated in [false, true] {
+ let root = crate::test_tempdir().unwrap();
+ let parent = root.path().join("native");
+ fs::create_dir(&parent).unwrap();
+ fs::set_permissions(&parent, fs::Permissions::from_mode(0o700)).unwrap();
+ let path = parent.join("settings.json");
+ let intent = intent(
+ AgentConnectionTransactionKindV1::Apply,
+ AgentConnectionEffectRoleV1::ManagedConfiguration,
+ None,
+ );
+ let operation = OperationId::parse("op_00112233445566778899aabbccddeeff").unwrap();
+ let open = || {
+ ManagedArtifactStore::open_with_external_targets(
+ &crate::test_storage_authority(),
+ root.path().join("artifacts"),
+ root.path().join("restore"),
+ [(intent.target().to_owned(), path.clone())],
+ )
+ };
+ let store = open().unwrap();
+ let effect = store
+ .stage_native_target(&operation, &intent, Some(b"managed content"), false)
+ .unwrap();
+ if activated {
+ store.activate_artifact(&effect).unwrap();
+ }
+ fs::set_permissions(&parent, fs::Permissions::from_mode(0o775)).unwrap();
+ let target_before = fs::read(&path).ok();
+ let marker_path = store.marker_path(&operation, intent.effect_id());
+ let marker_before = fs::read(&marker_path).unwrap();
+ let restore_key = root.path().join("restore/.restore-key");
+ let key_before = fs::read(&restore_key).unwrap();
+ if !activated {
+ assert!(store.activate_artifact(&effect).is_err());
+ }
+ assert!(store.compensate_artifact(&effect).is_err());
+ assert!(store.read_native_target(intent.target()).is_err());
+ drop(store);
+ assert!(matches!(open(), Err(LocalStorageError::Permission)));
+ assert_eq!(fs::read(&path).ok(), target_before);
+ assert_eq!(fs::read(&marker_path).unwrap(), marker_before);
+ assert_eq!(fs::read(&restore_key).unwrap(), key_before);
+ assert_eq!(
+ fs::metadata(&parent).unwrap().permissions().mode() & 0o777,
+ 0o775
+ );
+ }
+}
diff --git a/crates/local-storage/src/agents/native_restoration_ack.rs b/crates/local-storage/src/agents/native_restoration_ack.rs
index b468690e..de7038af 100644
--- a/crates/local-storage/src/agents/native_restoration_ack.rs
+++ b/crates/local-storage/src/agents/native_restoration_ack.rs
@@ -56,7 +56,7 @@ impl ManagedArtifactStore {
));
}
let target = self.native_target_path(intent.target())?;
- let safe = read_native_file(&target, 1024 * 1024).map_err(|_| {
+ let safe = read_native_file(&target, 1024 * 1024, None).map_err(|_| {
port(
PortErrorCode::PermissionDenied,
"native.restoration.ack.read",
@@ -96,7 +96,7 @@ impl ManagedArtifactStore {
));
}
let target = self.native_target_path(intent.target())?;
- let current = read_native_file(&target, 1024 * 1024).map_err(|_| {
+ let current = read_native_file(&target, 1024 * 1024, None).map_err(|_| {
port(
PortErrorCode::PermissionDenied,
"native.restoration.ack.read",
diff --git a/crates/local-storage/src/control/agent_transaction_tests.rs b/crates/local-storage/src/control/agent_transaction_tests.rs
index bf2cc583..4ad368d4 100644
--- a/crates/local-storage/src/control/agent_transaction_tests.rs
+++ b/crates/local-storage/src/control/agent_transaction_tests.rs
@@ -136,13 +136,72 @@ fn native_read_rejects_links_and_oversized_files_without_following() {
fs::set_permissions(&target, fs::Permissions::from_mode(0o600)).unwrap();
fs::hard_link(&target, root.join("other")).unwrap();
assert!(store.read_native_target("native.toml").is_err());
+ assert!(store.read_private_native_target("native.toml").is_err());
fs::remove_file(&target).unwrap();
symlink(root.join("other"), &target).unwrap();
assert!(store.read_native_target("native.toml").is_err());
+ assert!(store.read_private_native_target("native.toml").is_err());
fs::remove_file(&target).unwrap();
let file = fs::File::create(&target).unwrap();
file.set_len(1024 * 1024 + 1).unwrap();
+ fs::set_permissions(&target, fs::Permissions::from_mode(0o600)).unwrap();
assert!(store.read_native_target("native.toml").is_err());
+ assert!(store.read_private_native_target("native.toml").is_err());
+}
+
+#[test]
+#[cfg(unix)]
+fn private_native_read_requires_0600_while_import_can_read_0644_without_chmod() {
+ use hiroute_domain::{NativeAgentArtifactPort, PortErrorCode};
+ use std::os::unix::fs::PermissionsExt;
+ let directory = tempdir().unwrap();
+ let path = directory.path().join("settings.json");
+ let store = ManagedArtifactStore::open_with_external_target(
+ &crate::test_storage_authority(),
+ directory.path().join("artifacts"),
+ directory.path().join("restore"),
+ "native-settings",
+ &path,
+ )
+ .unwrap();
+ assert!(
+ store
+ .read_private_native_target("native-settings")
+ .unwrap()
+ .is_none()
+ );
+ let bytes = br#"{"providers":[{"apiKey":"fixture-local-bearer"}]}"#;
+ fs::write(&path, bytes).unwrap();
+ fs::set_permissions(&path, fs::Permissions::from_mode(0o600)).unwrap();
+ assert_eq!(
+ store
+ .read_private_native_target("native-settings")
+ .unwrap()
+ .unwrap()
+ .as_slice(),
+ bytes
+ );
+ fs::set_permissions(&path, fs::Permissions::from_mode(0o644)).unwrap();
+ assert_eq!(
+ store
+ .read_private_native_target("native-settings")
+ .unwrap_err()
+ .code,
+ PortErrorCode::PermissionDenied
+ );
+ assert_eq!(
+ store
+ .read_native_target("native-settings")
+ .unwrap()
+ .unwrap()
+ .as_slice(),
+ bytes
+ );
+ assert_eq!(
+ fs::metadata(&path).unwrap().permissions().mode() & 0o7777,
+ 0o644
+ );
+ assert_eq!(fs::read(&path).unwrap(), bytes);
}
fn agent_transaction_plan(
diff --git a/crates/local-storage/src/control/journal.rs b/crates/local-storage/src/control/journal.rs
index 0a729939..b5276df7 100644
--- a/crates/local-storage/src/control/journal.rs
+++ b/crates/local-storage/src/control/journal.rs
@@ -83,11 +83,13 @@ pub(super) fn is_current(connection: &Connection, operation: &OperationV1) -> Po
.map_err(|_| port(PortErrorCode::InvalidData, "control.current.steps"))?;
let revisions = serde_json::to_string(&operation.expected_revisions)
.map_err(|_| port(PortErrorCode::InvalidData, "control.current.revisions"))?;
- // Step rows are written through json! (Value), whose object ordering depends on the
- // serde_json feature set. Use the same representation, not struct field order.
- let step_rows = serde_json::to_value(&operation.steps)
- .map_err(|_| port(PortErrorCode::InvalidData, "control.current.step-rows"))?
- .to_string();
+ // Current row production is canonical; historical rows may retain struct member order.
+ // Compare their exact JSON structure, without rewriting either stored journal copy.
+ let step_rows = hiroute_domain::canonicalize_json(
+ serde_json::to_value(&operation.steps)
+ .map_err(|_| port(PortErrorCode::InvalidData, "control.current.step-rows"))?,
+ )
+ .to_string();
// A sealed settings service releases its writer claim while the native-file tail waits for
// explicit retry. The coordinator verifies the receipt before doing any tail work and must
// still be able to observe this exact committed journal during startup recovery.
@@ -98,9 +100,15 @@ pub(super) fn is_current(connection: &Connection, operation: &OperationV1) -> Po
.as_deref()
.and_then(hiroute_domain::SettingsServiceCompletionV1::parse)
.is_some();
- connection
+ // Fetch guards and both mutable copies in one SQLite snapshot. A second query could
+ // accidentally approve an old generation after another connection commits a new one.
+ let copies: Option<(String, String)> = connection
.query_row(
- "SELECT EXISTS(SELECT 1 FROM operations WHERE operation_id=?1 AND generation=?2
+ "SELECT json_extract(operation_json, '$.steps'),
+ (SELECT json_group_array(json(step)) FROM (
+ SELECT json_extract(step_json, '$.step') AS step FROM operation_steps
+ WHERE operation_id=?1 ORDER BY step_no))
+ FROM operations WHERE operation_id=?1 AND generation=?2
AND json_extract(operation_json, '$.plan')=?3 AND request_digest=?4
AND accepted_change_digest=?5 AND workspace_id=?6 AND principal=?7
AND operation_kind=?8 AND idempotency_key=?9 AND state=?10
@@ -111,22 +119,20 @@ pub(super) fn is_current(connection: &Connection, operation: &OperationV1) -> Po
AND json_extract(operation_json, '$.idempotency.principal')=?7
AND json_extract(operation_json, '$.idempotency.operation_kind')=?8
AND json_extract(operation_json, '$.idempotency.key')=?9
- AND json_extract(operation_json, '$.steps')=json(?11)
- AND json_extract(operation_json, '$.safe_error_code') IS ?12
- AND json_extract(operation_json, '$.expected_revisions')=json(?13)
- AND json_extract(operation_json, '$.schema_version')=?14
+ AND json_type(operation_json, '$.steps')='array'
+ AND json_extract(operation_json, '$.safe_error_code') IS ?11
+ AND json_extract(operation_json, '$.expected_revisions')=json(?12)
+ AND json_extract(operation_json, '$.schema_version')=?13
AND json_extract(operation_json, '$.generation')=?2
AND json_extract(operation_json, '$.state')=?10
AND (state IN ('succeeded', 'rolled_back', 'needs_attention')
OR EXISTS(SELECT 1 FROM writer_claim WHERE operation_id=?1)
- OR (?17 AND NOT EXISTS(SELECT 1 FROM writer_claim)))
- AND (SELECT count(*) FROM operation_steps WHERE operation_id=?1)=?15
+ OR (?15 AND NOT EXISTS(SELECT 1 FROM writer_claim)))
+ AND (SELECT count(*) FROM operation_steps WHERE operation_id=?1)=?14
AND NOT EXISTS(SELECT 1 FROM operation_steps s WHERE s.operation_id=?1
AND (s.step_no IS NOT json_extract(s.step_json, '$.step.sequence')
OR s.step_kind IS NOT json_extract(s.step_json, '$.step.kind')
- OR s.state IS NOT json_extract(s.step_json, '$.step.status')
- OR json_extract(s.step_json, '$.step') IS NOT
- json_extract(?16, '$[' || s.step_no || ']'))))",
+ OR s.state IS NOT json_extract(s.step_json, '$.step.status')))",
params![
operation.operation_id.as_str(),
operation.generation,
@@ -138,15 +144,102 @@ pub(super) fn is_current(connection: &Connection, operation: &OperationV1) -> Po
operation.idempotency.operation_kind,
operation.idempotency.key,
operation.state.as_str(),
- steps,
operation.safe_error_code,
revisions,
operation.schema_version,
operation.steps.len() as u64,
- step_rows,
parked_settings_tail,
],
- |row| row.get(0),
+ |row| Ok((row.get(0)?, row.get(1)?)),
)
- .map_err(|_| port(PortErrorCode::Unavailable, "control.current.read"))
+ .optional()
+ .map_err(|_| port(PortErrorCode::Unavailable, "control.current.read"))?;
+ let Some((journal_steps, row_steps)) = copies else {
+ return Ok(false);
+ };
+ if journal_steps == steps && row_steps == step_rows {
+ return Ok(true);
+ }
+ let expected = read_journal_json(&steps)
+ .map_err(|_| port(PortErrorCode::InvalidData, "control.current.expected-steps"))?;
+ Ok(journal_json_matches(&journal_steps, &expected)
+ && journal_json_matches(&row_steps, &expected))
+}
+
+// Only mutable journal copies use this reader. Immutable plans and admission identities
+// retain exact SQL predicates. Typed OperationStep decoding would discard unknown fields;
+// ordinary Value decoding would discard duplicate members and round oversized numbers.
+fn journal_json_matches(encoded: &str, expected: &JournalJson) -> bool {
+ read_journal_json(encoded).is_ok_and(|actual| actual == *expected)
+}
+
+#[derive(PartialEq)]
+enum JournalJson {
+ Scalar(Value),
+ Number(String),
+ Array(Vec<Self>),
+ Object(BTreeMap<String, Self>),
+}
+
+fn read_journal_json(encoded: &str) -> serde_json::Result<JournalJson> {
+ JournalJson::read(serde_json::from_str(encoded)?, 0)
+}
+
+impl JournalJson {
+ fn read(raw: &serde_json::value::RawValue, depth: usize) -> serde_json::Result<Self> {
+ // RawValue starts a fresh deserializer for each container. Retain serde's usual
+ // whole-document depth bound instead of letting nested corrupt input exhaust the stack.
+ if depth >= 128 {
+ return Err(serde::de::Error::custom("journal nesting limit exceeded"));
+ }
+ match raw.get().as_bytes()[0] {
+ b'{' => {
+ let JournalObject(values) = serde_json::from_str(raw.get())?;
+ values
+ .into_iter()
+ .map(|(key, value)| Ok((key, Self::read(value, depth + 1)?)))
+ .collect::<serde_json::Result<_>>()
+ .map(Self::Object)
+ }
+ b'[' => serde_json::from_str::<Vec<&serde_json::value::RawValue>>(raw.get())?
+ .into_iter()
+ .map(|value| Self::read(value, depth + 1))
+ .collect::<serde_json::Result<_>>()
+ .map(Self::Array),
+ b'"' | b'n' | b't' | b'f' => serde_json::from_str(raw.get()).map(Self::Scalar),
+ // Current producers serialize numeric tokens deterministically. Retain their
+ // spelling to reject changed integers beyond u64 and floats that round alike.
+ _ => Ok(Self::Number(raw.get().to_owned())),
+ }
+ }
+}
+
+struct JournalObject<'a>(BTreeMap<String, &'a serde_json::value::RawValue>);
+
+impl<'de> Deserialize<'de> for JournalObject<'de> {
+ fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
+ struct JournalVisitor;
+ impl<'de> serde::de::Visitor<'de> for JournalVisitor {
+ type Value = JournalObject<'de>;
+
+ fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ formatter.write_str("journal object without duplicate members")
+ }
+
+ fn visit_map<A: serde::de::MapAccess<'de>>(
+ self,
+ mut map: A,
+ ) -> Result<Self::Value, A::Error> {
+ let mut values = BTreeMap::new();
+ while let Some(key) = map.next_key::<String>()? {
+ if values.contains_key(&key) {
+ return Err(serde::de::Error::custom("duplicate journal member"));
+ }
+ values.insert(key, map.next_value()?);
+ }
+ Ok(JournalObject(values))
+ }
+ }
+ deserializer.deserialize_map(JournalVisitor)
+ }
}
diff --git a/crates/local-storage/src/control/journal_order_tests.rs b/crates/local-storage/src/control/journal_order_tests.rs
new file mode 100644
index 00000000..40e64d56
--- /dev/null
+++ b/crates/local-storage/src/control/journal_order_tests.rs
@@ -0,0 +1,186 @@
+//! Journal copies may differ in object order; content and admission identity may not drift.
+use super::*;
+use hiroute_domain::OwnedEffectV1;
+use rusqlite::params;
+
+fn journal_copies(control: &ControlStore) -> (String, String) {
+ let connection = control.connection.borrow();
+ (
+ connection
+ .query_row("SELECT operation_json FROM operations", [], |r| r.get(0))
+ .unwrap(),
+ connection
+ .query_row(
+ "SELECT step_json FROM operation_steps WHERE step_no=0",
+ [],
+ |r| r.get(0),
+ )
+ .unwrap(),
+ )
+}
+
+fn restore_copies(control: &ControlStore, copies: &(String, String)) {
+ let connection = control.connection.borrow();
+ connection
+ .execute("UPDATE operations SET operation_json=?1", [&copies.0])
+ .unwrap();
+ connection
+ .execute(
+ "UPDATE operation_steps SET step_json=?1 WHERE step_no=0",
+ [&copies.1],
+ )
+ .unwrap();
+}
+
+#[test]
+fn journal_member_order_survives_recovery_but_never_hides_changed_or_duplicate_content() {
+ let root = tempdir().unwrap();
+ let control = ControlStore::open(
+ &crate::test_storage_authority(),
+ root.path().join("control.db"),
+ root.path().join("backups"),
+ )
+ .unwrap();
+ let mut op = operation(&WorkspaceId::default(), "journal-object-order", 0);
+ let authorization = authorize(&control, &op, "journal-order-capability", i64::MAX);
+ control.begin_operation(&op, &authorization).unwrap();
+ op.steps[0].effects.push(OwnedEffectV1 {
+ effect_id: "journal-order".into(),
+ kind: OwnedEffectKind::Control,
+ target: "journal-order".into(),
+ before_fingerprint: None,
+ after_fingerprint: None,
+ compensation: json!({"a":1,"large":9_223_372_036_854_775_808_u64,"z":[1,2]}).into(),
+ });
+ control.save_operation(&mut op).unwrap();
+ assert!(control.operation_is_current(&op).unwrap());
+ let immutable_plan: String = control
+ .connection
+ .borrow()
+ .query_row(
+ "SELECT json_extract(operation_json, '$.plan') FROM operations",
+ [],
+ |r| r.get(0),
+ )
+ .unwrap();
+ // SQLite constructs an explicit alternative producer order in both journal copies,
+ // independently of whichever serde_json feature set this test binary resolved.
+ control.connection.borrow().execute_batch(
+ "UPDATE operation_steps SET step_json=json_set(step_json, '$.step', json_object(
+ 'effects', json_extract(step_json, '$.step.effects'),
+ 'attempts', json_extract(step_json, '$.step.attempts'),
+ 'status', json_extract(step_json, '$.step.status'),
+ 'kind', json_extract(step_json, '$.step.kind'),
+ 'deterministic_input_digest', json_extract(step_json, '$.step.deterministic_input_digest'),
+ 'sequence', json_extract(step_json, '$.step.sequence'))) WHERE step_no=0;
+ UPDATE operation_steps SET step_json=json_set(step_json,
+ '$.step.effects[0].compensation', json('{\"z\":[1,2],\"large\":9223372036854775808,\"a\":1}')) WHERE step_no=0;
+ UPDATE operations SET operation_json=json_set(operation_json, '$.steps[0]',
+ json((SELECT json_extract(step_json, '$.step') FROM operation_steps WHERE step_no=0)));"
+ ).unwrap();
+ let reordered = journal_copies(&control);
+ let mut recovered = control.load_operation(&op.operation_id).unwrap().unwrap();
+ assert_eq!(recovered, op);
+ assert!(control.operation_is_current(&recovered).unwrap());
+ assert_eq!(
+ journal_copies(&control),
+ reordered,
+ "read-only validation must retain old bytes"
+ );
+
+ let compensation_locations = [
+ (
+ "operations",
+ "operation_json",
+ "",
+ "$.steps[0].effects[0].compensation",
+ ),
+ (
+ "operation_steps",
+ "step_json",
+ " WHERE step_no=0",
+ "$.step.effects[0].compensation",
+ ),
+ ];
+ for (table, column, scope, path) in compensation_locations {
+ for corrupted in [
+ // Identical duplicate values must still fail.
+ r#"{"a":1,"a":1,"large":9223372036854775808,"z":[1,2]}"#,
+ r#"{"a":1,"\u0061":1,"large":9223372036854775808,"z":[1,2]}"#,
+ r#"{"a":1,"large":9223372036854775808,"z":[1,2],"unexpected":null}"#,
+ r#"{"a":1,"large":9223372036854775808,"z":[2,1]}"#,
+ r#"{"a":1.0,"large":9223372036854775808,"z":[1,2]}"#,
+ r#"{"a":1,"large":9223372036854775808}"#,
+ r#"{"a":1,"large":9223372036854775808,"z":null}"#,
+ r#"{"a":1,"large":9223372036854775809,"z":[1,2]}"#,
+ ] {
+ restore_copies(&control, &reordered);
+ control
+ .connection
+ .borrow()
+ .execute(
+ &format!(
+ "UPDATE {table} SET {column}=json_set({column}, '{path}', json(?1)){scope}"
+ ),
+ params![corrupted],
+ )
+ .unwrap();
+ assert!(
+ !control.operation_is_current(&recovered).unwrap(),
+ "{table}: {corrupted}"
+ );
+ }
+ }
+ for statement in [
+ "UPDATE operations SET operation_json=json_set(operation_json, '$.steps[0].unexpected', 1)",
+ "UPDATE operation_steps SET step_json=json_set(step_json, '$.step.unexpected', 1) WHERE step_no=0",
+ ] {
+ restore_copies(&control, &reordered);
+ control.connection.borrow().execute(statement, []).unwrap();
+ assert!(!control.operation_is_current(&recovered).unwrap());
+ }
+ restore_copies(&control, &reordered);
+ // SQLite and ordinary Value decoding can round these different numeric tokens alike.
+ // A quoted key also proves that comparison does not depend on SQLite's JSON-path parser.
+ for (number, changed_token) in [
+ (json!(u64::MAX), "18446744073709551614"),
+ (
+ json!(18_446_744_073_709_551_616.0_f64),
+ "18446744073709551616",
+ ),
+ (json!(1.0_f64), "1.00000000000000001"),
+ ] {
+ recovered.steps[0].effects[0].compensation = json!({"quoted\"number": number}).into();
+ control.save_operation(&mut recovered).unwrap();
+ assert!(control.operation_is_current(&recovered).unwrap());
+ let current = journal_copies(&control);
+ for (table, column, scope, path) in compensation_locations {
+ let corrupted = format!(r#"{{"quoted\"number":{changed_token}}}"#);
+ control
+ .connection
+ .borrow()
+ .execute(
+ &format!(
+ "UPDATE {table} SET {column}=json_set({column}, '{path}', json(?1)){scope}"
+ ),
+ params![corrupted],
+ )
+ .unwrap();
+ assert!(!control.operation_is_current(&recovered).unwrap());
+ restore_copies(&control, &current);
+ }
+ }
+ recovered.safe_error_code = Some("ORDER_RECOVERED".into());
+ control.save_operation(&mut recovered).unwrap();
+ assert!(control.operation_is_current(&recovered).unwrap());
+ let current_plan: String = control
+ .connection
+ .borrow()
+ .query_row(
+ "SELECT json_extract(operation_json, '$.plan') FROM operations",
+ [],
+ |r| r.get(0),
+ )
+ .unwrap();
+ assert_eq!(current_plan, immutable_plan);
+}
diff --git a/crates/local-storage/src/control/mod.rs b/crates/local-storage/src/control/mod.rs
index 65629e49..95b5e032 100644
--- a/crates/local-storage/src/control/mod.rs
+++ b/crates/local-storage/src/control/mod.rs
@@ -230,6 +230,7 @@ impl ControlStore {
path: &Path,
migration_backup_root: &Path,
expected_store_uuid: &str,
+ target_schema_version: u32,
) -> Result<Self, LocalStorageError> {
Ok(Self {
diagnostics: RefCell::new(Default::default()),
@@ -241,6 +242,7 @@ impl ControlStore {
migration_backup_root,
Some(expected_store_uuid),
None,
+ target_schema_version,
)?),
})
}
@@ -1694,10 +1696,10 @@ fn store_step(
operation: &OperationV1,
step: &OperationStepV1,
) -> PortResult<()> {
- let encoded = serde_json::to_string(&json!({
+ let encoded = serde_json::to_string(&hiroute_domain::canonicalize_json(json!({
"schema": "hiroute.operation-step/v1",
"step": step,
- }))
+ })))
.map_err(|_| port(PortErrorCode::InvalidData, "control.step.encode"))?;
transaction
.execute(
@@ -2009,7 +2011,9 @@ impl ManagedArtifactStore {
) -> Result<Self, LocalStorageError> {
let mut external_targets = BTreeMap::new();
for (target, path) in targets {
- validate_external_target_path(&path)?;
+ // Startup registers potential targets, including Agents never configured here.
+ // Native permissions are checked on use and for every durable recovery marker.
+ validate_external_target_location(&path)?;
if external_targets.contains_key(&target)
|| external_targets.values().any(|existing| existing == &path)
{
@@ -2032,11 +2036,8 @@ impl ManagedArtifactStore {
external_targets,
untouched_deletions: std::sync::Mutex::new(BTreeMap::new()),
};
- // Validate every durable marker only after its native path binding is present. This is
- // the restart-safe counterpart to bind_external_target, which is used before first Apply.
- for target in store.external_targets.keys() {
- let _ = store.target_path(target)?;
- }
+ // Register all exact bindings before validating the targets actually owned by markers.
+ // A never-managed Agent's directory cannot prevent unrelated service startup.
store.migrate_legacy_markers()?;
store.validate_existing_marker_bindings()?;
Ok(store)
@@ -2242,6 +2243,11 @@ impl ManagedArtifactStore {
{
return Err(LocalStorageError::Locked);
}
+ if self.external_targets.contains_key(&marker.target) {
+ // A durable effect is a real recovery consumer, not an unused registration.
+ // Validate before touching even a legacy marker's internal representation.
+ let _ = self.target_path(&marker.target)?;
+ }
let changed = match marker.schema.as_str() {
"hiroute.managed-artifact-marker/v2" => {
marker.backup_aad = if marker.backup_name.is_some() {
@@ -3003,14 +3009,20 @@ fn prepare_owner_directory(path: &Path) -> Result<(), LocalStorageError> {
Ok(())
}
-fn validate_external_target_path(path: &Path) -> Result<(), LocalStorageError> {
+fn validate_external_target_location(path: &Path) -> Result<(), LocalStorageError> {
if !path.is_absolute()
+ || path.parent().is_none()
|| path
.components()
.any(|component| matches!(component, Component::ParentDir | Component::CurDir))
{
return Err(LocalStorageError::InvalidData);
}
+ Ok(())
+}
+
+fn validate_external_target_path(path: &Path) -> Result<(), LocalStorageError> {
+ validate_external_target_location(path)?;
let parent = path.parent().ok_or(LocalStorageError::InvalidData)?;
native_directories::validate_parent(parent)?;
match fs::symlink_metadata(path) {
diff --git a/crates/local-storage/src/control/surface_check_tests.rs b/crates/local-storage/src/control/surface_check_tests.rs
index b6967e4f..56f655b6 100644
--- a/crates/local-storage/src/control/surface_check_tests.rs
+++ b/crates/local-storage/src/control/surface_check_tests.rs
@@ -59,6 +59,53 @@ fn storage() -> (tempfile::TempDir, ControlStore) {
(directory, control)
}
+#[test]
+fn all_supported_native_surfaces_persist_current_verification_independently() {
+ let (_directory, store) = storage();
+ let workspace = WorkspaceId::default();
+ activate(&store, &workspace, 2);
+ let revision = GatewayPublicationRevision::new(2).unwrap();
+ let surfaces = [
+ AgentModelSurfaceV2::CodexCli,
+ AgentModelSurfaceV2::CodexDesktop,
+ AgentModelSurfaceV2::ClaudeCli,
+ AgentModelSurfaceV2::QoderCli,
+ ];
+ for surface in surfaces {
+ assert!(
+ store
+ .save_agent_surface_check(
+ &workspace,
+ &record(revision, surface, AgentSurfaceCheckStateV1::Passed)
+ )
+ .unwrap()
+ );
+ }
+ assert_eq!(
+ store
+ .agent_surface_checks(&workspace, "agent-context/surface-check")
+ .unwrap()
+ .len(),
+ surfaces.len()
+ );
+ let failed = record(
+ revision,
+ AgentModelSurfaceV2::QoderCli,
+ AgentSurfaceCheckStateV1::Failed,
+ );
+ assert!(store.save_agent_surface_check(&workspace, &failed).unwrap());
+ let checks = store
+ .agent_surface_checks(&workspace, "agent-context/surface-check")
+ .unwrap();
+ assert_eq!(checks.len(), surfaces.len());
+ assert!(checks.iter().all(|check| check.state
+ == if check.surface == AgentModelSurfaceV2::QoderCli {
+ AgentSurfaceCheckStateV1::Failed
+ } else {
+ AgentSurfaceCheckStateV1::Passed
+ }));
+}
+
#[test]
fn current_revision_results_are_kept_and_overwritten_per_surface() {
let (_directory, store) = storage();
diff --git a/crates/local-storage/src/control/transaction_v2_tests.rs b/crates/local-storage/src/control/transaction_v2_tests.rs
index aef96951..06472780 100644
--- a/crates/local-storage/src/control/transaction_v2_tests.rs
+++ b/crates/local-storage/src/control/transaction_v2_tests.rs
@@ -1014,3 +1014,6 @@ fn current_operation_allows_only_the_committed_parked_settings_tail_without_a_wr
.unwrap();
assert!(!control.operation_is_current(&op).unwrap());
}
+
+#[path = "journal_order_tests.rs"]
+mod journal_order_tests;
diff --git a/crates/local-storage/src/control/worker_dependencies.rs b/crates/local-storage/src/control/worker_dependencies.rs
index 0a98a144..af4843bc 100644
--- a/crates/local-storage/src/control/worker_dependencies.rs
+++ b/crates/local-storage/src/control/worker_dependencies.rs
@@ -627,6 +627,7 @@ pub(super) const fn harness_key(harness: WorkerHarnessV1) -> &'static str {
match harness {
WorkerHarnessV1::CodexCli => "codex_cli",
WorkerHarnessV1::ClaudeCode => "claude_code",
+ WorkerHarnessV1::QoderCli => "qoder_cli",
}
}
@@ -634,6 +635,7 @@ fn parse_harness(value: &str) -> PortResult<WorkerHarnessV1> {
match value {
"codex_cli" => Ok(WorkerHarnessV1::CodexCli),
"claude_code" => Ok(WorkerHarnessV1::ClaudeCode),
+ "qoder_cli" => Ok(WorkerHarnessV1::QoderCli),
_ => Err(port(
PortErrorCode::Corrupt,
"control.worker_dependency.harness",
diff --git a/crates/local-storage/src/control/worker_dependencies_tests.rs b/crates/local-storage/src/control/worker_dependencies_tests.rs
index 2c57d90d..609af68d 100644
--- a/crates/local-storage/src/control/worker_dependencies_tests.rs
+++ b/crates/local-storage/src/control/worker_dependencies_tests.rs
@@ -15,9 +15,9 @@ fn change(
before_revision,
WorkerDependencySelectionRecordV1::new(
harness,
- format!("/opt/{suffix}/adapter.js"),
+ (harness != WorkerHarnessV1::QoderCli).then(|| format!("/opt/{suffix}/adapter.js")),
format!("/opt/{suffix}/cli"),
- Some(format!("/opt/{suffix}/node")),
+ (harness != WorkerHarnessV1::QoderCli).then(|| format!("/opt/{suffix}/node")),
)
.unwrap(),
)
@@ -32,6 +32,7 @@ fn selection_operation(
let harness = match change.after_selection.harness {
WorkerHarnessV1::CodexCli => "codex_cli",
WorkerHarnessV1::ClaudeCode => "claude_code",
+ WorkerHarnessV1::QoderCli => "qoder_cli",
};
let expected_revisions = RevisionSetV1 {
target: change.before_revision,
@@ -159,22 +160,25 @@ fn selection_stage_is_invisible_and_harness_revisions_are_independent_and_durabl
finish_succeeded(&store, &mut codex_operation);
completed_operations.push(codex_operation);
- let claude = change(WorkerHarnessV1::ClaudeCode, 0, "claude");
- let mut claude_operation = begin_selection(&store, &workspace, "claude", &claude);
- let claude_effect = store
- .stage_worker_dependency_selection(&claude_operation.operation_id, &workspace, &claude)
- .unwrap();
- store
- .activate_worker_dependency_selection(&claude_effect)
- .unwrap();
- assert_eq!(
- store
- .worker_dependency_selection_revision(&workspace, WorkerHarnessV1::ClaudeCode,)
- .unwrap(),
- 1
- );
- finish_succeeded(&store, &mut claude_operation);
- completed_operations.push(claude_operation);
+ for (harness, suffix) in [
+ (WorkerHarnessV1::ClaudeCode, "claude"),
+ (WorkerHarnessV1::QoderCli, "qoder"),
+ ] {
+ let selection = change(harness, 0, suffix);
+ let mut operation = begin_selection(&store, &workspace, suffix, &selection);
+ let effect = store
+ .stage_worker_dependency_selection(&operation.operation_id, &workspace, &selection)
+ .unwrap();
+ store.activate_worker_dependency_selection(&effect).unwrap();
+ assert_eq!(
+ store
+ .worker_dependency_selection(&workspace, harness)
+ .unwrap(),
+ Some((selection.after_selection, 1))
+ );
+ finish_succeeded(&store, &mut operation);
+ completed_operations.push(operation);
+ }
let stale = change(WorkerHarnessV1::CodexCli, 0, "stale");
let stale_operation = selection_operation(&workspace, "stale", &stale);
@@ -192,7 +196,11 @@ fn selection_stage_is_invisible_and_harness_revisions_are_independent_and_durabl
}
let reopened =
ControlStore::open(&crate::test_storage_authority(), &database, &backups).unwrap();
- for harness in [WorkerHarnessV1::CodexCli, WorkerHarnessV1::ClaudeCode] {
+ for harness in [
+ WorkerHarnessV1::CodexCli,
+ WorkerHarnessV1::ClaudeCode,
+ WorkerHarnessV1::QoderCli,
+ ] {
let (_, revision) = reopened
.worker_dependency_selection(&workspace, harness)
.unwrap()
diff --git a/crates/local-storage/src/lib.rs b/crates/local-storage/src/lib.rs
index 180820ab..cd62fce8 100644
--- a/crates/local-storage/src/lib.rs
+++ b/crates/local-storage/src/lib.rs
@@ -124,6 +124,7 @@ impl LocalStorageSet {
&backup_root,
secret_binding.as_ref(),
)?;
+ let target_schema_version = migration.target_schema_version();
let control_result = if migration.durable_set_prepared() {
ControlStore::open_from_migration_set(
authority,
@@ -132,6 +133,7 @@ impl LocalStorageSet {
migration
.expected_control_store_uuid()
.ok_or(LocalStorageError::InvalidData)?,
+ target_schema_version,
)
} else {
ControlStore::open(authority, &control_path, &backup_root)
@@ -157,6 +159,7 @@ impl LocalStorageSet {
migration
.expected_runtime_store_uuid()
.ok_or(LocalStorageError::InvalidData)?,
+ target_schema_version,
)
} else {
RuntimeStore::open(authority, &runtime_path, &backup_root)
@@ -183,6 +186,7 @@ impl LocalStorageSet {
&master_key_path,
&backup_root,
secret_binding.as_ref().ok_or(LocalStorageError::Locked)?,
+ target_schema_version,
)
} else {
LocalSecretStore::open(authority, &secrets_path, &master_key_path, &backup_root)
@@ -219,6 +223,17 @@ impl LocalStorageSet {
migration.restore_after_failure(barrier, &live_root)?;
return Err(error);
}
+ if target_schema_version < migrations::LATEST_SCHEMA_VERSION {
+ // A prior binary's accepted batch must finish under its own target and backup.
+ // Keep the startup lock while reopening: prepare archives that completed batch
+ // and publishes a fresh source backup for the current version. Admission opens
+ // only after the current batch also completes.
+ drop(secrets);
+ drop(runtime);
+ drop(control);
+ drop(migration);
+ return Self::open_locked_stores(authority, barrier, storage_root, startup_lock);
+ }
control.startup_lock = Some(startup_lock.clone());
runtime.startup_lock = Some(startup_lock.clone());
secrets.startup_lock = Some(startup_lock);
diff --git a/crates/local-storage/src/migrations/agent_surface_checks_v25.rs b/crates/local-storage/src/migrations/agent_surface_checks_v25.rs
new file mode 100644
index 00000000..3bbaee51
--- /dev/null
+++ b/crates/local-storage/src/migrations/agent_surface_checks_v25.rs
@@ -0,0 +1,20 @@
+//! Add Qoder model verification while retaining existing result bytes and revision authority.
+
+pub(super) const CONTROL: &str = r#"
+CREATE TABLE agent_surface_checks_v25 (
+ workspace_id TEXT NOT NULL,
+ context_id TEXT NOT NULL,
+ surface TEXT NOT NULL
+ CHECK(surface IN ('codex_cli','codex_desktop','claude_cli','qoder_cli')),
+ applied_revision INTEGER NOT NULL
+ CHECK(typeof(applied_revision) = 'integer' AND applied_revision > 0),
+ record_json TEXT NOT NULL,
+ updated_at INTEGER NOT NULL,
+ PRIMARY KEY(workspace_id, context_id, surface)
+);
+INSERT INTO agent_surface_checks_v25
+ SELECT workspace_id, context_id, surface, applied_revision, record_json, updated_at
+ FROM agent_surface_checks;
+DROP TABLE agent_surface_checks;
+ALTER TABLE agent_surface_checks_v25 RENAME TO agent_surface_checks;
+"#;
diff --git a/crates/local-storage/src/migrations/agent_surface_checks_v25_tests.rs b/crates/local-storage/src/migrations/agent_surface_checks_v25_tests.rs
new file mode 100644
index 00000000..1802d49d
--- /dev/null
+++ b/crates/local-storage/src/migrations/agent_surface_checks_v25_tests.rs
@@ -0,0 +1,61 @@
+//! Historical SQL layout evidence, not a synthetic native model-call receipt.
+use super::*;
+use crate::LocalStorageSet;
+
+fn rows(connection: &Connection) -> Vec<(String, String, String, i64, String, i64)> {
+ connection.prepare("SELECT workspace_id, context_id, surface, applied_revision, record_json, updated_at FROM agent_surface_checks ORDER BY surface")
+ .unwrap().query_map([], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?, row.get(4)?, row.get(5)?)))
+ .unwrap().map(Result::unwrap).collect()
+}
+
+#[test]
+fn schema24_surface_upgrade_preserves_raw_results_and_existing_key() {
+ let directory = crate::test_tempdir().unwrap();
+ let root = directory.path().join("storage");
+ drop(LocalStorageSet::open_for_daemon_startup(&root).unwrap());
+ let mut expected = Vec::new();
+ for path in live_database_paths(&root.join("live")) {
+ let connection = Connection::open(&path).unwrap();
+ if path.file_name().unwrap() == "control.db" {
+ connection
+ .execute_batch("DROP TABLE agent_surface_checks")
+ .unwrap();
+ connection
+ .execute_batch(agent_surface_checks_v22::CONTROL)
+ .unwrap();
+ for surface in ["codex_cli", "codex_desktop", "claude_cli"] {
+ // Opaque historical bytes intentionally do not use the current record serializer.
+ let raw =
+ format!(" {{ \"historical_surface\" : \"{surface}\", \"opaque\" : [ ] }}\n");
+ connection.execute("INSERT INTO agent_surface_checks VALUES ('personal/default', 'historical/context', ?1, 7, ?2, 123)", params![surface, raw]).unwrap();
+ }
+ expected = rows(&connection);
+ }
+ connection
+ .execute("DELETE FROM schema_migrations WHERE version > 24", [])
+ .unwrap();
+ connection.pragma_update(None, "user_version", 24).unwrap();
+ }
+ let key = fs::read(root.join("master-key")).unwrap();
+ let stores = LocalStorageSet::open_for_daemon_startup(&root).unwrap();
+ assert_eq!(fs::read(root.join("master-key")).unwrap(), key);
+ stores.control().with_connection(|connection| {
+ assert_eq!(rows(connection), expected);
+ // Only the named new surface is admitted; the storage constraint remains closed.
+ connection.execute("INSERT INTO agent_surface_checks VALUES ('personal/default', 'new/context', 'qoder_cli', 8, '{}', 124)", []).unwrap();
+ assert!(connection.execute("INSERT INTO agent_surface_checks VALUES ('personal/default', 'new/context', 'unknown_cli', 8, '{}', 124)", []).is_err());
+ connection.execute("DELETE FROM agent_surface_checks WHERE context_id='new/context'", []).unwrap();
+ assert_eq!(rows(connection), expected);
+ });
+ drop(stores);
+ let reopened = LocalStorageSet::open_for_daemon_startup(&root).unwrap();
+ reopened
+ .control()
+ .with_connection(|connection| assert_eq!(rows(connection), expected));
+ for path in live_database_paths(&root.join("live")) {
+ assert_eq!(
+ database_version(&path).unwrap(),
+ Some(LATEST_SCHEMA_VERSION)
+ );
+ }
+}
diff --git a/crates/local-storage/src/migrations/completed_batches.rs b/crates/local-storage/src/migrations/completed_batches.rs
index 83c30637..b7606ee8 100644
--- a/crates/local-storage/src/migrations/completed_batches.rs
+++ b/crates/local-storage/src/migrations/completed_batches.rs
@@ -5,7 +5,7 @@ pub(super) fn archive_if_needed(
previous: &BackupSet,
paths: &[PathBuf; 3],
backup_root: &Path,
- _secret_binding: Option<&MigrationSecretBinding>,
+ secret_binding: Option<&MigrationSecretBinding>,
) -> Result<(), LocalStorageError> {
if previous.phase() != BackupSetPhase::Completed
|| previous.target_schema_version() > LATEST_SCHEMA_VERSION
@@ -26,6 +26,17 @@ pub(super) fn archive_if_needed(
{
return Err(LocalStorageError::InvalidData);
}
+ let binding = secret_binding.ok_or(LocalStorageError::Locked)?;
+ if previous.secrets.manifest().key_id.as_deref() != Some(binding.key_id.as_str()) {
+ return Err(LocalStorageError::InvalidData);
+ }
+ validate_live_set(
+ previous,
+ paths,
+ &target_store_uuid(previous, DatabaseKind::Control),
+ &target_store_uuid(previous, DatabaseKind::Runtime),
+ binding,
+ )?;
let parent = backup_root.parent().ok_or(LocalStorageError::InvalidData)?;
let archived = parent.join(format!("migration-set.{}", previous.set_id()));
match fs::symlink_metadata(&archived) {
diff --git a/crates/local-storage/src/migrations/convergence_tests.rs b/crates/local-storage/src/migrations/convergence_tests.rs
index 2f5d3dd4..5cd040a4 100644
--- a/crates/local-storage/src/migrations/convergence_tests.rs
+++ b/crates/local-storage/src/migrations/convergence_tests.rs
@@ -71,7 +71,7 @@ fn both_frozen_v14_shapes_upgrade_without_losing_their_applied_history() {
Path::new("unused-backups"),
None,
None,
- true,
+ Some(LATEST_SCHEMA_VERSION),
)
.unwrap();
diff --git a/crates/local-storage/src/migrations/fixtures/README.md b/crates/local-storage/src/migrations/fixtures/README.md
new file mode 100644
index 00000000..ebcec53c
--- /dev/null
+++ b/crates/local-storage/src/migrations/fixtures/README.md
@@ -0,0 +1,36 @@
+# Stable schema 23 Worker journal fixture
+
+`schema23-worker-operations.json` is frozen output from the original schema 23
+producer at `cdbb2cec` (product code identical to `c509481d`). The one-shot exporter
+is commit `5d8306cc`, based directly on that producer. It was run with:
+
+```text
+cargo test --locked -p hiroute-local-storage --lib export_schema23_worker_operations -- --ignored --nocapture
+```
+
+Managed run: `3724c06e070e4d00bd51bab284c8ab49`, green. Exact exporter:
+`5d8306cc2f9ce5e95d79657e4d406cfd9e1ca062`. Fixture SHA-256:
+`1886b84980aab4ddb7b3cd9ed21da0a654b13474e448f02883a233dc312d043f`.
+
+The exporter opened the production `LocalStorageSet`, admitted real Worker
+selection Operations and saved their effects and step journals through the old
+storage API. It exported the exact SQL row values for Codex and Claude at staged,
+activated and succeeded checkpoints, with a prior successful selection. It did
+not export keys, authentication material or user data. Timestamps are original
+synthetic-run values and are deliberately not normalized.
+
+The current test reconstructs the published v20 Worker tables and schema 23
+version/marker, inserts these frozen rows verbatim, then enters production
+startup. Fresh keys and store identities are generated per test. This isolates
+the actual historical contract from the current serializer while keeping the
+fixture independent of machines and credentials.
+
+Read `worker_dependencies_v24_tests.rs` for the user-visible invariants: old
+Operations remain replayable, activation does not increment a revision twice,
+compensation respects the current owner, interrupted upgrades require the exact
+backup set, and completed backups survive the next upgrade batch. The ordinary
+current-format selection test also covers the Qoder single-CLI form.
+
+Do not regenerate this fixture from the new producer to make a failing migration
+pass. Its removal requires an explicit end to schema 23 upgrade support, retaining
+a documented supported recovery path.
diff --git a/crates/local-storage/src/migrations/fixtures/schema23-worker-operations.json b/crates/local-storage/src/migrations/fixtures/schema23-worker-operations.json
new file mode 100644
index 00000000..d899f4ac
--- /dev/null
+++ b/crates/local-storage/src/migrations/fixtures/schema23-worker-operations.json
@@ -0,0 +1,1464 @@
+{
+ "cases": [
+ {
+ "effect": {
+ "after_fingerprint": "sha256:56fd8be01787e9003143ba94d003b4650ba9f2d51da44724534f85869b49349d",
+ "before_fingerprint": "sha256:a0187c2271bab58183319337b972c299cf37491a86823664cfc68b625759dbea",
+ "compensation": {
+ "after_revision": 2,
+ "operation_id": "op_b11607ab48bae8c308337e49c24b6014",
+ "schema": "hiroute.worker-dependency-selection-compensation/v1"
+ },
+ "effect_id": "worker-dependency-selection:codex_cli",
+ "kind": "control",
+ "target": "personal/default/worker-dependency-selection/codex_cli"
+ },
+ "harness": "codex_cli",
+ "operation_id": "op_b11607ab48bae8c308337e49c24b6014",
+ "previous_effect": {
+ "after_fingerprint": "sha256:a0187c2271bab58183319337b972c299cf37491a86823664cfc68b625759dbea",
+ "compensation": {
+ "after_revision": 1,
+ "operation_id": "op_eae94ac62ab719efa325df7f93567385",
+ "schema": "hiroute.worker-dependency-selection-compensation/v1"
+ },
+ "effect_id": "worker-dependency-selection:codex_cli",
+ "kind": "control",
+ "target": "personal/default/worker-dependency-selection/codex_cli"
+ },
+ "stage": "staged",
+ "tables": {
+ "operation_steps": {
+ "columns": [
+ "operation_id",
+ "step_no",
+ "step_kind",
+ "state",
+ "step_json"
+ ],
+ "rows": [
+ [
+ "op_b11607ab48bae8c308337e49c24b6014",
+ 0,
+ "prepare",
+ "applied",
+ "{\"schema\":\"hiroute.operation-step/v1\",\"step\":{\"attempts\":1,\"deterministic_input_digest\":\"sha256:6b273ac3806ed5ad22337748ea95303cc01ae0d310e9858231381bc73d2fa2ff\",\"effects\":[],\"kind\":\"prepare\",\"sequence\":0,\"status\":\"applied\"}}"
+ ],
+ [
+ "op_b11607ab48bae8c308337e49c24b6014",
+ 1,
+ "apply_secrets",
+ "applied",
+ "{\"schema\":\"hiroute.operation-step/v1\",\"step\":{\"attempts\":1,\"deterministic_input_digest\":\"sha256:75f16a5c021b74501c720d197122fe1e672dc27c9025d026d257aad66e6561b4\",\"effects\":[],\"kind\":\"apply_secrets\",\"sequence\":1,\"status\":\"applied\"}}"
+ ],
+ [
+ "op_b11607ab48bae8c308337e49c24b6014",
+ 2,
+ "materialize_sources",
+ "applied",
+ "{\"schema\":\"hiroute.operation-step/v1\",\"step\":{\"attempts\":1,\"deterministic_input_digest\":\"sha256:2ee7eb2fa88af2075cda8d982130d3573cd234ff240025861129f7cb9663ce91\",\"effects\":[{\"after_fingerprint\":\"sha256:56fd8be01787e9003143ba94d003b4650ba9f2d51da44724534f85869b49349d\",\"before_fingerprint\":\"sha256:a0187c2271bab58183319337b972c299cf37491a86823664cfc68b625759dbea\",\"compensation\":{\"after_revision\":2,\"operation_id\":\"op_b11607ab48bae8c308337e49c24b6014\",\"schema\":\"hiroute.worker-dependency-selection-compensation/v1\"},\"effect_id\":\"worker-dependency-selection:codex_cli\",\"kind\":\"control\",\"target\":\"personal/default/worker-dependency-selection/codex_cli\"}],\"kind\":\"materialize_sources\",\"sequence\":2,\"status\":\"applied\"}}"
+ ],
+ [
+ "op_b11607ab48bae8c308337e49c24b6014",
+ 3,
+ "compile_publication",
+ "pending",
+ "{\"schema\":\"hiroute.operation-step/v1\",\"step\":{\"attempts\":0,\"deterministic_input_digest\":\"sha256:c9171635fed9ca419452391118a4de7a2afe2190f23346129db8cd0fad57e365\",\"effects\":[],\"kind\":\"compile_publication\",\"sequence\":3,\"status\":\"pending\"}}"
+ ],
+ [
+ "op_b11607ab48bae8c308337e49c24b6014",
+ 4,
+ "apply_agent_artifacts",
+ "pending",
+ "{\"schema\":\"hiroute.operation-step/v1\",\"step\":{\"attempts\":0,\"deterministic_input_digest\":\"sha256:5ac4612884ca3ffb3894cdd5bfa06ddfa853f083ca2bdf5605db6cc1f6922b51\",\"effects\":[],\"kind\":\"apply_agent_artifacts\",\"sequence\":4,\"status\":\"pending\"}}"
+ ],
+ [
+ "op_b11607ab48bae8c308337e49c24b6014",
+ 5,
+ "activate",
+ "pending",
+ "{\"schema\":\"hiroute.operation-step/v1\",\"step\":{\"attempts\":0,\"deterministic_input_digest\":\"sha256:e522a4f844eb520088412ae184c9dc4b0cc2c8ca509e02b8c269b8eda7c1ae8b\",\"effects\":[],\"kind\":\"activate\",\"sequence\":5,\"status\":\"pending\"}}"
+ ],
+ [
+ "op_eae94ac62ab719efa325df7f93567385",
+ 0,
+ "prepare",
+ "applied",
+ "{\"schema\":\"hiroute.operation-step/v1\",\"step\":{\"attempts\":1,\"deterministic_input_digest\":\"sha256:89568ed74e77d437891b2a969be85acc4097ef4de75807a265d3464a364b16a9\",\"effects\":[],\"kind\":\"prepare\",\"sequence\":0,\"status\":\"applied\"}}"
+ ],
+ [
+ "op_eae94ac62ab719efa325df7f93567385",
+ 1,
+ "apply_secrets",
+ "applied",
+ "{\"schema\":\"hiroute.operation-step/v1\",\"step\":{\"attempts\":1,\"deterministic_input_digest\":\"sha256:75f16a5c021b74501c720d197122fe1e672dc27c9025d026d257aad66e6561b4\",\"effects\":[],\"kind\":\"apply_secrets\",\"sequence\":1,\"status\":\"applied\"}}"
+ ],
+ [
+ "op_eae94ac62ab719efa325df7f93567385",
+ 2,
+ "materialize_sources",
+ "applied",
+ "{\"schema\":\"hiroute.operation-step/v1\",\"step\":{\"attempts\":1,\"deterministic_input_digest\":\"sha256:2eaa42f80de54f3cc89eb18e6956fd90f59b6d6f37b6adc085cf632e1f61c6e9\",\"effects\":[{\"after_fingerprint\":\"sha256:a0187c2271bab58183319337b972c299cf37491a86823664cfc68b625759dbea\",\"compensation\":{\"after_revision\":1,\"operation_id\":\"op_eae94ac62ab719efa325df7f93567385\",\"schema\":\"hiroute.worker-dependency-selection-compensation/v1\"},\"effect_id\":\"worker-dependency-selection:codex_cli\",\"kind\":\"control\",\"target\":\"personal/default/worker-dependency-selection/codex_cli\"}],\"kind\":\"materialize_sources\",\"sequence\":2,\"status\":\"applied\"}}"
+ ],
+ [
+ "op_eae94ac62ab719efa325df7f93567385",
+ 3,
+ "compile_publication",
+ "applied",
+ "{\"schema\":\"hiroute.operation-step/v1\",\"step\":{\"attempts\":1,\"deterministic_input_digest\":\"sha256:c9171635fed9ca419452391118a4de7a2afe2190f23346129db8cd0fad57e365\",\"effects\":[],\"kind\":\"compile_publication\",\"sequence\":3,\"status\":\"applied\"}}"
+ ],
+ [
+ "op_eae94ac62ab719efa325df7f93567385",
+ 4,
+ "apply_agent_artifacts",
+ "applied",
+ "{\"schema\":\"hiroute.operation-step/v1\",\"step\":{\"attempts\":1,\"deterministic_input_digest\":\"sha256:5ac4612884ca3ffb3894cdd5bfa06ddfa853f083ca2bdf5605db6cc1f6922b51\",\"effects\":[],\"kind\":\"apply_agent_artifacts\",\"sequence\":4,\"status\":\"applied\"}}"
+ ],
+ [
+ "op_eae94ac62ab719efa325df7f93567385",
+ 5,
+ "activate",
+ "applied",
+ "{\"schema\":\"hiroute.operation-step/v1\",\"step\":{\"attempts\":1,\"deterministic_input_digest\":\"sha256:e522a4f844eb520088412ae184c9dc4b0cc2c8ca509e02b8c269b8eda7c1ae8b\",\"effects\":[],\"kind\":\"activate\",\"sequence\":5,\"status\":\"applied\"}}"
+ ]
+ ]
+ },
+ "operations": {
+ "columns": [
+ "operation_id",
+ "workspace_id",
+ "principal",
+ "operation_kind",
+ "idempotency_key",
+ "request_digest",
+ "accepted_change_digest",
+ "state",
+ "generation",
+ "operation_json",
+ "created_at",
+ "updated_at"
+ ],
+ "rows": [
+ [
+ "op_b11607ab48bae8c308337e49c24b6014",
+ "personal/default",
+ "interactive-user",
+ "SelectWorkerDependencies",
+ "staged",
+ "sha256:5f8cf78eaa6755b91fa931df07923db354c59b2288551ff143ea4128077e7701",
+ "sha256:60d940201528a762c1c879bcf8321c7376795f1ff5f9c91f84ff04c21347a7b8",
+ "materializing_sources",
+ 1,
+ "{\"schema_version\":2,\"operation_id\":\"op_b11607ab48bae8c308337e49c24b6014\",\"workspace_id\":\"personal/default\",\"idempotency\":{\"principal\":\"interactive-user\",\"operation_kind\":\"SelectWorkerDependencies\",\"key\":\"staged\"},\"request_digest\":\"sha256:5f8cf78eaa6755b91fa931df07923db354c59b2288551ff143ea4128077e7701\",\"accepted_digest\":\"sha256:60d940201528a762c1c879bcf8321c7376795f1ff5f9c91f84ff04c21347a7b8\",\"expected_revisions\":{\"target\":1},\"plan\":{\"control\":{},\"credential_pool\":null,\"external\":[],\"runtime\":[],\"schema\":\"hiroute.operation-input/v1\",\"secrets\":[],\"spec\":{\"command_id\":\"worker.dependencies.select\",\"desired_state\":{\"adapter_path\":\"/opt/new-installation/adapter.js\",\"cli_path\":\"/opt/new-installation/cli\",\"harness\":\"codex_cli\",\"node_path\":\"/opt/new-installation/node\"},\"resource_id\":\"worker-dependency-selection/codex_cli\",\"schema_version\":{\"major\":1,\"minor\":0}},\"worker_dependency_selection\":{\"after_selection\":{\"adapter_path\":\"/opt/new-installation/adapter.js\",\"cli_path\":\"/opt/new-installation/cli\",\"harness\":\"codex_cli\",\"node_path\":\"/opt/new-installation/node\"},\"before_revision\":1}},\"state\":\"materializing_sources\",\"generation\":1,\"steps\":[{\"sequence\":0,\"kind\":\"prepare\",\"deterministic_input_digest\":\"sha256:6b273ac3806ed5ad22337748ea95303cc01ae0d310e9858231381bc73d2fa2ff\",\"status\":\"applied\",\"attempts\":1,\"effects\":[]},{\"sequence\":1,\"kind\":\"apply_secrets\",\"deterministic_input_digest\":\"sha256:75f16a5c021b74501c720d197122fe1e672dc27c9025d026d257aad66e6561b4\",\"status\":\"applied\",\"attempts\":1,\"effects\":[]},{\"sequence\":2,\"kind\":\"materialize_sources\",\"deterministic_input_digest\":\"sha256:2ee7eb2fa88af2075cda8d982130d3573cd234ff240025861129f7cb9663ce91\",\"status\":\"applied\",\"attempts\":1,\"effects\":[{\"effect_id\":\"worker-dependency-selection:codex_cli\",\"kind\":\"control\",\"target\":\"personal/default/worker-dependency-selection/codex_cli\",\"before_fingerprint\":\"sha256:a0187c2271bab58183319337b972c299cf37491a86823664cfc68b625759dbea\",\"after_fingerprint\":\"sha256:56fd8be01787e9003143ba94d003b4650ba9f2d51da44724534f85869b49349d\",\"compensation\":{\"after_revision\":2,\"operation_id\":\"op_b11607ab48bae8c308337e49c24b6014\",\"schema\":\"hiroute.worker-dependency-selection-compensation/v1\"}}]},{\"sequence\":3,\"kind\":\"compile_publication\",\"deterministic_input_digest\":\"sha256:c9171635fed9ca419452391118a4de7a2afe2190f23346129db8cd0fad57e365\",\"status\":\"pending\",\"attempts\":0,\"effects\":[]},{\"sequence\":4,\"kind\":\"apply_agent_artifacts\",\"deterministic_input_digest\":\"sha256:5ac4612884ca3ffb3894cdd5bfa06ddfa853f083ca2bdf5605db6cc1f6922b51\",\"status\":\"pending\",\"attempts\":0,\"effects\":[]},{\"sequence\":5,\"kind\":\"activate\",\"deterministic_input_digest\":\"sha256:e522a4f844eb520088412ae184c9dc4b0cc2c8ca509e02b8c269b8eda7c1ae8b\",\"status\":\"pending\",\"attempts\":0,\"effects\":[]}],\"safe_error_code\":null}",
+ 1791051525,
+ 1791051525
+ ],
+ [
+ "op_eae94ac62ab719efa325df7f93567385",
+ "personal/default",
+ "interactive-user",
+ "SelectWorkerDependencies",
+ "before",
+ "sha256:6e7a07e13ebfac57bd3b26c1420041a565e0494f7419773bf83d498fb15b93ba",
+ "sha256:059abecbcf3998f101f54fb071df49052efda401f0fc1bbfa776a9acb28e9119",
+ "succeeded",
+ 1,
+ "{\"schema_version\":2,\"operation_id\":\"op_eae94ac62ab719efa325df7f93567385\",\"workspace_id\":\"personal/default\",\"idempotency\":{\"principal\":\"interactive-user\",\"operation_kind\":\"SelectWorkerDependencies\",\"key\":\"before\"},\"request_digest\":\"sha256:6e7a07e13ebfac57bd3b26c1420041a565e0494f7419773bf83d498fb15b93ba\",\"accepted_digest\":\"sha256:059abecbcf3998f101f54fb071df49052efda401f0fc1bbfa776a9acb28e9119\",\"expected_revisions\":{\"target\":0},\"plan\":{\"control\":{},\"credential_pool\":null,\"external\":[],\"runtime\":[],\"schema\":\"hiroute.operation-input/v1\",\"secrets\":[],\"spec\":{\"command_id\":\"worker.dependencies.select\",\"desired_state\":{\"adapter_path\":\"/opt/old-installation/adapter.js\",\"cli_path\":\"/opt/old-installation/cli\",\"harness\":\"codex_cli\",\"node_path\":\"/opt/old-installation/node\"},\"resource_id\":\"worker-dependency-selection/codex_cli\",\"schema_version\":{\"major\":1,\"minor\":0}},\"worker_dependency_selection\":{\"after_selection\":{\"adapter_path\":\"/opt/old-installation/adapter.js\",\"cli_path\":\"/opt/old-installation/cli\",\"harness\":\"codex_cli\",\"node_path\":\"/opt/old-installation/node\"},\"before_revision\":0}},\"state\":\"succeeded\",\"generation\":1,\"steps\":[{\"sequence\":0,\"kind\":\"prepare\",\"deterministic_input_digest\":\"sha256:89568ed74e77d437891b2a969be85acc4097ef4de75807a265d3464a364b16a9\",\"status\":\"applied\",\"attempts\":1,\"effects\":[]},{\"sequence\":1,\"kind\":\"apply_secrets\",\"deterministic_input_digest\":\"sha256:75f16a5c021b74501c720d197122fe1e672dc27c9025d026d257aad66e6561b4\",\"status\":\"applied\",\"attempts\":1,\"effects\":[]},{\"sequence\":2,\"kind\":\"materialize_sources\",\"deterministic_input_digest\":\"sha256:2eaa42f80de54f3cc89eb18e6956fd90f59b6d6f37b6adc085cf632e1f61c6e9\",\"status\":\"applied\",\"attempts\":1,\"effects\":[{\"effect_id\":\"worker-dependency-selection:codex_cli\",\"kind\":\"control\",\"target\":\"personal/default/worker-dependency-selection/codex_cli\",\"after_fingerprint\":\"sha256:a0187c2271bab58183319337b972c299cf37491a86823664cfc68b625759dbea\",\"compensation\":{\"after_revision\":1,\"operation_id\":\"op_eae94ac62ab719efa325df7f93567385\",\"schema\":\"hiroute.worker-dependency-selection-compensation/v1\"}}]},{\"sequence\":3,\"kind\":\"compile_publication\",\"deterministic_input_digest\":\"sha256:c9171635fed9ca419452391118a4de7a2afe2190f23346129db8cd0fad57e365\",\"status\":\"applied\",\"attempts\":1,\"effects\":[]},{\"sequence\":4,\"kind\":\"apply_agent_artifacts\",\"deterministic_input_digest\":\"sha256:5ac4612884ca3ffb3894cdd5bfa06ddfa853f083ca2bdf5605db6cc1f6922b51\",\"status\":\"applied\",\"attempts\":1,\"effects\":[]},{\"sequence\":5,\"kind\":\"activate\",\"deterministic_input_digest\":\"sha256:e522a4f844eb520088412ae184c9dc4b0cc2c8ca509e02b8c269b8eda7c1ae8b\",\"status\":\"applied\",\"attempts\":1,\"effects\":[]}],\"safe_error_code\":null}",
+ 1791051525,
+ 1791051525
+ ]
+ ]
+ },
+ "worker_dependency_selection_effects": {
+ "columns": [
+ "operation_id",
+ "workspace_id",
+ "harness",
+ "before_revision",
+ "before_json",
+ "before_owner_operation_id",
+ "after_revision",
+ "after_json",
+ "activated",
+ "compensated"
+ ],
+ "rows": [
+ [
+ "op_b11607ab48bae8c308337e49c24b6014",
+ "personal/default",
+ "codex_cli",
+ 1,
+ "{\"harness\":\"codex_cli\",\"adapter_path\":\"/opt/old-installation/adapter.js\",\"cli_path\":\"/opt/old-installation/cli\",\"node_path\":\"/opt/old-installation/node\"}",
+ "op_eae94ac62ab719efa325df7f93567385",
+ 2,
+ "{\"harness\":\"codex_cli\",\"adapter_path\":\"/opt/new-installation/adapter.js\",\"cli_path\":\"/opt/new-installation/cli\",\"node_path\":\"/opt/new-installation/node\"}",
+ 0,
+ 0
+ ],
+ [
+ "op_eae94ac62ab719efa325df7f93567385",
+ "personal/default",
+ "codex_cli",
+ 0,
+ null,
+ null,
+ 1,
+ "{\"harness\":\"codex_cli\",\"adapter_path\":\"/opt/old-installation/adapter.js\",\"cli_path\":\"/opt/old-installation/cli\",\"node_path\":\"/opt/old-installation/node\"}",
+ 1,
+ 0
+ ]
+ ]
+ },
+ "worker_dependency_selections": {
+ "columns": [
+ "workspace_id",
+ "harness",
+ "revision",
+ "selection_json",
+ "owner_operation_id",
+ "updated_at"
+ ],
+ "rows": [
+ [
+ "personal/default",
+ "codex_cli",
+ 1,
+ "{\"harness\":\"codex_cli\",\"adapter_path\":\"/opt/old-installation/adapter.js\",\"cli_path\":\"/opt/old-installation/cli\",\"node_path\":\"/opt/old-installation/node\"}",
+ "op_eae94ac62ab719efa325df7f93567385",
+ 1791051525
+ ]
+ ]
+ },
+ "writer_claim": {
+ "columns": [
+ "singleton",
+ "operation_id",
+ "admitted_at"
+ ],
+ "rows": [
+ [
+ 1,
+ "op_b11607ab48bae8c308337e49c24b6014",
+ 1791051525
+ ]
+ ]
+ }
+ }
+ },
+ {
+ "effect": {
+ "after_fingerprint": "sha256:56fd8be01787e9003143ba94d003b4650ba9f2d51da44724534f85869b49349d",
+ "before_fingerprint": "sha256:a0187c2271bab58183319337b972c299cf37491a86823664cfc68b625759dbea",
+ "compensation": {
+ "after_revision": 2,
+ "operation_id": "op_3824e5057bdb23d4b2bf76685d797b4e",
+ "schema": "hiroute.worker-dependency-selection-compensation/v1"
+ },
+ "effect_id": "worker-dependency-selection:codex_cli",
+ "kind": "control",
+ "target": "personal/default/worker-dependency-selection/codex_cli"
+ },
+ "harness": "codex_cli",
+ "operation_id": "op_3824e5057bdb23d4b2bf76685d797b4e",
+ "previous_effect": {
+ "after_fingerprint": "sha256:a0187c2271bab58183319337b972c299cf37491a86823664cfc68b625759dbea",
+ "compensation": {
+ "after_revision": 1,
+ "operation_id": "op_eae94ac62ab719efa325df7f93567385",
+ "schema": "hiroute.worker-dependency-selection-compensation/v1"
+ },
+ "effect_id": "worker-dependency-selection:codex_cli",
+ "kind": "control",
+ "target": "personal/default/worker-dependency-selection/codex_cli"
+ },
+ "stage": "activated",
+ "tables": {
+ "operation_steps": {
+ "columns": [
+ "operation_id",
+ "step_no",
+ "step_kind",
+ "state",
+ "step_json"
+ ],
+ "rows": [
+ [
+ "op_3824e5057bdb23d4b2bf76685d797b4e",
+ 0,
+ "prepare",
+ "applied",
+ "{\"schema\":\"hiroute.operation-step/v1\",\"step\":{\"attempts\":1,\"deterministic_input_digest\":\"sha256:6b273ac3806ed5ad22337748ea95303cc01ae0d310e9858231381bc73d2fa2ff\",\"effects\":[],\"kind\":\"prepare\",\"sequence\":0,\"status\":\"applied\"}}"
+ ],
+ [
+ "op_3824e5057bdb23d4b2bf76685d797b4e",
+ 1,
+ "apply_secrets",
+ "applied",
+ "{\"schema\":\"hiroute.operation-step/v1\",\"step\":{\"attempts\":1,\"deterministic_input_digest\":\"sha256:75f16a5c021b74501c720d197122fe1e672dc27c9025d026d257aad66e6561b4\",\"effects\":[],\"kind\":\"apply_secrets\",\"sequence\":1,\"status\":\"applied\"}}"
+ ],
+ [
+ "op_3824e5057bdb23d4b2bf76685d797b4e",
+ 2,
+ "materialize_sources",
+ "applied",
+ "{\"schema\":\"hiroute.operation-step/v1\",\"step\":{\"attempts\":1,\"deterministic_input_digest\":\"sha256:2ee7eb2fa88af2075cda8d982130d3573cd234ff240025861129f7cb9663ce91\",\"effects\":[{\"after_fingerprint\":\"sha256:56fd8be01787e9003143ba94d003b4650ba9f2d51da44724534f85869b49349d\",\"before_fingerprint\":\"sha256:a0187c2271bab58183319337b972c299cf37491a86823664cfc68b625759dbea\",\"compensation\":{\"after_revision\":2,\"operation_id\":\"op_3824e5057bdb23d4b2bf76685d797b4e\",\"schema\":\"hiroute.worker-dependency-selection-compensation/v1\"},\"effect_id\":\"worker-dependency-selection:codex_cli\",\"kind\":\"control\",\"target\":\"personal/default/worker-dependency-selection/codex_cli\"}],\"kind\":\"materialize_sources\",\"sequence\":2,\"status\":\"applied\"}}"
+ ],
+ [
+ "op_3824e5057bdb23d4b2bf76685d797b4e",
+ 3,
+ "compile_publication",
+ "applied",
+ "{\"schema\":\"hiroute.operation-step/v1\",\"step\":{\"attempts\":1,\"deterministic_input_digest\":\"sha256:c9171635fed9ca419452391118a4de7a2afe2190f23346129db8cd0fad57e365\",\"effects\":[],\"kind\":\"compile_publication\",\"sequence\":3,\"status\":\"applied\"}}"
+ ],
+ [
+ "op_3824e5057bdb23d4b2bf76685d797b4e",
+ 4,
+ "apply_agent_artifacts",
+ "applied",
+ "{\"schema\":\"hiroute.operation-step/v1\",\"step\":{\"attempts\":1,\"deterministic_input_digest\":\"sha256:5ac4612884ca3ffb3894cdd5bfa06ddfa853f083ca2bdf5605db6cc1f6922b51\",\"effects\":[],\"kind\":\"apply_agent_artifacts\",\"sequence\":4,\"status\":\"applied\"}}"
+ ],
+ [
+ "op_3824e5057bdb23d4b2bf76685d797b4e",
+ 5,
+ "activate",
+ "applied",
+ "{\"schema\":\"hiroute.operation-step/v1\",\"step\":{\"attempts\":1,\"deterministic_input_digest\":\"sha256:e522a4f844eb520088412ae184c9dc4b0cc2c8ca509e02b8c269b8eda7c1ae8b\",\"effects\":[],\"kind\":\"activate\",\"sequence\":5,\"status\":\"applied\"}}"
+ ],
+ [
+ "op_eae94ac62ab719efa325df7f93567385",
+ 0,
+ "prepare",
+ "applied",
+ "{\"schema\":\"hiroute.operation-step/v1\",\"step\":{\"attempts\":1,\"deterministic_input_digest\":\"sha256:89568ed74e77d437891b2a969be85acc4097ef4de75807a265d3464a364b16a9\",\"effects\":[],\"kind\":\"prepare\",\"sequence\":0,\"status\":\"applied\"}}"
+ ],
+ [
+ "op_eae94ac62ab719efa325df7f93567385",
+ 1,
+ "apply_secrets",
+ "applied",
+ "{\"schema\":\"hiroute.operation-step/v1\",\"step\":{\"attempts\":1,\"deterministic_input_digest\":\"sha256:75f16a5c021b74501c720d197122fe1e672dc27c9025d026d257aad66e6561b4\",\"effects\":[],\"kind\":\"apply_secrets\",\"sequence\":1,\"status\":\"applied\"}}"
+ ],
+ [
+ "op_eae94ac62ab719efa325df7f93567385",
+ 2,
+ "materialize_sources",
+ "applied",
+ "{\"schema\":\"hiroute.operation-step/v1\",\"step\":{\"attempts\":1,\"deterministic_input_digest\":\"sha256:2eaa42f80de54f3cc89eb18e6956fd90f59b6d6f37b6adc085cf632e1f61c6e9\",\"effects\":[{\"after_fingerprint\":\"sha256:a0187c2271bab58183319337b972c299cf37491a86823664cfc68b625759dbea\",\"compensation\":{\"after_revision\":1,\"operation_id\":\"op_eae94ac62ab719efa325df7f93567385\",\"schema\":\"hiroute.worker-dependency-selection-compensation/v1\"},\"effect_id\":\"worker-dependency-selection:codex_cli\",\"kind\":\"control\",\"target\":\"personal/default/worker-dependency-selection/codex_cli\"}],\"kind\":\"materialize_sources\",\"sequence\":2,\"status\":\"applied\"}}"
+ ],
+ [
+ "op_eae94ac62ab719efa325df7f93567385",
+ 3,
+ "compile_publication",
+ "applied",
+ "{\"schema\":\"hiroute.operation-step/v1\",\"step\":{\"attempts\":1,\"deterministic_input_digest\":\"sha256:c9171635fed9ca419452391118a4de7a2afe2190f23346129db8cd0fad57e365\",\"effects\":[],\"kind\":\"compile_publication\",\"sequence\":3,\"status\":\"applied\"}}"
+ ],
+ [
+ "op_eae94ac62ab719efa325df7f93567385",
+ 4,
+ "apply_agent_artifacts",
+ "applied",
+ "{\"schema\":\"hiroute.operation-step/v1\",\"step\":{\"attempts\":1,\"deterministic_input_digest\":\"sha256:5ac4612884ca3ffb3894cdd5bfa06ddfa853f083ca2bdf5605db6cc1f6922b51\",\"effects\":[],\"kind\":\"apply_agent_artifacts\",\"sequence\":4,\"status\":\"applied\"}}"
+ ],
+ [
+ "op_eae94ac62ab719efa325df7f93567385",
+ 5,
+ "activate",
+ "applied",
+ "{\"schema\":\"hiroute.operation-step/v1\",\"step\":{\"attempts\":1,\"deterministic_input_digest\":\"sha256:e522a4f844eb520088412ae184c9dc4b0cc2c8ca509e02b8c269b8eda7c1ae8b\",\"effects\":[],\"kind\":\"activate\",\"sequence\":5,\"status\":\"applied\"}}"
+ ]
+ ]
+ },
+ "operations": {
+ "columns": [
+ "operation_id",
+ "workspace_id",
+ "principal",
+ "operation_kind",
+ "idempotency_key",
+ "request_digest",
+ "accepted_change_digest",
+ "state",
+ "generation",
+ "operation_json",
+ "created_at",
+ "updated_at"
+ ],
+ "rows": [
+ [
+ "op_3824e5057bdb23d4b2bf76685d797b4e",
+ "personal/default",
+ "interactive-user",
+ "SelectWorkerDependencies",
+ "activated",
+ "sha256:c423c380c2151df5da63235d47c4b3c95e392f31718e3d3e4eb7455c1443ea66",
+ "sha256:60d940201528a762c1c879bcf8321c7376795f1ff5f9c91f84ff04c21347a7b8",
+ "activating",
+ 1,
+ "{\"schema_version\":2,\"operation_id\":\"op_3824e5057bdb23d4b2bf76685d797b4e\",\"workspace_id\":\"personal/default\",\"idempotency\":{\"principal\":\"interactive-user\",\"operation_kind\":\"SelectWorkerDependencies\",\"key\":\"activated\"},\"request_digest\":\"sha256:c423c380c2151df5da63235d47c4b3c95e392f31718e3d3e4eb7455c1443ea66\",\"accepted_digest\":\"sha256:60d940201528a762c1c879bcf8321c7376795f1ff5f9c91f84ff04c21347a7b8\",\"expected_revisions\":{\"target\":1},\"plan\":{\"control\":{},\"credential_pool\":null,\"external\":[],\"runtime\":[],\"schema\":\"hiroute.operation-input/v1\",\"secrets\":[],\"spec\":{\"command_id\":\"worker.dependencies.select\",\"desired_state\":{\"adapter_path\":\"/opt/new-installation/adapter.js\",\"cli_path\":\"/opt/new-installation/cli\",\"harness\":\"codex_cli\",\"node_path\":\"/opt/new-installation/node\"},\"resource_id\":\"worker-dependency-selection/codex_cli\",\"schema_version\":{\"major\":1,\"minor\":0}},\"worker_dependency_selection\":{\"after_selection\":{\"adapter_path\":\"/opt/new-installation/adapter.js\",\"cli_path\":\"/opt/new-installation/cli\",\"harness\":\"codex_cli\",\"node_path\":\"/opt/new-installation/node\"},\"before_revision\":1}},\"state\":\"activating\",\"generation\":1,\"steps\":[{\"sequence\":0,\"kind\":\"prepare\",\"deterministic_input_digest\":\"sha256:6b273ac3806ed5ad22337748ea95303cc01ae0d310e9858231381bc73d2fa2ff\",\"status\":\"applied\",\"attempts\":1,\"effects\":[]},{\"sequence\":1,\"kind\":\"apply_secrets\",\"deterministic_input_digest\":\"sha256:75f16a5c021b74501c720d197122fe1e672dc27c9025d026d257aad66e6561b4\",\"status\":\"applied\",\"attempts\":1,\"effects\":[]},{\"sequence\":2,\"kind\":\"materialize_sources\",\"deterministic_input_digest\":\"sha256:2ee7eb2fa88af2075cda8d982130d3573cd234ff240025861129f7cb9663ce91\",\"status\":\"applied\",\"attempts\":1,\"effects\":[{\"effect_id\":\"worker-dependency-selection:codex_cli\",\"kind\":\"control\",\"target\":\"personal/default/worker-dependency-selection/codex_cli\",\"before_fingerprint\":\"sha256:a0187c2271bab58183319337b972c299cf37491a86823664cfc68b625759dbea\",\"after_fingerprint\":\"sha256:56fd8be01787e9003143ba94d003b4650ba9f2d51da44724534f85869b49349d\",\"compensation\":{\"after_revision\":2,\"operation_id\":\"op_3824e5057bdb23d4b2bf76685d797b4e\",\"schema\":\"hiroute.worker-dependency-selection-compensation/v1\"}}]},{\"sequence\":3,\"kind\":\"compile_publication\",\"deterministic_input_digest\":\"sha256:c9171635fed9ca419452391118a4de7a2afe2190f23346129db8cd0fad57e365\",\"status\":\"applied\",\"attempts\":1,\"effects\":[]},{\"sequence\":4,\"kind\":\"apply_agent_artifacts\",\"deterministic_input_digest\":\"sha256:5ac4612884ca3ffb3894cdd5bfa06ddfa853f083ca2bdf5605db6cc1f6922b51\",\"status\":\"applied\",\"attempts\":1,\"effects\":[]},{\"sequence\":5,\"kind\":\"activate\",\"deterministic_input_digest\":\"sha256:e522a4f844eb520088412ae184c9dc4b0cc2c8ca509e02b8c269b8eda7c1ae8b\",\"status\":\"applied\",\"attempts\":1,\"effects\":[]}],\"safe_error_code\":null}",
+ 1791051525,
+ 1791051525
+ ],
+ [
+ "op_eae94ac62ab719efa325df7f93567385",
+ "personal/default",
+ "interactive-user",
+ "SelectWorkerDependencies",
+ "before",
+ "sha256:6e7a07e13ebfac57bd3b26c1420041a565e0494f7419773bf83d498fb15b93ba",
+ "sha256:059abecbcf3998f101f54fb071df49052efda401f0fc1bbfa776a9acb28e9119",
+ "succeeded",
+ 1,
+ "{\"schema_version\":2,\"operation_id\":\"op_eae94ac62ab719efa325df7f93567385\",\"workspace_id\":\"personal/default\",\"idempotency\":{\"principal\":\"interactive-user\",\"operation_kind\":\"SelectWorkerDependencies\",\"key\":\"before\"},\"request_digest\":\"sha256:6e7a07e13ebfac57bd3b26c1420041a565e0494f7419773bf83d498fb15b93ba\",\"accepted_digest\":\"sha256:059abecbcf3998f101f54fb071df49052efda401f0fc1bbfa776a9acb28e9119\",\"expected_revisions\":{\"target\":0},\"plan\":{\"control\":{},\"credential_pool\":null,\"external\":[],\"runtime\":[],\"schema\":\"hiroute.operation-input/v1\",\"secrets\":[],\"spec\":{\"command_id\":\"worker.dependencies.select\",\"desired_state\":{\"adapter_path\":\"/opt/old-installation/adapter.js\",\"cli_path\":\"/opt/old-installation/cli\",\"harness\":\"codex_cli\",\"node_path\":\"/opt/old-installation/node\"},\"resource_id\":\"worker-dependency-selection/codex_cli\",\"schema_version\":{\"major\":1,\"minor\":0}},\"worker_dependency_selection\":{\"after_selection\":{\"adapter_path\":\"/opt/old-installation/adapter.js\",\"cli_path\":\"/opt/old-installation/cli\",\"harness\":\"codex_cli\",\"node_path\":\"/opt/old-installation/node\"},\"before_revision\":0}},\"state\":\"succeeded\",\"generation\":1,\"steps\":[{\"sequence\":0,\"kind\":\"prepare\",\"deterministic_input_digest\":\"sha256:89568ed74e77d437891b2a969be85acc4097ef4de75807a265d3464a364b16a9\",\"status\":\"applied\",\"attempts\":1,\"effects\":[]},{\"sequence\":1,\"kind\":\"apply_secrets\",\"deterministic_input_digest\":\"sha256:75f16a5c021b74501c720d197122fe1e672dc27c9025d026d257aad66e6561b4\",\"status\":\"applied\",\"attempts\":1,\"effects\":[]},{\"sequence\":2,\"kind\":\"materialize_sources\",\"deterministic_input_digest\":\"sha256:2eaa42f80de54f3cc89eb18e6956fd90f59b6d6f37b6adc085cf632e1f61c6e9\",\"status\":\"applied\",\"attempts\":1,\"effects\":[{\"effect_id\":\"worker-dependency-selection:codex_cli\",\"kind\":\"control\",\"target\":\"personal/default/worker-dependency-selection/codex_cli\",\"after_fingerprint\":\"sha256:a0187c2271bab58183319337b972c299cf37491a86823664cfc68b625759dbea\",\"compensation\":{\"after_revision\":1,\"operation_id\":\"op_eae94ac62ab719efa325df7f93567385\",\"schema\":\"hiroute.worker-dependency-selection-compensation/v1\"}}]},{\"sequence\":3,\"kind\":\"compile_publication\",\"deterministic_input_digest\":\"sha256:c9171635fed9ca419452391118a4de7a2afe2190f23346129db8cd0fad57e365\",\"status\":\"applied\",\"attempts\":1,\"effects\":[]},{\"sequence\":4,\"kind\":\"apply_agent_artifacts\",\"deterministic_input_digest\":\"sha256:5ac4612884ca3ffb3894cdd5bfa06ddfa853f083ca2bdf5605db6cc1f6922b51\",\"status\":\"applied\",\"attempts\":1,\"effects\":[]},{\"sequence\":5,\"kind\":\"activate\",\"deterministic_input_digest\":\"sha256:e522a4f844eb520088412ae184c9dc4b0cc2c8ca509e02b8c269b8eda7c1ae8b\",\"status\":\"applied\",\"attempts\":1,\"effects\":[]}],\"safe_error_code\":null}",
+ 1791051525,
+ 1791051525
+ ]
+ ]
+ },
+ "worker_dependency_selection_effects": {
+ "columns": [
+ "operation_id",
+ "workspace_id",
+ "harness",
+ "before_revision",
+ "before_json",
+ "before_owner_operation_id",
+ "after_revision",
+ "after_json",
+ "activated",
+ "compensated"
+ ],
+ "rows": [
+ [
+ "op_3824e5057bdb23d4b2bf76685d797b4e",
+ "personal/default",
+ "codex_cli",
+ 1,
+ "{\"harness\":\"codex_cli\",\"adapter_path\":\"/opt/old-installation/adapter.js\",\"cli_path\":\"/opt/old-installation/cli\",\"node_path\":\"/opt/old-installation/node\"}",
+ "op_eae94ac62ab719efa325df7f93567385",
+ 2,
+ "{\"harness\":\"codex_cli\",\"adapter_path\":\"/opt/new-installation/adapter.js\",\"cli_path\":\"/opt/new-installation/cli\",\"node_path\":\"/opt/new-installation/node\"}",
+ 1,
+ 0
+ ],
+ [
+ "op_eae94ac62ab719efa325df7f93567385",
+ "personal/default",
+ "codex_cli",
+ 0,
+ null,
+ null,
+ 1,
+ "{\"harness\":\"codex_cli\",\"adapter_path\":\"/opt/old-installation/adapter.js\",\"cli_path\":\"/opt/old-installation/cli\",\"node_path\":\"/opt/old-installation/node\"}",
+ 1,
+ 0
+ ]
+ ]
+ },
+ "worker_dependency_selections": {
+ "columns": [
+ "workspace_id",
+ "harness",
+ "revision",
+ "selection_json",
+ "owner_operation_id",
+ "updated_at"
+ ],
+ "rows": [
+ [
+ "personal/default",
+ "codex_cli",
+ 2,
+ "{\"harness\":\"codex_cli\",\"adapter_path\":\"/opt/new-installation/adapter.js\",\"cli_path\":\"/opt/new-installation/cli\",\"node_path\":\"/opt/new-installation/node\"}",
+ "op_3824e5057bdb23d4b2bf76685d797b4e",
+ 1791051525
+ ]
+ ]
+ },
+ "writer_claim": {
+ "columns": [
+ "singleton",
+ "operation_id",
+ "admitted_at"
+ ],
+ "rows": [
+ [
+ 1,
+ "op_3824e5057bdb23d4b2bf76685d797b4e",
+ 1791051525
+ ]
+ ]
+ }
+ }
+ },
+ {
+ "effect": {
+ "after_fingerprint": "sha256:56fd8be01787e9003143ba94d003b4650ba9f2d51da44724534f85869b49349d",
+ "before_fingerprint": "sha256:a0187c2271bab58183319337b972c299cf37491a86823664cfc68b625759dbea",
+ "compensation": {
+ "after_revision": 2,
+ "operation_id": "op_6693417061f9f840b88fa9f61f367441",
+ "schema": "hiroute.worker-dependency-selection-compensation/v1"
+ },
+ "effect_id": "worker-dependency-selection:codex_cli",
+ "kind": "control",
+ "target": "personal/default/worker-dependency-selection/codex_cli"
+ },
+ "harness": "codex_cli",
+ "operation_id": "op_6693417061f9f840b88fa9f61f367441",
+ "previous_effect": {
+ "after_fingerprint": "sha256:a0187c2271bab58183319337b972c299cf37491a86823664cfc68b625759dbea",
+ "compensation": {
+ "after_revision": 1,
+ "operation_id": "op_eae94ac62ab719efa325df7f93567385",
+ "schema": "hiroute.worker-dependency-selection-compensation/v1"
+ },
+ "effect_id": "worker-dependency-selection:codex_cli",
+ "kind": "control",
+ "target": "personal/default/worker-dependency-selection/codex_cli"
+ },
+ "stage": "succeeded",
+ "tables": {
+ "operation_steps": {
+ "columns": [
+ "operation_id",
+ "step_no",
+ "step_kind",
+ "state",
+ "step_json"
+ ],
+ "rows": [
+ [
+ "op_6693417061f9f840b88fa9f61f367441",
+ 0,
+ "prepare",
+ "applied",
+ "{\"schema\":\"hiroute.operation-step/v1\",\"step\":{\"attempts\":1,\"deterministic_input_digest\":\"sha256:6b273ac3806ed5ad22337748ea95303cc01ae0d310e9858231381bc73d2fa2ff\",\"effects\":[],\"kind\":\"prepare\",\"sequence\":0,\"status\":\"applied\"}}"
+ ],
+ [
+ "op_6693417061f9f840b88fa9f61f367441",
+ 1,
+ "apply_secrets",
+ "applied",
+ "{\"schema\":\"hiroute.operation-step/v1\",\"step\":{\"attempts\":1,\"deterministic_input_digest\":\"sha256:75f16a5c021b74501c720d197122fe1e672dc27c9025d026d257aad66e6561b4\",\"effects\":[],\"kind\":\"apply_secrets\",\"sequence\":1,\"status\":\"applied\"}}"
+ ],
+ [
+ "op_6693417061f9f840b88fa9f61f367441",
+ 2,
+ "materialize_sources",
+ "applied",
+ "{\"schema\":\"hiroute.operation-step/v1\",\"step\":{\"attempts\":1,\"deterministic_input_digest\":\"sha256:2ee7eb2fa88af2075cda8d982130d3573cd234ff240025861129f7cb9663ce91\",\"effects\":[{\"after_fingerprint\":\"sha256:56fd8be01787e9003143ba94d003b4650ba9f2d51da44724534f85869b49349d\",\"before_fingerprint\":\"sha256:a0187c2271bab58183319337b972c299cf37491a86823664cfc68b625759dbea\",\"compensation\":{\"after_revision\":2,\"operation_id\":\"op_6693417061f9f840b88fa9f61f367441\",\"schema\":\"hiroute.worker-dependency-selection-compensation/v1\"},\"effect_id\":\"worker-dependency-selection:codex_cli\",\"kind\":\"control\",\"target\":\"personal/default/worker-dependency-selection/codex_cli\"}],\"kind\":\"materialize_sources\",\"sequence\":2,\"status\":\"applied\"}}"
+ ],
+ [
+ "op_6693417061f9f840b88fa9f61f367441",
+ 3,
+ "compile_publication",
+ "applied",
+ "{\"schema\":\"hiroute.operation-step/v1\",\"step\":{\"attempts\":1,\"deterministic_input_digest\":\"sha256:c9171635fed9ca419452391118a4de7a2afe2190f23346129db8cd0fad57e365\",\"effects\":[],\"kind\":\"compile_publication\",\"sequence\":3,\"status\":\"applied\"}}"
+ ],
+ [
+ "op_6693417061f9f840b88fa9f61f367441",
+ 4,
+ "apply_agent_artifacts",
+ "applied",
+ "{\"schema\":\"hiroute.operation-step/v1\",\"step\":{\"attempts\":1,\"deterministic_input_digest\":\"sha256:5ac4612884ca3ffb3894cdd5bfa06ddfa853f083ca2bdf5605db6cc1f6922b51\",\"effects\":[],\"kind\":\"apply_agent_artifacts\",\"sequence\":4,\"status\":\"applied\"}}"
+ ],
+ [
+ "op_6693417061f9f840b88fa9f61f367441",
+ 5,
+ "activate",
+ "applied",
+ "{\"schema\":\"hiroute.operation-step/v1\",\"step\":{\"attempts\":1,\"deterministic_input_digest\":\"sha256:e522a4f844eb520088412ae184c9dc4b0cc2c8ca509e02b8c269b8eda7c1ae8b\",\"effects\":[],\"kind\":\"activate\",\"sequence\":5,\"status\":\"applied\"}}"
+ ],
+ [
+ "op_eae94ac62ab719efa325df7f93567385",
+ 0,
+ "prepare",
+ "applied",
+ "{\"schema\":\"hiroute.operation-step/v1\",\"step\":{\"attempts\":1,\"deterministic_input_digest\":\"sha256:89568ed74e77d437891b2a969be85acc4097ef4de75807a265d3464a364b16a9\",\"effects\":[],\"kind\":\"prepare\",\"sequence\":0,\"status\":\"applied\"}}"
+ ],
+ [
+ "op_eae94ac62ab719efa325df7f93567385",
+ 1,
+ "apply_secrets",
+ "applied",
+ "{\"schema\":\"hiroute.operation-step/v1\",\"step\":{\"attempts\":1,\"deterministic_input_digest\":\"sha256:75f16a5c021b74501c720d197122fe1e672dc27c9025d026d257aad66e6561b4\",\"effects\":[],\"kind\":\"apply_secrets\",\"sequence\":1,\"status\":\"applied\"}}"
+ ],
+ [
+ "op_eae94ac62ab719efa325df7f93567385",
+ 2,
+ "materialize_sources",
+ "applied",
+ "{\"schema\":\"hiroute.operation-step/v1\",\"step\":{\"attempts\":1,\"deterministic_input_digest\":\"sha256:2eaa42f80de54f3cc89eb18e6956fd90f59b6d6f37b6adc085cf632e1f61c6e9\",\"effects\":[{\"after_fingerprint\":\"sha256:a0187c2271bab58183319337b972c299cf37491a86823664cfc68b625759dbea\",\"compensation\":{\"after_revision\":1,\"operation_id\":\"op_eae94ac62ab719efa325df7f93567385\",\"schema\":\"hiroute.worker-dependency-selection-compensation/v1\"},\"effect_id\":\"worker-dependency-selection:codex_cli\",\"kind\":\"control\",\"target\":\"personal/default/worker-dependency-selection/codex_cli\"}],\"kind\":\"materialize_sources\",\"sequence\":2,\"status\":\"applied\"}}"
+ ],
+ [
+ "op_eae94ac62ab719efa325df7f93567385",
+ 3,
+ "compile_publication",
+ "applied",
+ "{\"schema\":\"hiroute.operation-step/v1\",\"step\":{\"attempts\":1,\"deterministic_input_digest\":\"sha256:c9171635fed9ca419452391118a4de7a2afe2190f23346129db8cd0fad57e365\",\"effects\":[],\"kind\":\"compile_publication\",\"sequence\":3,\"status\":\"applied\"}}"
+ ],
+ [
+ "op_eae94ac62ab719efa325df7f93567385",
+ 4,
+ "apply_agent_artifacts",
+ "applied",
+ "{\"schema\":\"hiroute.operation-step/v1\",\"step\":{\"attempts\":1,\"deterministic_input_digest\":\"sha256:5ac4612884ca3ffb3894cdd5bfa06ddfa853f083ca2bdf5605db6cc1f6922b51\",\"effects\":[],\"kind\":\"apply_agent_artifacts\",\"sequence\":4,\"status\":\"applied\"}}"
+ ],
+ [
+ "op_eae94ac62ab719efa325df7f93567385",
+ 5,
+ "activate",
+ "applied",
+ "{\"schema\":\"hiroute.operation-step/v1\",\"step\":{\"attempts\":1,\"deterministic_input_digest\":\"sha256:e522a4f844eb520088412ae184c9dc4b0cc2c8ca509e02b8c269b8eda7c1ae8b\",\"effects\":[],\"kind\":\"activate\",\"sequence\":5,\"status\":\"applied\"}}"
+ ]
+ ]
+ },
+ "operations": {
+ "columns": [
+ "operation_id",
+ "workspace_id",
+ "principal",
+ "operation_kind",
+ "idempotency_key",
+ "request_digest",
+ "accepted_change_digest",
+ "state",
+ "generation",
+ "operation_json",
+ "created_at",
+ "updated_at"
+ ],
+ "rows": [
+ [
+ "op_6693417061f9f840b88fa9f61f367441",
+ "personal/default",
+ "interactive-user",
+ "SelectWorkerDependencies",
+ "succeeded",
+ "sha256:333073c4155f0bd05323857095216a7ede54c22c565c7e1ab3f76223ebcb4b1a",
+ "sha256:60d940201528a762c1c879bcf8321c7376795f1ff5f9c91f84ff04c21347a7b8",
+ "succeeded",
+ 1,
+ "{\"schema_version\":2,\"operation_id\":\"op_6693417061f9f840b88fa9f61f367441\",\"workspace_id\":\"personal/default\",\"idempotency\":{\"principal\":\"interactive-user\",\"operation_kind\":\"SelectWorkerDependencies\",\"key\":\"succeeded\"},\"request_digest\":\"sha256:333073c4155f0bd05323857095216a7ede54c22c565c7e1ab3f76223ebcb4b1a\",\"accepted_digest\":\"sha256:60d940201528a762c1c879bcf8321c7376795f1ff5f9c91f84ff04c21347a7b8\",\"expected_revisions\":{\"target\":1},\"plan\":{\"control\":{},\"credential_pool\":null,\"external\":[],\"runtime\":[],\"schema\":\"hiroute.operation-input/v1\",\"secrets\":[],\"spec\":{\"command_id\":\"worker.dependencies.select\",\"desired_state\":{\"adapter_path\":\"/opt/new-installation/adapter.js\",\"cli_path\":\"/opt/new-installation/cli\",\"harness\":\"codex_cli\",\"node_path\":\"/opt/new-installation/node\"},\"resource_id\":\"worker-dependency-selection/codex_cli\",\"schema_version\":{\"major\":1,\"minor\":0}},\"worker_dependency_selection\":{\"after_selection\":{\"adapter_path\":\"/opt/new-installation/adapter.js\",\"cli_path\":\"/opt/new-installation/cli\",\"harness\":\"codex_cli\",\"node_path\":\"/opt/new-installation/node\"},\"before_revision\":1}},\"state\":\"succeeded\",\"generation\":1,\"steps\":[{\"sequence\":0,\"kind\":\"prepare\",\"deterministic_input_digest\":\"sha256:6b273ac3806ed5ad22337748ea95303cc01ae0d310e9858231381bc73d2fa2ff\",\"status\":\"applied\",\"attempts\":1,\"effects\":[]},{\"sequence\":1,\"kind\":\"apply_secrets\",\"deterministic_input_digest\":\"sha256:75f16a5c021b74501c720d197122fe1e672dc27c9025d026d257aad66e6561b4\",\"status\":\"applied\",\"attempts\":1,\"effects\":[]},{\"sequence\":2,\"kind\":\"materialize_sources\",\"deterministic_input_digest\":\"sha256:2ee7eb2fa88af2075cda8d982130d3573cd234ff240025861129f7cb9663ce91\",\"status\":\"applied\",\"attempts\":1,\"effects\":[{\"effect_id\":\"worker-dependency-selection:codex_cli\",\"kind\":\"control\",\"target\":\"personal/default/worker-dependency-selection/codex_cli\",\"before_fingerprint\":\"sha256:a0187c2271bab58183319337b972c299cf37491a86823664cfc68b625759dbea\",\"after_fingerprint\":\"sha256:56fd8be01787e9003143ba94d003b4650ba9f2d51da44724534f85869b49349d\",\"compensation\":{\"after_revision\":2,\"operation_id\":\"op_6693417061f9f840b88fa9f61f367441\",\"schema\":\"hiroute.worker-dependency-selection-compensation/v1\"}}]},{\"sequence\":3,\"kind\":\"compile_publication\",\"deterministic_input_digest\":\"sha256:c9171635fed9ca419452391118a4de7a2afe2190f23346129db8cd0fad57e365\",\"status\":\"applied\",\"attempts\":1,\"effects\":[]},{\"sequence\":4,\"kind\":\"apply_agent_artifacts\",\"deterministic_input_digest\":\"sha256:5ac4612884ca3ffb3894cdd5bfa06ddfa853f083ca2bdf5605db6cc1f6922b51\",\"status\":\"applied\",\"attempts\":1,\"effects\":[]},{\"sequence\":5,\"kind\":\"activate\",\"deterministic_input_digest\":\"sha256:e522a4f844eb520088412ae184c9dc4b0cc2c8ca509e02b8c269b8eda7c1ae8b\",\"status\":\"applied\",\"attempts\":1,\"effects\":[]}],\"safe_error_code\":null}",
+ 1791051525,
+ 1791051525
+ ],
+ [
+ "op_eae94ac62ab719efa325df7f93567385",
+ "personal/default",
+ "interactive-user",
+ "SelectWorkerDependencies",
+ "before",
+ "sha256:6e7a07e13ebfac57bd3b26c1420041a565e0494f7419773bf83d498fb15b93ba",
+ "sha256:059abecbcf3998f101f54fb071df49052efda401f0fc1bbfa776a9acb28e9119",
+ "succeeded",
+ 1,
+ "{\"schema_version\":2,\"operation_id\":\"op_eae94ac62ab719efa325df7f93567385\",\"workspace_id\":\"personal/default\",\"idempotency\":{\"principal\":\"interactive-user\",\"operation_kind\":\"SelectWorkerDependencies\",\"key\":\"before\"},\"request_digest\":\"sha256:6e7a07e13ebfac57bd3b26c1420041a565e0494f7419773bf83d498fb15b93ba\",\"accepted_digest\":\"sha256:059abecbcf3998f101f54fb071df49052efda401f0fc1bbfa776a9acb28e9119\",\"expected_revisions\":{\"target\":0},\"plan\":{\"control\":{},\"credential_pool\":null,\"external\":[],\"runtime\":[],\"schema\":\"hiroute.operation-input/v1\",\"secrets\":[],\"spec\":{\"command_id\":\"worker.dependencies.select\",\"desired_state\":{\"adapter_path\":\"/opt/old-installation/adapter.js\",\"cli_path\":\"/opt/old-installation/cli\",\"harness\":\"codex_cli\",\"node_path\":\"/opt/old-installation/node\"},\"resource_id\":\"worker-dependency-selection/codex_cli\",\"schema_version\":{\"major\":1,\"minor\":0}},\"worker_dependency_selection\":{\"after_selection\":{\"adapter_path\":\"/opt/old-installation/adapter.js\",\"cli_path\":\"/opt/old-installation/cli\",\"harness\":\"codex_cli\",\"node_path\":\"/opt/old-installation/node\"},\"before_revision\":0}},\"state\":\"succeeded\",\"generation\":1,\"steps\":[{\"sequence\":0,\"kind\":\"prepare\",\"deterministic_input_digest\":\"sha256:89568ed74e77d437891b2a969be85acc4097ef4de75807a265d3464a364b16a9\",\"status\":\"applied\",\"attempts\":1,\"effects\":[]},{\"sequence\":1,\"kind\":\"apply_secrets\",\"deterministic_input_digest\":\"sha256:75f16a5c021b74501c720d197122fe1e672dc27c9025d026d257aad66e6561b4\",\"status\":\"applied\",\"attempts\":1,\"effects\":[]},{\"sequence\":2,\"kind\":\"materialize_sources\",\"deterministic_input_digest\":\"sha256:2eaa42f80de54f3cc89eb18e6956fd90f59b6d6f37b6adc085cf632e1f61c6e9\",\"status\":\"applied\",\"attempts\":1,\"effects\":[{\"effect_id\":\"worker-dependency-selection:codex_cli\",\"kind\":\"control\",\"target\":\"personal/default/worker-dependency-selection/codex_cli\",\"after_fingerprint\":\"sha256:a0187c2271bab58183319337b972c299cf37491a86823664cfc68b625759dbea\",\"compensation\":{\"after_revision\":1,\"operation_id\":\"op_eae94ac62ab719efa325df7f93567385\",\"schema\":\"hiroute.worker-dependency-selection-compensation/v1\"}}]},{\"sequence\":3,\"kind\":\"compile_publication\",\"deterministic_input_digest\":\"sha256:c9171635fed9ca419452391118a4de7a2afe2190f23346129db8cd0fad57e365\",\"status\":\"applied\",\"attempts\":1,\"effects\":[]},{\"sequence\":4,\"kind\":\"apply_agent_artifacts\",\"deterministic_input_digest\":\"sha256:5ac4612884ca3ffb3894cdd5bfa06ddfa853f083ca2bdf5605db6cc1f6922b51\",\"status\":\"applied\",\"attempts\":1,\"effects\":[]},{\"sequence\":5,\"kind\":\"activate\",\"deterministic_input_digest\":\"sha256:e522a4f844eb520088412ae184c9dc4b0cc2c8ca509e02b8c269b8eda7c1ae8b\",\"status\":\"applied\",\"attempts\":1,\"effects\":[]}],\"safe_error_code\":null}",
+ 1791051525,
+ 1791051525
+ ]
+ ]
+ },
+ "worker_dependency_selection_effects": {
+ "columns": [
+ "operation_id",
+ "workspace_id",
+ "harness",
+ "before_revision",
+ "before_json",
+ "before_owner_operation_id",
+ "after_revision",
+ "after_json",
+ "activated",
+ "compensated"
+ ],
+ "rows": [
+ [
+ "op_6693417061f9f840b88fa9f61f367441",
+ "personal/default",
+ "codex_cli",
+ 1,
+ "{\"harness\":\"codex_cli\",\"adapter_path\":\"/opt/old-installation/adapter.js\",\"cli_path\":\"/opt/old-installation/cli\",\"node_path\":\"/opt/old-installation/node\"}",
+ "op_eae94ac62ab719efa325df7f93567385",
+ 2,
+ "{\"harness\":\"codex_cli\",\"adapter_path\":\"/opt/new-installation/adapter.js\",\"cli_path\":\"/opt/new-installation/cli\",\"node_path\":\"/opt/new-installation/node\"}",
+ 1,
+ 0
+ ],
+ [
+ "op_eae94ac62ab719efa325df7f93567385",
+ "personal/default",
+ "codex_cli",
+ 0,
+ null,
+ null,
+ 1,
+ "{\"harness\":\"codex_cli\",\"adapter_path\":\"/opt/old-installation/adapter.js\",\"cli_path\":\"/opt/old-installation/cli\",\"node_path\":\"/opt/old-installation/node\"}",
+ 1,
+ 0
+ ]
+ ]
+ },
+ "worker_dependency_selections": {
+ "columns": [
+ "workspace_id",
+ "harness",
+ "revision",
+ "selection_json",
+ "owner_operation_id",
+ "updated_at"
+ ],
+ "rows": [
+ [
+ "personal/default",
+ "codex_cli",
+ 2,
+ "{\"harness\":\"codex_cli\",\"adapter_path\":\"/opt/new-installation/adapter.js\",\"cli_path\":\"/opt/new-installation/cli\",\"node_path\":\"/opt/new-installation/node\"}",
+ "op_6693417061f9f840b88fa9f61f367441",
+ 1791051525
+ ]
+ ]
+ },
+ "writer_claim": {
+ "columns": [
+ "singleton",
+ "operation_id",
+ "admitted_at"
+ ],
+ "rows": []
+ }
+ }
+ },
+ {
+ "effect": {
+ "after_fingerprint": "sha256:5c46e954818b7b9968c004d4e949616c55917270c5aa09782d6c2fb6527547fa",
+ "before_fingerprint": "sha256:15dde49e810f048a183e48b85f75a7bb39d06b9ba39c915f105876122a24c3b0",
+ "compensation": {
+ "after_revision": 2,
+ "operation_id": "op_b11607ab48bae8c308337e49c24b6014",
+ "schema": "hiroute.worker-dependency-selection-compensation/v1"
+ },
+ "effect_id": "worker-dependency-selection:claude_code",
+ "kind": "control",
+ "target": "personal/default/worker-dependency-selection/claude_code"
+ },
+ "harness": "claude_code",
+ "operation_id": "op_b11607ab48bae8c308337e49c24b6014",
+ "previous_effect": {
+ "after_fingerprint": "sha256:15dde49e810f048a183e48b85f75a7bb39d06b9ba39c915f105876122a24c3b0",
+ "compensation": {
+ "after_revision": 1,
+ "operation_id": "op_eae94ac62ab719efa325df7f93567385",
+ "schema": "hiroute.worker-dependency-selection-compensation/v1"
+ },
+ "effect_id": "worker-dependency-selection:claude_code",
+ "kind": "control",
+ "target": "personal/default/worker-dependency-selection/claude_code"
+ },
+ "stage": "staged",
+ "tables": {
+ "operation_steps": {
+ "columns": [
+ "operation_id",
+ "step_no",
+ "step_kind",
+ "state",
+ "step_json"
+ ],
+ "rows": [
+ [
+ "op_b11607ab48bae8c308337e49c24b6014",
+ 0,
+ "prepare",
+ "applied",
+ "{\"schema\":\"hiroute.operation-step/v1\",\"step\":{\"attempts\":1,\"deterministic_input_digest\":\"sha256:35e058b9f2ea4948e5c439a419db29165314cb9afc20def152639e996cd606c9\",\"effects\":[],\"kind\":\"prepare\",\"sequence\":0,\"status\":\"applied\"}}"
+ ],
+ [
+ "op_b11607ab48bae8c308337e49c24b6014",
+ 1,
+ "apply_secrets",
+ "applied",
+ "{\"schema\":\"hiroute.operation-step/v1\",\"step\":{\"attempts\":1,\"deterministic_input_digest\":\"sha256:75f16a5c021b74501c720d197122fe1e672dc27c9025d026d257aad66e6561b4\",\"effects\":[],\"kind\":\"apply_secrets\",\"sequence\":1,\"status\":\"applied\"}}"
+ ],
+ [
+ "op_b11607ab48bae8c308337e49c24b6014",
+ 2,
+ "materialize_sources",
+ "applied",
+ "{\"schema\":\"hiroute.operation-step/v1\",\"step\":{\"attempts\":1,\"deterministic_input_digest\":\"sha256:67dc83911298082049d92d0306c35b482352d2a5ecea631c149337e12e5f05a7\",\"effects\":[{\"after_fingerprint\":\"sha256:5c46e954818b7b9968c004d4e949616c55917270c5aa09782d6c2fb6527547fa\",\"before_fingerprint\":\"sha256:15dde49e810f048a183e48b85f75a7bb39d06b9ba39c915f105876122a24c3b0\",\"compensation\":{\"after_revision\":2,\"operation_id\":\"op_b11607ab48bae8c308337e49c24b6014\",\"schema\":\"hiroute.worker-dependency-selection-compensation/v1\"},\"effect_id\":\"worker-dependency-selection:claude_code\",\"kind\":\"control\",\"target\":\"personal/default/worker-dependency-selection/claude_code\"}],\"kind\":\"materialize_sources\",\"sequence\":2,\"status\":\"applied\"}}"
+ ],
+ [
+ "op_b11607ab48bae8c308337e49c24b6014",
+ 3,
+ "compile_publication",
+ "pending",
+ "{\"schema\":\"hiroute.operation-step/v1\",\"step\":{\"attempts\":0,\"deterministic_input_digest\":\"sha256:c9171635fed9ca419452391118a4de7a2afe2190f23346129db8cd0fad57e365\",\"effects\":[],\"kind\":\"compile_publication\",\"sequence\":3,\"status\":\"pending\"}}"
+ ],
+ [
+ "op_b11607ab48bae8c308337e49c24b6014",
+ 4,
+ "apply_agent_artifacts",
+ "pending",
+ "{\"schema\":\"hiroute.operation-step/v1\",\"step\":{\"attempts\":0,\"deterministic_input_digest\":\"sha256:5ac4612884ca3ffb3894cdd5bfa06ddfa853f083ca2bdf5605db6cc1f6922b51\",\"effects\":[],\"kind\":\"apply_agent_artifacts\",\"sequence\":4,\"status\":\"pending\"}}"
+ ],
+ [
+ "op_b11607ab48bae8c308337e49c24b6014",
+ 5,
+ "activate",
+ "pending",
+ "{\"schema\":\"hiroute.operation-step/v1\",\"step\":{\"attempts\":0,\"deterministic_input_digest\":\"sha256:e522a4f844eb520088412ae184c9dc4b0cc2c8ca509e02b8c269b8eda7c1ae8b\",\"effects\":[],\"kind\":\"activate\",\"sequence\":5,\"status\":\"pending\"}}"
+ ],
+ [
+ "op_eae94ac62ab719efa325df7f93567385",
+ 0,
+ "prepare",
+ "applied",
+ "{\"schema\":\"hiroute.operation-step/v1\",\"step\":{\"attempts\":1,\"deterministic_input_digest\":\"sha256:97cb3489d6097eb4baaf6aa6b74ce4fb2ee133a8352057b80c3a60f577c704bb\",\"effects\":[],\"kind\":\"prepare\",\"sequence\":0,\"status\":\"applied\"}}"
+ ],
+ [
+ "op_eae94ac62ab719efa325df7f93567385",
+ 1,
+ "apply_secrets",
+ "applied",
+ "{\"schema\":\"hiroute.operation-step/v1\",\"step\":{\"attempts\":1,\"deterministic_input_digest\":\"sha256:75f16a5c021b74501c720d197122fe1e672dc27c9025d026d257aad66e6561b4\",\"effects\":[],\"kind\":\"apply_secrets\",\"sequence\":1,\"status\":\"applied\"}}"
+ ],
+ [
+ "op_eae94ac62ab719efa325df7f93567385",
+ 2,
+ "materialize_sources",
+ "applied",
+ "{\"schema\":\"hiroute.operation-step/v1\",\"step\":{\"attempts\":1,\"deterministic_input_digest\":\"sha256:6220ed5fce19edfce51546b542d6445b8119bcfe482b7497fd255603661c80d0\",\"effects\":[{\"after_fingerprint\":\"sha256:15dde49e810f048a183e48b85f75a7bb39d06b9ba39c915f105876122a24c3b0\",\"compensation\":{\"after_revision\":1,\"operation_id\":\"op_eae94ac62ab719efa325df7f93567385\",\"schema\":\"hiroute.worker-dependency-selection-compensation/v1\"},\"effect_id\":\"worker-dependency-selection:claude_code\",\"kind\":\"control\",\"target\":\"personal/default/worker-dependency-selection/claude_code\"}],\"kind\":\"materialize_sources\",\"sequence\":2,\"status\":\"applied\"}}"
+ ],
+ [
+ "op_eae94ac62ab719efa325df7f93567385",
+ 3,
+ "compile_publication",
+ "applied",
+ "{\"schema\":\"hiroute.operation-step/v1\",\"step\":{\"attempts\":1,\"deterministic_input_digest\":\"sha256:c9171635fed9ca419452391118a4de7a2afe2190f23346129db8cd0fad57e365\",\"effects\":[],\"kind\":\"compile_publication\",\"sequence\":3,\"status\":\"applied\"}}"
+ ],
+ [
+ "op_eae94ac62ab719efa325df7f93567385",
+ 4,
+ "apply_agent_artifacts",
+ "applied",
+ "{\"schema\":\"hiroute.operation-step/v1\",\"step\":{\"attempts\":1,\"deterministic_input_digest\":\"sha256:5ac4612884ca3ffb3894cdd5bfa06ddfa853f083ca2bdf5605db6cc1f6922b51\",\"effects\":[],\"kind\":\"apply_agent_artifacts\",\"sequence\":4,\"status\":\"applied\"}}"
+ ],
+ [
+ "op_eae94ac62ab719efa325df7f93567385",
+ 5,
+ "activate",
+ "applied",
+ "{\"schema\":\"hiroute.operation-step/v1\",\"step\":{\"attempts\":1,\"deterministic_input_digest\":\"sha256:e522a4f844eb520088412ae184c9dc4b0cc2c8ca509e02b8c269b8eda7c1ae8b\",\"effects\":[],\"kind\":\"activate\",\"sequence\":5,\"status\":\"applied\"}}"
+ ]
+ ]
+ },
+ "operations": {
+ "columns": [
+ "operation_id",
+ "workspace_id",
+ "principal",
+ "operation_kind",
+ "idempotency_key",
+ "request_digest",
+ "accepted_change_digest",
+ "state",
+ "generation",
+ "operation_json",
+ "created_at",
+ "updated_at"
+ ],
+ "rows": [
+ [
+ "op_b11607ab48bae8c308337e49c24b6014",
+ "personal/default",
+ "interactive-user",
+ "SelectWorkerDependencies",
+ "staged",
+ "sha256:5f8cf78eaa6755b91fa931df07923db354c59b2288551ff143ea4128077e7701",
+ "sha256:f002abe29724e3065c4f1a1a71f21c20a93c6bffa99bbf543b72dc5c3ffce6e1",
+ "materializing_sources",
+ 1,
+ "{\"schema_version\":2,\"operation_id\":\"op_b11607ab48bae8c308337e49c24b6014\",\"workspace_id\":\"personal/default\",\"idempotency\":{\"principal\":\"interactive-user\",\"operation_kind\":\"SelectWorkerDependencies\",\"key\":\"staged\"},\"request_digest\":\"sha256:5f8cf78eaa6755b91fa931df07923db354c59b2288551ff143ea4128077e7701\",\"accepted_digest\":\"sha256:f002abe29724e3065c4f1a1a71f21c20a93c6bffa99bbf543b72dc5c3ffce6e1\",\"expected_revisions\":{\"target\":1},\"plan\":{\"control\":{},\"credential_pool\":null,\"external\":[],\"runtime\":[],\"schema\":\"hiroute.operation-input/v1\",\"secrets\":[],\"spec\":{\"command_id\":\"worker.dependencies.select\",\"desired_state\":{\"adapter_path\":\"/opt/new-installation/adapter.js\",\"cli_path\":\"/opt/new-installation/cli\",\"harness\":\"claude_code\",\"node_path\":\"/opt/new-installation/node\"},\"resource_id\":\"worker-dependency-selection/claude_code\",\"schema_version\":{\"major\":1,\"minor\":0}},\"worker_dependency_selection\":{\"after_selection\":{\"adapter_path\":\"/opt/new-installation/adapter.js\",\"cli_path\":\"/opt/new-installation/cli\",\"harness\":\"claude_code\",\"node_path\":\"/opt/new-installation/node\"},\"before_revision\":1}},\"state\":\"materializing_sources\",\"generation\":1,\"steps\":[{\"sequence\":0,\"kind\":\"prepare\",\"deterministic_input_digest\":\"sha256:35e058b9f2ea4948e5c439a419db29165314cb9afc20def152639e996cd606c9\",\"status\":\"applied\",\"attempts\":1,\"effects\":[]},{\"sequence\":1,\"kind\":\"apply_secrets\",\"deterministic_input_digest\":\"sha256:75f16a5c021b74501c720d197122fe1e672dc27c9025d026d257aad66e6561b4\",\"status\":\"applied\",\"attempts\":1,\"effects\":[]},{\"sequence\":2,\"kind\":\"materialize_sources\",\"deterministic_input_digest\":\"sha256:67dc83911298082049d92d0306c35b482352d2a5ecea631c149337e12e5f05a7\",\"status\":\"applied\",\"attempts\":1,\"effects\":[{\"effect_id\":\"worker-dependency-selection:claude_code\",\"kind\":\"control\",\"target\":\"personal/default/worker-dependency-selection/claude_code\",\"before_fingerprint\":\"sha256:15dde49e810f048a183e48b85f75a7bb39d06b9ba39c915f105876122a24c3b0\",\"after_fingerprint\":\"sha256:5c46e954818b7b9968c004d4e949616c55917270c5aa09782d6c2fb6527547fa\",\"compensation\":{\"after_revision\":2,\"operation_id\":\"op_b11607ab48bae8c308337e49c24b6014\",\"schema\":\"hiroute.worker-dependency-selection-compensation/v1\"}}]},{\"sequence\":3,\"kind\":\"compile_publication\",\"deterministic_input_digest\":\"sha256:c9171635fed9ca419452391118a4de7a2afe2190f23346129db8cd0fad57e365\",\"status\":\"pending\",\"attempts\":0,\"effects\":[]},{\"sequence\":4,\"kind\":\"apply_agent_artifacts\",\"deterministic_input_digest\":\"sha256:5ac4612884ca3ffb3894cdd5bfa06ddfa853f083ca2bdf5605db6cc1f6922b51\",\"status\":\"pending\",\"attempts\":0,\"effects\":[]},{\"sequence\":5,\"kind\":\"activate\",\"deterministic_input_digest\":\"sha256:e522a4f844eb520088412ae184c9dc4b0cc2c8ca509e02b8c269b8eda7c1ae8b\",\"status\":\"pending\",\"attempts\":0,\"effects\":[]}],\"safe_error_code\":null}",
+ 1791051525,
+ 1791051525
+ ],
+ [
+ "op_eae94ac62ab719efa325df7f93567385",
+ "personal/default",
+ "interactive-user",
+ "SelectWorkerDependencies",
+ "before",
+ "sha256:6e7a07e13ebfac57bd3b26c1420041a565e0494f7419773bf83d498fb15b93ba",
+ "sha256:4284c7cee75159b561216a0a37f456906bce149068e4cbedfd386ebbd9c02d5a",
+ "succeeded",
+ 1,
+ "{\"schema_version\":2,\"operation_id\":\"op_eae94ac62ab719efa325df7f93567385\",\"workspace_id\":\"personal/default\",\"idempotency\":{\"principal\":\"interactive-user\",\"operation_kind\":\"SelectWorkerDependencies\",\"key\":\"before\"},\"request_digest\":\"sha256:6e7a07e13ebfac57bd3b26c1420041a565e0494f7419773bf83d498fb15b93ba\",\"accepted_digest\":\"sha256:4284c7cee75159b561216a0a37f456906bce149068e4cbedfd386ebbd9c02d5a\",\"expected_revisions\":{\"target\":0},\"plan\":{\"control\":{},\"credential_pool\":null,\"external\":[],\"runtime\":[],\"schema\":\"hiroute.operation-input/v1\",\"secrets\":[],\"spec\":{\"command_id\":\"worker.dependencies.select\",\"desired_state\":{\"adapter_path\":\"/opt/old-installation/adapter.js\",\"cli_path\":\"/opt/old-installation/cli\",\"harness\":\"claude_code\",\"node_path\":\"/opt/old-installation/node\"},\"resource_id\":\"worker-dependency-selection/claude_code\",\"schema_version\":{\"major\":1,\"minor\":0}},\"worker_dependency_selection\":{\"after_selection\":{\"adapter_path\":\"/opt/old-installation/adapter.js\",\"cli_path\":\"/opt/old-installation/cli\",\"harness\":\"claude_code\",\"node_path\":\"/opt/old-installation/node\"},\"before_revision\":0}},\"state\":\"succeeded\",\"generation\":1,\"steps\":[{\"sequence\":0,\"kind\":\"prepare\",\"deterministic_input_digest\":\"sha256:97cb3489d6097eb4baaf6aa6b74ce4fb2ee133a8352057b80c3a60f577c704bb\",\"status\":\"applied\",\"attempts\":1,\"effects\":[]},{\"sequence\":1,\"kind\":\"apply_secrets\",\"deterministic_input_digest\":\"sha256:75f16a5c021b74501c720d197122fe1e672dc27c9025d026d257aad66e6561b4\",\"status\":\"applied\",\"attempts\":1,\"effects\":[]},{\"sequence\":2,\"kind\":\"materialize_sources\",\"deterministic_input_digest\":\"sha256:6220ed5fce19edfce51546b542d6445b8119bcfe482b7497fd255603661c80d0\",\"status\":\"applied\",\"attempts\":1,\"effects\":[{\"effect_id\":\"worker-dependency-selection:claude_code\",\"kind\":\"control\",\"target\":\"personal/default/worker-dependency-selection/claude_code\",\"after_fingerprint\":\"sha256:15dde49e810f048a183e48b85f75a7bb39d06b9ba39c915f105876122a24c3b0\",\"compensation\":{\"after_revision\":1,\"operation_id\":\"op_eae94ac62ab719efa325df7f93567385\",\"schema\":\"hiroute.worker-dependency-selection-compensation/v1\"}}]},{\"sequence\":3,\"kind\":\"compile_publication\",\"deterministic_input_digest\":\"sha256:c9171635fed9ca419452391118a4de7a2afe2190f23346129db8cd0fad57e365\",\"status\":\"applied\",\"attempts\":1,\"effects\":[]},{\"sequence\":4,\"kind\":\"apply_agent_artifacts\",\"deterministic_input_digest\":\"sha256:5ac4612884ca3ffb3894cdd5bfa06ddfa853f083ca2bdf5605db6cc1f6922b51\",\"status\":\"applied\",\"attempts\":1,\"effects\":[]},{\"sequence\":5,\"kind\":\"activate\",\"deterministic_input_digest\":\"sha256:e522a4f844eb520088412ae184c9dc4b0cc2c8ca509e02b8c269b8eda7c1ae8b\",\"status\":\"applied\",\"attempts\":1,\"effects\":[]}],\"safe_error_code\":null}",
+ 1791051525,
+ 1791051525
+ ]
+ ]
+ },
+ "worker_dependency_selection_effects": {
+ "columns": [
+ "operation_id",
+ "workspace_id",
+ "harness",
+ "before_revision",
+ "before_json",
+ "before_owner_operation_id",
+ "after_revision",
+ "after_json",
+ "activated",
+ "compensated"
+ ],
+ "rows": [
+ [
+ "op_b11607ab48bae8c308337e49c24b6014",
+ "personal/default",
+ "claude_code",
+ 1,
+ "{\"harness\":\"claude_code\",\"adapter_path\":\"/opt/old-installation/adapter.js\",\"cli_path\":\"/opt/old-installation/cli\",\"node_path\":\"/opt/old-installation/node\"}",
+ "op_eae94ac62ab719efa325df7f93567385",
+ 2,
+ "{\"harness\":\"claude_code\",\"adapter_path\":\"/opt/new-installation/adapter.js\",\"cli_path\":\"/opt/new-installation/cli\",\"node_path\":\"/opt/new-installation/node\"}",
+ 0,
+ 0
+ ],
+ [
+ "op_eae94ac62ab719efa325df7f93567385",
+ "personal/default",
+ "claude_code",
+ 0,
+ null,
+ null,
+ 1,
+ "{\"harness\":\"claude_code\",\"adapter_path\":\"/opt/old-installation/adapter.js\",\"cli_path\":\"/opt/old-installation/cli\",\"node_path\":\"/opt/old-installation/node\"}",
+ 1,
+ 0
+ ]
+ ]
+ },
+ "worker_dependency_selections": {
+ "columns": [
+ "workspace_id",
+ "harness",
+ "revision",
+ "selection_json",
+ "owner_operation_id",
+ "updated_at"
+ ],
+ "rows": [
+ [
+ "personal/default",
+ "claude_code",
+ 1,
+ "{\"harness\":\"claude_code\",\"adapter_path\":\"/opt/old-installation/adapter.js\",\"cli_path\":\"/opt/old-installation/cli\",\"node_path\":\"/opt/old-installation/node\"}",
+ "op_eae94ac62ab719efa325df7f93567385",
+ 1791051525
+ ]
+ ]
+ },
+ "writer_claim": {
+ "columns": [
+ "singleton",
+ "operation_id",
+ "admitted_at"
+ ],
+ "rows": [
+ [
+ 1,
+ "op_b11607ab48bae8c308337e49c24b6014",
+ 1791051525
+ ]
+ ]
+ }
+ }
+ },
+ {
+ "effect": {
+ "after_fingerprint": "sha256:5c46e954818b7b9968c004d4e949616c55917270c5aa09782d6c2fb6527547fa",
+ "before_fingerprint": "sha256:15dde49e810f048a183e48b85f75a7bb39d06b9ba39c915f105876122a24c3b0",
+ "compensation": {
+ "after_revision": 2,
+ "operation_id": "op_3824e5057bdb23d4b2bf76685d797b4e",
+ "schema": "hiroute.worker-dependency-selection-compensation/v1"
+ },
+ "effect_id": "worker-dependency-selection:claude_code",
+ "kind": "control",
+ "target": "personal/default/worker-dependency-selection/claude_code"
+ },
+ "harness": "claude_code",
+ "operation_id": "op_3824e5057bdb23d4b2bf76685d797b4e",
+ "previous_effect": {
+ "after_fingerprint": "sha256:15dde49e810f048a183e48b85f75a7bb39d06b9ba39c915f105876122a24c3b0",
+ "compensation": {
+ "after_revision": 1,
+ "operation_id": "op_eae94ac62ab719efa325df7f93567385",
+ "schema": "hiroute.worker-dependency-selection-compensation/v1"
+ },
+ "effect_id": "worker-dependency-selection:claude_code",
+ "kind": "control",
+ "target": "personal/default/worker-dependency-selection/claude_code"
+ },
+ "stage": "activated",
+ "tables": {
+ "operation_steps": {
+ "columns": [
+ "operation_id",
+ "step_no",
+ "step_kind",
+ "state",
+ "step_json"
+ ],
+ "rows": [
+ [
+ "op_3824e5057bdb23d4b2bf76685d797b4e",
+ 0,
+ "prepare",
+ "applied",
+ "{\"schema\":\"hiroute.operation-step/v1\",\"step\":{\"attempts\":1,\"deterministic_input_digest\":\"sha256:35e058b9f2ea4948e5c439a419db29165314cb9afc20def152639e996cd606c9\",\"effects\":[],\"kind\":\"prepare\",\"sequence\":0,\"status\":\"applied\"}}"
+ ],
+ [
+ "op_3824e5057bdb23d4b2bf76685d797b4e",
+ 1,
+ "apply_secrets",
+ "applied",
+ "{\"schema\":\"hiroute.operation-step/v1\",\"step\":{\"attempts\":1,\"deterministic_input_digest\":\"sha256:75f16a5c021b74501c720d197122fe1e672dc27c9025d026d257aad66e6561b4\",\"effects\":[],\"kind\":\"apply_secrets\",\"sequence\":1,\"status\":\"applied\"}}"
+ ],
+ [
+ "op_3824e5057bdb23d4b2bf76685d797b4e",
+ 2,
+ "materialize_sources",
+ "applied",
+ "{\"schema\":\"hiroute.operation-step/v1\",\"step\":{\"attempts\":1,\"deterministic_input_digest\":\"sha256:67dc83911298082049d92d0306c35b482352d2a5ecea631c149337e12e5f05a7\",\"effects\":[{\"after_fingerprint\":\"sha256:5c46e954818b7b9968c004d4e949616c55917270c5aa09782d6c2fb6527547fa\",\"before_fingerprint\":\"sha256:15dde49e810f048a183e48b85f75a7bb39d06b9ba39c915f105876122a24c3b0\",\"compensation\":{\"after_revision\":2,\"operation_id\":\"op_3824e5057bdb23d4b2bf76685d797b4e\",\"schema\":\"hiroute.worker-dependency-selection-compensation/v1\"},\"effect_id\":\"worker-dependency-selection:claude_code\",\"kind\":\"control\",\"target\":\"personal/default/worker-dependency-selection/claude_code\"}],\"kind\":\"materialize_sources\",\"sequence\":2,\"status\":\"applied\"}}"
+ ],
+ [
+ "op_3824e5057bdb23d4b2bf76685d797b4e",
+ 3,
+ "compile_publication",
+ "applied",
+ "{\"schema\":\"hiroute.operation-step/v1\",\"step\":{\"attempts\":1,\"deterministic_input_digest\":\"sha256:c9171635fed9ca419452391118a4de7a2afe2190f23346129db8cd0fad57e365\",\"effects\":[],\"kind\":\"compile_publication\",\"sequence\":3,\"status\":\"applied\"}}"
+ ],
+ [
+ "op_3824e5057bdb23d4b2bf76685d797b4e",
+ 4,
+ "apply_agent_artifacts",
+ "applied",
+ "{\"schema\":\"hiroute.operation-step/v1\",\"step\":{\"attempts\":1,\"deterministic_input_digest\":\"sha256:5ac4612884ca3ffb3894cdd5bfa06ddfa853f083ca2bdf5605db6cc1f6922b51\",\"effects\":[],\"kind\":\"apply_agent_artifacts\",\"sequence\":4,\"status\":\"applied\"}}"
+ ],
+ [
+ "op_3824e5057bdb23d4b2bf76685d797b4e",
+ 5,
+ "activate",
+ "applied",
+ "{\"schema\":\"hiroute.operation-step/v1\",\"step\":{\"attempts\":1,\"deterministic_input_digest\":\"sha256:e522a4f844eb520088412ae184c9dc4b0cc2c8ca509e02b8c269b8eda7c1ae8b\",\"effects\":[],\"kind\":\"activate\",\"sequence\":5,\"status\":\"applied\"}}"
+ ],
+ [
+ "op_eae94ac62ab719efa325df7f93567385",
+ 0,
+ "prepare",
+ "applied",
+ "{\"schema\":\"hiroute.operation-step/v1\",\"step\":{\"attempts\":1,\"deterministic_input_digest\":\"sha256:97cb3489d6097eb4baaf6aa6b74ce4fb2ee133a8352057b80c3a60f577c704bb\",\"effects\":[],\"kind\":\"prepare\",\"sequence\":0,\"status\":\"applied\"}}"
+ ],
+ [
+ "op_eae94ac62ab719efa325df7f93567385",
+ 1,
+ "apply_secrets",
+ "applied",
+ "{\"schema\":\"hiroute.operation-step/v1\",\"step\":{\"attempts\":1,\"deterministic_input_digest\":\"sha256:75f16a5c021b74501c720d197122fe1e672dc27c9025d026d257aad66e6561b4\",\"effects\":[],\"kind\":\"apply_secrets\",\"sequence\":1,\"status\":\"applied\"}}"
+ ],
+ [
+ "op_eae94ac62ab719efa325df7f93567385",
+ 2,
+ "materialize_sources",
+ "applied",
+ "{\"schema\":\"hiroute.operation-step/v1\",\"step\":{\"attempts\":1,\"deterministic_input_digest\":\"sha256:6220ed5fce19edfce51546b542d6445b8119bcfe482b7497fd255603661c80d0\",\"effects\":[{\"after_fingerprint\":\"sha256:15dde49e810f048a183e48b85f75a7bb39d06b9ba39c915f105876122a24c3b0\",\"compensation\":{\"after_revision\":1,\"operation_id\":\"op_eae94ac62ab719efa325df7f93567385\",\"schema\":\"hiroute.worker-dependency-selection-compensation/v1\"},\"effect_id\":\"worker-dependency-selection:claude_code\",\"kind\":\"control\",\"target\":\"personal/default/worker-dependency-selection/claude_code\"}],\"kind\":\"materialize_sources\",\"sequence\":2,\"status\":\"applied\"}}"
+ ],
+ [
+ "op_eae94ac62ab719efa325df7f93567385",
+ 3,
+ "compile_publication",
+ "applied",
+ "{\"schema\":\"hiroute.operation-step/v1\",\"step\":{\"attempts\":1,\"deterministic_input_digest\":\"sha256:c9171635fed9ca419452391118a4de7a2afe2190f23346129db8cd0fad57e365\",\"effects\":[],\"kind\":\"compile_publication\",\"sequence\":3,\"status\":\"applied\"}}"
+ ],
+ [
+ "op_eae94ac62ab719efa325df7f93567385",
+ 4,
+ "apply_agent_artifacts",
+ "applied",
+ "{\"schema\":\"hiroute.operation-step/v1\",\"step\":{\"attempts\":1,\"deterministic_input_digest\":\"sha256:5ac4612884ca3ffb3894cdd5bfa06ddfa853f083ca2bdf5605db6cc1f6922b51\",\"effects\":[],\"kind\":\"apply_agent_artifacts\",\"sequence\":4,\"status\":\"applied\"}}"
+ ],
+ [
+ "op_eae94ac62ab719efa325df7f93567385",
+ 5,
+ "activate",
+ "applied",
+ "{\"schema\":\"hiroute.operation-step/v1\",\"step\":{\"attempts\":1,\"deterministic_input_digest\":\"sha256:e522a4f844eb520088412ae184c9dc4b0cc2c8ca509e02b8c269b8eda7c1ae8b\",\"effects\":[],\"kind\":\"activate\",\"sequence\":5,\"status\":\"applied\"}}"
+ ]
+ ]
+ },
+ "operations": {
+ "columns": [
+ "operation_id",
+ "workspace_id",
+ "principal",
+ "operation_kind",
+ "idempotency_key",
+ "request_digest",
+ "accepted_change_digest",
+ "state",
+ "generation",
+ "operation_json",
+ "created_at",
+ "updated_at"
+ ],
+ "rows": [
+ [
+ "op_3824e5057bdb23d4b2bf76685d797b4e",
+ "personal/default",
+ "interactive-user",
+ "SelectWorkerDependencies",
+ "activated",
+ "sha256:c423c380c2151df5da63235d47c4b3c95e392f31718e3d3e4eb7455c1443ea66",
+ "sha256:f002abe29724e3065c4f1a1a71f21c20a93c6bffa99bbf543b72dc5c3ffce6e1",
+ "activating",
+ 1,
+ "{\"schema_version\":2,\"operation_id\":\"op_3824e5057bdb23d4b2bf76685d797b4e\",\"workspace_id\":\"personal/default\",\"idempotency\":{\"principal\":\"interactive-user\",\"operation_kind\":\"SelectWorkerDependencies\",\"key\":\"activated\"},\"request_digest\":\"sha256:c423c380c2151df5da63235d47c4b3c95e392f31718e3d3e4eb7455c1443ea66\",\"accepted_digest\":\"sha256:f002abe29724e3065c4f1a1a71f21c20a93c6bffa99bbf543b72dc5c3ffce6e1\",\"expected_revisions\":{\"target\":1},\"plan\":{\"control\":{},\"credential_pool\":null,\"external\":[],\"runtime\":[],\"schema\":\"hiroute.operation-input/v1\",\"secrets\":[],\"spec\":{\"command_id\":\"worker.dependencies.select\",\"desired_state\":{\"adapter_path\":\"/opt/new-installation/adapter.js\",\"cli_path\":\"/opt/new-installation/cli\",\"harness\":\"claude_code\",\"node_path\":\"/opt/new-installation/node\"},\"resource_id\":\"worker-dependency-selection/claude_code\",\"schema_version\":{\"major\":1,\"minor\":0}},\"worker_dependency_selection\":{\"after_selection\":{\"adapter_path\":\"/opt/new-installation/adapter.js\",\"cli_path\":\"/opt/new-installation/cli\",\"harness\":\"claude_code\",\"node_path\":\"/opt/new-installation/node\"},\"before_revision\":1}},\"state\":\"activating\",\"generation\":1,\"steps\":[{\"sequence\":0,\"kind\":\"prepare\",\"deterministic_input_digest\":\"sha256:35e058b9f2ea4948e5c439a419db29165314cb9afc20def152639e996cd606c9\",\"status\":\"applied\",\"attempts\":1,\"effects\":[]},{\"sequence\":1,\"kind\":\"apply_secrets\",\"deterministic_input_digest\":\"sha256:75f16a5c021b74501c720d197122fe1e672dc27c9025d026d257aad66e6561b4\",\"status\":\"applied\",\"attempts\":1,\"effects\":[]},{\"sequence\":2,\"kind\":\"materialize_sources\",\"deterministic_input_digest\":\"sha256:67dc83911298082049d92d0306c35b482352d2a5ecea631c149337e12e5f05a7\",\"status\":\"applied\",\"attempts\":1,\"effects\":[{\"effect_id\":\"worker-dependency-selection:claude_code\",\"kind\":\"control\",\"target\":\"personal/default/worker-dependency-selection/claude_code\",\"before_fingerprint\":\"sha256:15dde49e810f048a183e48b85f75a7bb39d06b9ba39c915f105876122a24c3b0\",\"after_fingerprint\":\"sha256:5c46e954818b7b9968c004d4e949616c55917270c5aa09782d6c2fb6527547fa\",\"compensation\":{\"after_revision\":2,\"operation_id\":\"op_3824e5057bdb23d4b2bf76685d797b4e\",\"schema\":\"hiroute.worker-dependency-selection-compensation/v1\"}}]},{\"sequence\":3,\"kind\":\"compile_publication\",\"deterministic_input_digest\":\"sha256:c9171635fed9ca419452391118a4de7a2afe2190f23346129db8cd0fad57e365\",\"status\":\"applied\",\"attempts\":1,\"effects\":[]},{\"sequence\":4,\"kind\":\"apply_agent_artifacts\",\"deterministic_input_digest\":\"sha256:5ac4612884ca3ffb3894cdd5bfa06ddfa853f083ca2bdf5605db6cc1f6922b51\",\"status\":\"applied\",\"attempts\":1,\"effects\":[]},{\"sequence\":5,\"kind\":\"activate\",\"deterministic_input_digest\":\"sha256:e522a4f844eb520088412ae184c9dc4b0cc2c8ca509e02b8c269b8eda7c1ae8b\",\"status\":\"applied\",\"attempts\":1,\"effects\":[]}],\"safe_error_code\":null}",
+ 1791051525,
+ 1791051525
+ ],
+ [
+ "op_eae94ac62ab719efa325df7f93567385",
+ "personal/default",
+ "interactive-user",
+ "SelectWorkerDependencies",
+ "before",
+ "sha256:6e7a07e13ebfac57bd3b26c1420041a565e0494f7419773bf83d498fb15b93ba",
+ "sha256:4284c7cee75159b561216a0a37f456906bce149068e4cbedfd386ebbd9c02d5a",
+ "succeeded",
+ 1,
+ "{\"schema_version\":2,\"operation_id\":\"op_eae94ac62ab719efa325df7f93567385\",\"workspace_id\":\"personal/default\",\"idempotency\":{\"principal\":\"interactive-user\",\"operation_kind\":\"SelectWorkerDependencies\",\"key\":\"before\"},\"request_digest\":\"sha256:6e7a07e13ebfac57bd3b26c1420041a565e0494f7419773bf83d498fb15b93ba\",\"accepted_digest\":\"sha256:4284c7cee75159b561216a0a37f456906bce149068e4cbedfd386ebbd9c02d5a\",\"expected_revisions\":{\"target\":0},\"plan\":{\"control\":{},\"credential_pool\":null,\"external\":[],\"runtime\":[],\"schema\":\"hiroute.operation-input/v1\",\"secrets\":[],\"spec\":{\"command_id\":\"worker.dependencies.select\",\"desired_state\":{\"adapter_path\":\"/opt/old-installation/adapter.js\",\"cli_path\":\"/opt/old-installation/cli\",\"harness\":\"claude_code\",\"node_path\":\"/opt/old-installation/node\"},\"resource_id\":\"worker-dependency-selection/claude_code\",\"schema_version\":{\"major\":1,\"minor\":0}},\"worker_dependency_selection\":{\"after_selection\":{\"adapter_path\":\"/opt/old-installation/adapter.js\",\"cli_path\":\"/opt/old-installation/cli\",\"harness\":\"claude_code\",\"node_path\":\"/opt/old-installation/node\"},\"before_revision\":0}},\"state\":\"succeeded\",\"generation\":1,\"steps\":[{\"sequence\":0,\"kind\":\"prepare\",\"deterministic_input_digest\":\"sha256:97cb3489d6097eb4baaf6aa6b74ce4fb2ee133a8352057b80c3a60f577c704bb\",\"status\":\"applied\",\"attempts\":1,\"effects\":[]},{\"sequence\":1,\"kind\":\"apply_secrets\",\"deterministic_input_digest\":\"sha256:75f16a5c021b74501c720d197122fe1e672dc27c9025d026d257aad66e6561b4\",\"status\":\"applied\",\"attempts\":1,\"effects\":[]},{\"sequence\":2,\"kind\":\"materialize_sources\",\"deterministic_input_digest\":\"sha256:6220ed5fce19edfce51546b542d6445b8119bcfe482b7497fd255603661c80d0\",\"status\":\"applied\",\"attempts\":1,\"effects\":[{\"effect_id\":\"worker-dependency-selection:claude_code\",\"kind\":\"control\",\"target\":\"personal/default/worker-dependency-selection/claude_code\",\"after_fingerprint\":\"sha256:15dde49e810f048a183e48b85f75a7bb39d06b9ba39c915f105876122a24c3b0\",\"compensation\":{\"after_revision\":1,\"operation_id\":\"op_eae94ac62ab719efa325df7f93567385\",\"schema\":\"hiroute.worker-dependency-selection-compensation/v1\"}}]},{\"sequence\":3,\"kind\":\"compile_publication\",\"deterministic_input_digest\":\"sha256:c9171635fed9ca419452391118a4de7a2afe2190f23346129db8cd0fad57e365\",\"status\":\"applied\",\"attempts\":1,\"effects\":[]},{\"sequence\":4,\"kind\":\"apply_agent_artifacts\",\"deterministic_input_digest\":\"sha256:5ac4612884ca3ffb3894cdd5bfa06ddfa853f083ca2bdf5605db6cc1f6922b51\",\"status\":\"applied\",\"attempts\":1,\"effects\":[]},{\"sequence\":5,\"kind\":\"activate\",\"deterministic_input_digest\":\"sha256:e522a4f844eb520088412ae184c9dc4b0cc2c8ca509e02b8c269b8eda7c1ae8b\",\"status\":\"applied\",\"attempts\":1,\"effects\":[]}],\"safe_error_code\":null}",
+ 1791051525,
+ 1791051525
+ ]
+ ]
+ },
+ "worker_dependency_selection_effects": {
+ "columns": [
+ "operation_id",
+ "workspace_id",
+ "harness",
+ "before_revision",
+ "before_json",
+ "before_owner_operation_id",
+ "after_revision",
+ "after_json",
+ "activated",
+ "compensated"
+ ],
+ "rows": [
+ [
+ "op_3824e5057bdb23d4b2bf76685d797b4e",
+ "personal/default",
+ "claude_code",
+ 1,
+ "{\"harness\":\"claude_code\",\"adapter_path\":\"/opt/old-installation/adapter.js\",\"cli_path\":\"/opt/old-installation/cli\",\"node_path\":\"/opt/old-installation/node\"}",
+ "op_eae94ac62ab719efa325df7f93567385",
+ 2,
+ "{\"harness\":\"claude_code\",\"adapter_path\":\"/opt/new-installation/adapter.js\",\"cli_path\":\"/opt/new-installation/cli\",\"node_path\":\"/opt/new-installation/node\"}",
+ 1,
+ 0
+ ],
+ [
+ "op_eae94ac62ab719efa325df7f93567385",
+ "personal/default",
+ "claude_code",
+ 0,
+ null,
+ null,
+ 1,
+ "{\"harness\":\"claude_code\",\"adapter_path\":\"/opt/old-installation/adapter.js\",\"cli_path\":\"/opt/old-installation/cli\",\"node_path\":\"/opt/old-installation/node\"}",
+ 1,
+ 0
+ ]
+ ]
+ },
+ "worker_dependency_selections": {
+ "columns": [
+ "workspace_id",
+ "harness",
+ "revision",
+ "selection_json",
+ "owner_operation_id",
+ "updated_at"
+ ],
+ "rows": [
+ [
+ "personal/default",
+ "claude_code",
+ 2,
+ "{\"harness\":\"claude_code\",\"adapter_path\":\"/opt/new-installation/adapter.js\",\"cli_path\":\"/opt/new-installation/cli\",\"node_path\":\"/opt/new-installation/node\"}",
+ "op_3824e5057bdb23d4b2bf76685d797b4e",
+ 1791051525
+ ]
+ ]
+ },
+ "writer_claim": {
+ "columns": [
+ "singleton",
+ "operation_id",
+ "admitted_at"
+ ],
+ "rows": [
+ [
+ 1,
+ "op_3824e5057bdb23d4b2bf76685d797b4e",
+ 1791051525
+ ]
+ ]
+ }
+ }
+ },
+ {
+ "effect": {
+ "after_fingerprint": "sha256:5c46e954818b7b9968c004d4e949616c55917270c5aa09782d6c2fb6527547fa",
+ "before_fingerprint": "sha256:15dde49e810f048a183e48b85f75a7bb39d06b9ba39c915f105876122a24c3b0",
+ "compensation": {
+ "after_revision": 2,
+ "operation_id": "op_6693417061f9f840b88fa9f61f367441",
+ "schema": "hiroute.worker-dependency-selection-compensation/v1"
+ },
+ "effect_id": "worker-dependency-selection:claude_code",
+ "kind": "control",
+ "target": "personal/default/worker-dependency-selection/claude_code"
+ },
+ "harness": "claude_code",
+ "operation_id": "op_6693417061f9f840b88fa9f61f367441",
+ "previous_effect": {
+ "after_fingerprint": "sha256:15dde49e810f048a183e48b85f75a7bb39d06b9ba39c915f105876122a24c3b0",
+ "compensation": {
+ "after_revision": 1,
+ "operation_id": "op_eae94ac62ab719efa325df7f93567385",
+ "schema": "hiroute.worker-dependency-selection-compensation/v1"
+ },
+ "effect_id": "worker-dependency-selection:claude_code",
+ "kind": "control",
+ "target": "personal/default/worker-dependency-selection/claude_code"
+ },
+ "stage": "succeeded",
+ "tables": {
+ "operation_steps": {
+ "columns": [
+ "operation_id",
+ "step_no",
+ "step_kind",
+ "state",
+ "step_json"
+ ],
+ "rows": [
+ [
+ "op_6693417061f9f840b88fa9f61f367441",
+ 0,
+ "prepare",
+ "applied",
+ "{\"schema\":\"hiroute.operation-step/v1\",\"step\":{\"attempts\":1,\"deterministic_input_digest\":\"sha256:35e058b9f2ea4948e5c439a419db29165314cb9afc20def152639e996cd606c9\",\"effects\":[],\"kind\":\"prepare\",\"sequence\":0,\"status\":\"applied\"}}"
+ ],
+ [
+ "op_6693417061f9f840b88fa9f61f367441",
+ 1,
+ "apply_secrets",
+ "applied",
+ "{\"schema\":\"hiroute.operation-step/v1\",\"step\":{\"attempts\":1,\"deterministic_input_digest\":\"sha256:75f16a5c021b74501c720d197122fe1e672dc27c9025d026d257aad66e6561b4\",\"effects\":[],\"kind\":\"apply_secrets\",\"sequence\":1,\"status\":\"applied\"}}"
+ ],
+ [
+ "op_6693417061f9f840b88fa9f61f367441",
+ 2,
+ "materialize_sources",
+ "applied",
+ "{\"schema\":\"hiroute.operation-step/v1\",\"step\":{\"attempts\":1,\"deterministic_input_digest\":\"sha256:67dc83911298082049d92d0306c35b482352d2a5ecea631c149337e12e5f05a7\",\"effects\":[{\"after_fingerprint\":\"sha256:5c46e954818b7b9968c004d4e949616c55917270c5aa09782d6c2fb6527547fa\",\"before_fingerprint\":\"sha256:15dde49e810f048a183e48b85f75a7bb39d06b9ba39c915f105876122a24c3b0\",\"compensation\":{\"after_revision\":2,\"operation_id\":\"op_6693417061f9f840b88fa9f61f367441\",\"schema\":\"hiroute.worker-dependency-selection-compensation/v1\"},\"effect_id\":\"worker-dependency-selection:claude_code\",\"kind\":\"control\",\"target\":\"personal/default/worker-dependency-selection/claude_code\"}],\"kind\":\"materialize_sources\",\"sequence\":2,\"status\":\"applied\"}}"
+ ],
+ [
+ "op_6693417061f9f840b88fa9f61f367441",
+ 3,
+ "compile_publication",
+ "applied",
+ "{\"schema\":\"hiroute.operation-step/v1\",\"step\":{\"attempts\":1,\"deterministic_input_digest\":\"sha256:c9171635fed9ca419452391118a4de7a2afe2190f23346129db8cd0fad57e365\",\"effects\":[],\"kind\":\"compile_publication\",\"sequence\":3,\"status\":\"applied\"}}"
+ ],
+ [
+ "op_6693417061f9f840b88fa9f61f367441",
+ 4,
+ "apply_agent_artifacts",
+ "applied",
+ "{\"schema\":\"hiroute.operation-step/v1\",\"step\":{\"attempts\":1,\"deterministic_input_digest\":\"sha256:5ac4612884ca3ffb3894cdd5bfa06ddfa853f083ca2bdf5605db6cc1f6922b51\",\"effects\":[],\"kind\":\"apply_agent_artifacts\",\"sequence\":4,\"status\":\"applied\"}}"
+ ],
+ [
+ "op_6693417061f9f840b88fa9f61f367441",
+ 5,
+ "activate",
+ "applied",
+ "{\"schema\":\"hiroute.operation-step/v1\",\"step\":{\"attempts\":1,\"deterministic_input_digest\":\"sha256:e522a4f844eb520088412ae184c9dc4b0cc2c8ca509e02b8c269b8eda7c1ae8b\",\"effects\":[],\"kind\":\"activate\",\"sequence\":5,\"status\":\"applied\"}}"
+ ],
+ [
+ "op_eae94ac62ab719efa325df7f93567385",
+ 0,
+ "prepare",
+ "applied",
+ "{\"schema\":\"hiroute.operation-step/v1\",\"step\":{\"attempts\":1,\"deterministic_input_digest\":\"sha256:97cb3489d6097eb4baaf6aa6b74ce4fb2ee133a8352057b80c3a60f577c704bb\",\"effects\":[],\"kind\":\"prepare\",\"sequence\":0,\"status\":\"applied\"}}"
+ ],
+ [
+ "op_eae94ac62ab719efa325df7f93567385",
+ 1,
+ "apply_secrets",
+ "applied",
+ "{\"schema\":\"hiroute.operation-step/v1\",\"step\":{\"attempts\":1,\"deterministic_input_digest\":\"sha256:75f16a5c021b74501c720d197122fe1e672dc27c9025d026d257aad66e6561b4\",\"effects\":[],\"kind\":\"apply_secrets\",\"sequence\":1,\"status\":\"applied\"}}"
+ ],
+ [
+ "op_eae94ac62ab719efa325df7f93567385",
+ 2,
+ "materialize_sources",
+ "applied",
+ "{\"schema\":\"hiroute.operation-step/v1\",\"step\":{\"attempts\":1,\"deterministic_input_digest\":\"sha256:6220ed5fce19edfce51546b542d6445b8119bcfe482b7497fd255603661c80d0\",\"effects\":[{\"after_fingerprint\":\"sha256:15dde49e810f048a183e48b85f75a7bb39d06b9ba39c915f105876122a24c3b0\",\"compensation\":{\"after_revision\":1,\"operation_id\":\"op_eae94ac62ab719efa325df7f93567385\",\"schema\":\"hiroute.worker-dependency-selection-compensation/v1\"},\"effect_id\":\"worker-dependency-selection:claude_code\",\"kind\":\"control\",\"target\":\"personal/default/worker-dependency-selection/claude_code\"}],\"kind\":\"materialize_sources\",\"sequence\":2,\"status\":\"applied\"}}"
+ ],
+ [
+ "op_eae94ac62ab719efa325df7f93567385",
+ 3,
+ "compile_publication",
+ "applied",
+ "{\"schema\":\"hiroute.operation-step/v1\",\"step\":{\"attempts\":1,\"deterministic_input_digest\":\"sha256:c9171635fed9ca419452391118a4de7a2afe2190f23346129db8cd0fad57e365\",\"effects\":[],\"kind\":\"compile_publication\",\"sequence\":3,\"status\":\"applied\"}}"
+ ],
+ [
+ "op_eae94ac62ab719efa325df7f93567385",
+ 4,
+ "apply_agent_artifacts",
+ "applied",
+ "{\"schema\":\"hiroute.operation-step/v1\",\"step\":{\"attempts\":1,\"deterministic_input_digest\":\"sha256:5ac4612884ca3ffb3894cdd5bfa06ddfa853f083ca2bdf5605db6cc1f6922b51\",\"effects\":[],\"kind\":\"apply_agent_artifacts\",\"sequence\":4,\"status\":\"applied\"}}"
+ ],
+ [
+ "op_eae94ac62ab719efa325df7f93567385",
+ 5,
+ "activate",
+ "applied",
+ "{\"schema\":\"hiroute.operation-step/v1\",\"step\":{\"attempts\":1,\"deterministic_input_digest\":\"sha256:e522a4f844eb520088412ae184c9dc4b0cc2c8ca509e02b8c269b8eda7c1ae8b\",\"effects\":[],\"kind\":\"activate\",\"sequence\":5,\"status\":\"applied\"}}"
+ ]
+ ]
+ },
+ "operations": {
+ "columns": [
+ "operation_id",
+ "workspace_id",
+ "principal",
+ "operation_kind",
+ "idempotency_key",
+ "request_digest",
+ "accepted_change_digest",
+ "state",
+ "generation",
+ "operation_json",
+ "created_at",
+ "updated_at"
+ ],
+ "rows": [
+ [
+ "op_6693417061f9f840b88fa9f61f367441",
+ "personal/default",
+ "interactive-user",
+ "SelectWorkerDependencies",
+ "succeeded",
+ "sha256:333073c4155f0bd05323857095216a7ede54c22c565c7e1ab3f76223ebcb4b1a",
+ "sha256:f002abe29724e3065c4f1a1a71f21c20a93c6bffa99bbf543b72dc5c3ffce6e1",
+ "succeeded",
+ 1,
+ "{\"schema_version\":2,\"operation_id\":\"op_6693417061f9f840b88fa9f61f367441\",\"workspace_id\":\"personal/default\",\"idempotency\":{\"principal\":\"interactive-user\",\"operation_kind\":\"SelectWorkerDependencies\",\"key\":\"succeeded\"},\"request_digest\":\"sha256:333073c4155f0bd05323857095216a7ede54c22c565c7e1ab3f76223ebcb4b1a\",\"accepted_digest\":\"sha256:f002abe29724e3065c4f1a1a71f21c20a93c6bffa99bbf543b72dc5c3ffce6e1\",\"expected_revisions\":{\"target\":1},\"plan\":{\"control\":{},\"credential_pool\":null,\"external\":[],\"runtime\":[],\"schema\":\"hiroute.operation-input/v1\",\"secrets\":[],\"spec\":{\"command_id\":\"worker.dependencies.select\",\"desired_state\":{\"adapter_path\":\"/opt/new-installation/adapter.js\",\"cli_path\":\"/opt/new-installation/cli\",\"harness\":\"claude_code\",\"node_path\":\"/opt/new-installation/node\"},\"resource_id\":\"worker-dependency-selection/claude_code\",\"schema_version\":{\"major\":1,\"minor\":0}},\"worker_dependency_selection\":{\"after_selection\":{\"adapter_path\":\"/opt/new-installation/adapter.js\",\"cli_path\":\"/opt/new-installation/cli\",\"harness\":\"claude_code\",\"node_path\":\"/opt/new-installation/node\"},\"before_revision\":1}},\"state\":\"succeeded\",\"generation\":1,\"steps\":[{\"sequence\":0,\"kind\":\"prepare\",\"deterministic_input_digest\":\"sha256:35e058b9f2ea4948e5c439a419db29165314cb9afc20def152639e996cd606c9\",\"status\":\"applied\",\"attempts\":1,\"effects\":[]},{\"sequence\":1,\"kind\":\"apply_secrets\",\"deterministic_input_digest\":\"sha256:75f16a5c021b74501c720d197122fe1e672dc27c9025d026d257aad66e6561b4\",\"status\":\"applied\",\"attempts\":1,\"effects\":[]},{\"sequence\":2,\"kind\":\"materialize_sources\",\"deterministic_input_digest\":\"sha256:67dc83911298082049d92d0306c35b482352d2a5ecea631c149337e12e5f05a7\",\"status\":\"applied\",\"attempts\":1,\"effects\":[{\"effect_id\":\"worker-dependency-selection:claude_code\",\"kind\":\"control\",\"target\":\"personal/default/worker-dependency-selection/claude_code\",\"before_fingerprint\":\"sha256:15dde49e810f048a183e48b85f75a7bb39d06b9ba39c915f105876122a24c3b0\",\"after_fingerprint\":\"sha256:5c46e954818b7b9968c004d4e949616c55917270c5aa09782d6c2fb6527547fa\",\"compensation\":{\"after_revision\":2,\"operation_id\":\"op_6693417061f9f840b88fa9f61f367441\",\"schema\":\"hiroute.worker-dependency-selection-compensation/v1\"}}]},{\"sequence\":3,\"kind\":\"compile_publication\",\"deterministic_input_digest\":\"sha256:c9171635fed9ca419452391118a4de7a2afe2190f23346129db8cd0fad57e365\",\"status\":\"applied\",\"attempts\":1,\"effects\":[]},{\"sequence\":4,\"kind\":\"apply_agent_artifacts\",\"deterministic_input_digest\":\"sha256:5ac4612884ca3ffb3894cdd5bfa06ddfa853f083ca2bdf5605db6cc1f6922b51\",\"status\":\"applied\",\"attempts\":1,\"effects\":[]},{\"sequence\":5,\"kind\":\"activate\",\"deterministic_input_digest\":\"sha256:e522a4f844eb520088412ae184c9dc4b0cc2c8ca509e02b8c269b8eda7c1ae8b\",\"status\":\"applied\",\"attempts\":1,\"effects\":[]}],\"safe_error_code\":null}",
+ 1791051525,
+ 1791051525
+ ],
+ [
+ "op_eae94ac62ab719efa325df7f93567385",
+ "personal/default",
+ "interactive-user",
+ "SelectWorkerDependencies",
+ "before",
+ "sha256:6e7a07e13ebfac57bd3b26c1420041a565e0494f7419773bf83d498fb15b93ba",
+ "sha256:4284c7cee75159b561216a0a37f456906bce149068e4cbedfd386ebbd9c02d5a",
+ "succeeded",
+ 1,
+ "{\"schema_version\":2,\"operation_id\":\"op_eae94ac62ab719efa325df7f93567385\",\"workspace_id\":\"personal/default\",\"idempotency\":{\"principal\":\"interactive-user\",\"operation_kind\":\"SelectWorkerDependencies\",\"key\":\"before\"},\"request_digest\":\"sha256:6e7a07e13ebfac57bd3b26c1420041a565e0494f7419773bf83d498fb15b93ba\",\"accepted_digest\":\"sha256:4284c7cee75159b561216a0a37f456906bce149068e4cbedfd386ebbd9c02d5a\",\"expected_revisions\":{\"target\":0},\"plan\":{\"control\":{},\"credential_pool\":null,\"external\":[],\"runtime\":[],\"schema\":\"hiroute.operation-input/v1\",\"secrets\":[],\"spec\":{\"command_id\":\"worker.dependencies.select\",\"desired_state\":{\"adapter_path\":\"/opt/old-installation/adapter.js\",\"cli_path\":\"/opt/old-installation/cli\",\"harness\":\"claude_code\",\"node_path\":\"/opt/old-installation/node\"},\"resource_id\":\"worker-dependency-selection/claude_code\",\"schema_version\":{\"major\":1,\"minor\":0}},\"worker_dependency_selection\":{\"after_selection\":{\"adapter_path\":\"/opt/old-installation/adapter.js\",\"cli_path\":\"/opt/old-installation/cli\",\"harness\":\"claude_code\",\"node_path\":\"/opt/old-installation/node\"},\"before_revision\":0}},\"state\":\"succeeded\",\"generation\":1,\"steps\":[{\"sequence\":0,\"kind\":\"prepare\",\"deterministic_input_digest\":\"sha256:97cb3489d6097eb4baaf6aa6b74ce4fb2ee133a8352057b80c3a60f577c704bb\",\"status\":\"applied\",\"attempts\":1,\"effects\":[]},{\"sequence\":1,\"kind\":\"apply_secrets\",\"deterministic_input_digest\":\"sha256:75f16a5c021b74501c720d197122fe1e672dc27c9025d026d257aad66e6561b4\",\"status\":\"applied\",\"attempts\":1,\"effects\":[]},{\"sequence\":2,\"kind\":\"materialize_sources\",\"deterministic_input_digest\":\"sha256:6220ed5fce19edfce51546b542d6445b8119bcfe482b7497fd255603661c80d0\",\"status\":\"applied\",\"attempts\":1,\"effects\":[{\"effect_id\":\"worker-dependency-selection:claude_code\",\"kind\":\"control\",\"target\":\"personal/default/worker-dependency-selection/claude_code\",\"after_fingerprint\":\"sha256:15dde49e810f048a183e48b85f75a7bb39d06b9ba39c915f105876122a24c3b0\",\"compensation\":{\"after_revision\":1,\"operation_id\":\"op_eae94ac62ab719efa325df7f93567385\",\"schema\":\"hiroute.worker-dependency-selection-compensation/v1\"}}]},{\"sequence\":3,\"kind\":\"compile_publication\",\"deterministic_input_digest\":\"sha256:c9171635fed9ca419452391118a4de7a2afe2190f23346129db8cd0fad57e365\",\"status\":\"applied\",\"attempts\":1,\"effects\":[]},{\"sequence\":4,\"kind\":\"apply_agent_artifacts\",\"deterministic_input_digest\":\"sha256:5ac4612884ca3ffb3894cdd5bfa06ddfa853f083ca2bdf5605db6cc1f6922b51\",\"status\":\"applied\",\"attempts\":1,\"effects\":[]},{\"sequence\":5,\"kind\":\"activate\",\"deterministic_input_digest\":\"sha256:e522a4f844eb520088412ae184c9dc4b0cc2c8ca509e02b8c269b8eda7c1ae8b\",\"status\":\"applied\",\"attempts\":1,\"effects\":[]}],\"safe_error_code\":null}",
+ 1791051525,
+ 1791051525
+ ]
+ ]
+ },
+ "worker_dependency_selection_effects": {
+ "columns": [
+ "operation_id",
+ "workspace_id",
+ "harness",
+ "before_revision",
+ "before_json",
+ "before_owner_operation_id",
+ "after_revision",
+ "after_json",
+ "activated",
+ "compensated"
+ ],
+ "rows": [
+ [
+ "op_6693417061f9f840b88fa9f61f367441",
+ "personal/default",
+ "claude_code",
+ 1,
+ "{\"harness\":\"claude_code\",\"adapter_path\":\"/opt/old-installation/adapter.js\",\"cli_path\":\"/opt/old-installation/cli\",\"node_path\":\"/opt/old-installation/node\"}",
+ "op_eae94ac62ab719efa325df7f93567385",
+ 2,
+ "{\"harness\":\"claude_code\",\"adapter_path\":\"/opt/new-installation/adapter.js\",\"cli_path\":\"/opt/new-installation/cli\",\"node_path\":\"/opt/new-installation/node\"}",
+ 1,
+ 0
+ ],
+ [
+ "op_eae94ac62ab719efa325df7f93567385",
+ "personal/default",
+ "claude_code",
+ 0,
+ null,
+ null,
+ 1,
+ "{\"harness\":\"claude_code\",\"adapter_path\":\"/opt/old-installation/adapter.js\",\"cli_path\":\"/opt/old-installation/cli\",\"node_path\":\"/opt/old-installation/node\"}",
+ 1,
+ 0
+ ]
+ ]
+ },
+ "worker_dependency_selections": {
+ "columns": [
+ "workspace_id",
+ "harness",
+ "revision",
+ "selection_json",
+ "owner_operation_id",
+ "updated_at"
+ ],
+ "rows": [
+ [
+ "personal/default",
+ "claude_code",
+ 2,
+ "{\"harness\":\"claude_code\",\"adapter_path\":\"/opt/new-installation/adapter.js\",\"cli_path\":\"/opt/new-installation/cli\",\"node_path\":\"/opt/new-installation/node\"}",
+ "op_6693417061f9f840b88fa9f61f367441",
+ 1791051525
+ ]
+ ]
+ },
+ "writer_claim": {
+ "columns": [
+ "singleton",
+ "operation_id",
+ "admitted_at"
+ ],
+ "rows": []
+ }
+ }
+ }
+ ],
+ "producer_revision": "cdbb2cec",
+ "schema_version": 23
+}
\ No newline at end of file
diff --git a/crates/local-storage/src/migrations/mod.rs b/crates/local-storage/src/migrations/mod.rs
index db6e1ea0..66e29dba 100644
--- a/crates/local-storage/src/migrations/mod.rs
+++ b/crates/local-storage/src/migrations/mod.rs
@@ -11,6 +11,9 @@ use hiroute_domain::CanonicalDigest;
mod agent_access_grant_v9;
mod agent_surface_checks_v22;
+mod agent_surface_checks_v25;
+#[cfg(test)]
+mod agent_surface_checks_v25_tests;
mod current_storage;
mod startup_format;
pub(crate) use startup_format::validate_startup_format;
@@ -31,16 +34,21 @@ mod integration_v17_tests;
mod plan_authoring_v10;
mod source_prices_v10;
mod subscription_v16;
+#[cfg(test)]
+mod upgrade_batch_recovery_tests;
mod worker_dependencies_v20;
+mod worker_dependencies_v24;
+#[cfg(test)]
+mod worker_dependencies_v24_tests;
mod worker_instance_v19;
#[cfg(test)]
mod convergence_tests;
-/// Converged integration format: Worker marker in all stores, Control subscription validations,
-/// and the single runtime-owned Worker concurrency setting. Older layouts migrate through a
-/// durable three-store backup set.
-pub const LATEST_SCHEMA_VERSION: u32 = 23;
+/// Current stable storage format, including native ACP Worker dependency selections.
+/// Production source admission is defined in `startup_format`; supported upgrades retain the
+/// existing durable three-store backup and recovery coordinator.
+pub const LATEST_SCHEMA_VERSION: u32 = 25;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum DatabaseKind {
@@ -63,7 +71,7 @@ pub(crate) fn open_database(
None,
None,
None,
- false,
+ None,
)
}
@@ -82,7 +90,7 @@ pub(crate) fn open_database_with_key_id(
key_id,
None,
None,
- false,
+ None,
)
}
@@ -100,6 +108,7 @@ pub(crate) fn open_database_from_set(
migration_backup_root: &Path,
expected_store_uuid: Option<&str>,
secret_binding: Option<&MigrationSecretBinding>,
+ target_schema_version: u32,
) -> Result<Connection, LocalStorageError> {
open_database_internal(
authority,
@@ -109,7 +118,7 @@ pub(crate) fn open_database_from_set(
secret_binding.map(|binding| &binding.key_id),
secret_binding,
expected_store_uuid,
- true,
+ Some(target_schema_version),
)
}
@@ -122,7 +131,7 @@ fn open_database_internal(
key_id: Option<&CanonicalDigest>,
secret_binding: Option<&MigrationSecretBinding>,
expected_store_uuid: Option<&str>,
- durable_set_prepared: bool,
+ durable_set_target: Option<u32>,
) -> Result<Connection, LocalStorageError> {
let parent = path.parent().ok_or(LocalStorageError::InvalidData)?;
prepare_owner_directory(parent)?;
@@ -146,7 +155,7 @@ fn open_database_internal(
migration_backup_root,
key_id,
secret_binding,
- durable_set_prepared,
+ durable_set_target,
)?;
if kind != DatabaseKind::Secrets {
initialize_storage_meta(&connection, expected_store_uuid)?;
@@ -251,20 +260,21 @@ fn migrate(
backup_root: &Path,
key_id: Option<&CanonicalDigest>,
secret_binding: Option<&MigrationSecretBinding>,
- durable_set_prepared: bool,
+ durable_set_target: Option<u32>,
) -> Result<(), LocalStorageError> {
+ let target = durable_set_target.unwrap_or(LATEST_SCHEMA_VERSION);
let current: u32 = connection.query_row("PRAGMA user_version", [], |row| row.get(0))?;
- if current > LATEST_SCHEMA_VERSION {
+ if target > LATEST_SCHEMA_VERSION || current > target {
return Err(LocalStorageError::InvalidData);
}
- if current > 0 && current < LATEST_SCHEMA_VERSION && !durable_set_prepared {
+ if current > 0 && current < target && durable_set_target.is_none() {
let backup_path = migration_backup_path(path, backup_root, current)?;
// `create_bound` reuses only the exact source identity/key/watermark manifest. A stale or
// half-published final is preserved and replaced by a unique fresh attempt.
SqliteBackup::create_bound(connection, &backup_path, key_id)?;
}
- for version in (current + 1)..=LATEST_SCHEMA_VERSION {
+ for version in (current + 1)..=target {
let transaction = connection.transaction_with_behavior(TransactionBehavior::Immediate)?;
transaction.execute_batch(migration_sql(kind, version)?)?;
if kind == DatabaseKind::Control && version == 8 {
@@ -423,10 +433,7 @@ impl MigrationSetCoordinator {
let set = if let Some(set) = durable_set {
set
} else {
- if versions
- .iter()
- .any(|version| *version == LATEST_SCHEMA_VERSION || *version == 0)
- {
+ if versions[0] == 0 || versions.iter().any(|version| *version != versions[0]) {
// A partially upgraded set without a durable source manifest has no exact group
// recovery point and must not be adopted.
return Err(LocalStorageError::InvalidData);
@@ -444,7 +451,15 @@ impl MigrationSetCoordinator {
LATEST_SCHEMA_VERSION,
)?
};
- if set.target_schema_version() != LATEST_SCHEMA_VERSION
+ if !matches!(set.target_schema_version(), 24 | LATEST_SCHEMA_VERSION)
+ || (set.target_schema_version() == 24
+ && [
+ set.control.manifest(),
+ set.runtime.manifest(),
+ set.secrets.manifest(),
+ ]
+ .iter()
+ .any(|source| source.schema_version != 23))
|| set.secrets.manifest().key_id.as_deref() != Some(secret_binding.key_id.as_str())
{
return Err(LocalStorageError::InvalidData);
@@ -469,6 +484,12 @@ impl MigrationSetCoordinator {
self.set.is_some()
}
+ pub(crate) fn target_schema_version(&self) -> u32 {
+ self.set
+ .as_ref()
+ .map_or(LATEST_SCHEMA_VERSION, BackupSet::target_schema_version)
+ }
+
pub(crate) fn expected_control_store_uuid(&self) -> Option<&str> {
self.control_store_uuid.as_deref()
}
@@ -608,12 +629,15 @@ fn validate_live_set(
runtime_target_uuid: &str,
secret_binding: &MigrationSecretBinding,
) -> Result<(), LocalStorageError> {
+ let rank = phase_rank(set.phase());
let control_target = validate_live_database(
&paths[0],
set.control.manifest(),
DatabaseKind::Control,
control_target_uuid,
None,
+ set.target_schema_version(),
+ rank,
)?;
let runtime_target = validate_live_database(
&paths[1],
@@ -621,6 +645,8 @@ fn validate_live_set(
DatabaseKind::Runtime,
runtime_target_uuid,
None,
+ set.target_schema_version(),
+ rank,
)?;
let secrets_target = validate_live_database(
&paths[2],
@@ -628,8 +654,9 @@ fn validate_live_set(
DatabaseKind::Secrets,
&secret_binding.store_uuid,
Some(&secret_binding.key_id),
+ set.target_schema_version(),
+ rank,
)?;
- let rank = phase_rank(set.phase());
if (rank >= phase_rank(BackupSetPhase::ControlMigrated) && !control_target)
|| (rank >= phase_rank(BackupSetPhase::RuntimeMigrated) && !runtime_target)
|| (rank >= phase_rank(BackupSetPhase::SecretsMigrated) && !secrets_target)
@@ -641,12 +668,15 @@ fn validate_live_set(
Ok(())
}
+#[allow(clippy::too_many_arguments)]
fn validate_live_database(
path: &Path,
source: &crate::backup::BackupManifest,
kind: DatabaseKind,
target_store_uuid: &str,
target_key_id: Option<&CanonicalDigest>,
+ target_schema_version: u32,
+ recorded_phase: u8,
) -> Result<bool, LocalStorageError> {
validate_owner_file(path)?;
let connection = Connection::open_with_flags(
@@ -658,11 +688,39 @@ fn validate_live_database(
if database_state_digest(&connection)? != source.source_state_digest {
return Err(LocalStorageError::InvalidData);
}
- return Ok(false);
+ return Ok(version == target_schema_version);
}
- if version != LATEST_SCHEMA_VERSION {
+ let store_phase = match kind {
+ DatabaseKind::Control => 0,
+ DatabaseKind::Runtime => 1,
+ DatabaseKind::Secrets => 2,
+ };
+ if recorded_phase < store_phase {
return Err(LocalStorageError::InvalidData);
}
+ let at_target = version == target_schema_version;
+ if !at_target {
+ // Only the published stable 23 -> 25 chain has a supported intermediate commit.
+ // Its original source/target and next-store phase must all agree; arbitrary mixed
+ // versions are not migration sources. Version 24 must have its real committed ledger.
+ if recorded_phase != store_phase
+ || source.schema_version != 23
+ || target_schema_version != 25
+ || version != 24
+ || connection.query_row(
+ "SELECT COUNT(*) FROM schema_migrations WHERE version >= 24",
+ [],
+ |row| row.get::<_, u32>(0),
+ )? != 1
+ || !connection.query_row(
+ "SELECT EXISTS(SELECT 1 FROM schema_migrations WHERE version = 24)",
+ [],
+ |row| row.get::<_, bool>(0),
+ )?
+ {
+ return Err(LocalStorageError::InvalidData);
+ }
+ }
match kind {
DatabaseKind::Control | DatabaseKind::Runtime => {
let binding = connection
@@ -672,9 +730,10 @@ fn validate_live_database(
|row| row.get::<_, String>(0),
)
.optional()?;
- if binding
- .as_deref()
- .is_some_and(|binding| !binding.is_empty() && binding != target_store_uuid)
+ if (source.schema_version >= 23 && binding.as_deref() != Some(target_store_uuid))
+ || binding
+ .as_deref()
+ .is_some_and(|binding| !binding.is_empty() && binding != target_store_uuid)
{
return Err(LocalStorageError::InvalidData);
}
@@ -692,7 +751,7 @@ fn validate_live_database(
}
}
}
- Ok(true)
+ Ok(at_target)
}
fn phase_rank(phase: BackupSetPhase) -> u8 {
@@ -769,6 +828,10 @@ fn migration_sql(kind: DatabaseKind, version: u32) -> Result<&'static str, Local
(DatabaseKind::Control | DatabaseKind::Runtime | DatabaseKind::Secrets, 23) => {
Ok(current_storage::MARKER_SQL)
}
+ (DatabaseKind::Control, 24) => Ok(worker_dependencies_v24::CONTROL),
+ (DatabaseKind::Runtime | DatabaseKind::Secrets, 24) => Ok(NOOP_V9),
+ (DatabaseKind::Control, 25) => Ok(agent_surface_checks_v25::CONTROL),
+ (DatabaseKind::Runtime | DatabaseKind::Secrets, 25) => Ok(NOOP_V9),
_ => Err(LocalStorageError::InvalidData),
}
}
@@ -1553,6 +1616,7 @@ mod tests {
&live.join("control.db"),
&backup_root,
&control_uuid,
+ LATEST_SCHEMA_VERSION,
)
.unwrap(),
);
@@ -1757,6 +1821,7 @@ mod tests {
&live.join("control.db"),
&backup_root,
&control_uuid,
+ LATEST_SCHEMA_VERSION,
)
.unwrap(),
);
diff --git a/crates/local-storage/src/migrations/startup_format.rs b/crates/local-storage/src/migrations/startup_format.rs
index 8e180846..925edd94 100644
--- a/crates/local-storage/src/migrations/startup_format.rs
+++ b/crates/local-storage/src/migrations/startup_format.rs
@@ -33,7 +33,10 @@ pub(crate) fn validate_startup_format(root: &Path) -> Result<(), LocalStorageErr
OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX,
)?;
let version: u32 = connection.query_row("PRAGMA user_version", [], |row| row.get(0))?;
- if version != LATEST_SCHEMA_VERSION {
+ // Schema 23 is the first stable format; 24 preserves that same marker.
+ // A mixed supported live set is only a candidate for the existing coordinator:
+ // it must still prove its complete source backup, store identities, key and phase.
+ if !matches!(version, 23 | 24 | LATEST_SCHEMA_VERSION) {
return Err(LocalStorageError::UpgradeSourceUnsupported);
}
let marker = connection.query_row(
diff --git a/crates/local-storage/src/migrations/upgrade_batch_recovery_tests.rs b/crates/local-storage/src/migrations/upgrade_batch_recovery_tests.rs
new file mode 100644
index 00000000..5a5d1f2d
--- /dev/null
+++ b/crates/local-storage/src/migrations/upgrade_batch_recovery_tests.rs
@@ -0,0 +1,281 @@
+//! Product startup recovery at fixed schema23/24/25 crash boundaries.
+//! Reuses frozen old Worker journals; SQL commits are real historical migration steps.
+use super::*;
+use crate::{LocalStorageSet, backup::test_writer_barrier};
+use worker_dependencies_v24_tests::{assert_frozen_rows, cases, schema23_source};
+
+fn source_batch(root: &Path, target: u32) -> BackupSet {
+ schema23_source(root, &cases()[0]);
+ let paths = live_database_paths(&root.join("live"));
+ let binding = crate::LocalSecretStore::migration_binding(&paths[2], &root.join("master-key"))
+ .unwrap()
+ .unwrap();
+ BackupSet::create_migration(
+ &test_writer_barrier(),
+ &crate::upgrade_backup_root(root).unwrap(),
+ &open_existing_for_snapshot(&paths[0]).unwrap(),
+ &open_existing_for_snapshot(&paths[1]).unwrap(),
+ &open_existing_for_snapshot(&paths[2]).unwrap(),
+ &binding.key_id,
+ target,
+ )
+ .unwrap()
+}
+
+fn commit_step(path: &Path, kind: DatabaseKind, version: u32) {
+ let mut connection = Connection::open(path).unwrap();
+ let transaction = connection
+ .transaction_with_behavior(TransactionBehavior::Immediate)
+ .unwrap();
+ transaction
+ .execute_batch(migration_sql(kind, version).unwrap())
+ .unwrap();
+ transaction
+ .pragma_update(None, "user_version", version)
+ .unwrap();
+ transaction.execute(
+ "INSERT INTO schema_migrations(version, applied_at, binary_version) VALUES (?1, 1, 'interrupted-producer')",
+ [version],
+ ).unwrap();
+ transaction.commit().unwrap();
+}
+
+fn assert_latest_and_preserved(root: &Path, key: &[u8]) {
+ let stores = LocalStorageSet::open_for_daemon_startup(root).unwrap();
+ stores
+ .control()
+ .with_connection(|connection| assert_frozen_rows(connection, &cases()[0]));
+ assert_eq!(fs::read(root.join("master-key")).unwrap(), key);
+ for path in live_database_paths(&root.join("live")) {
+ assert_eq!(
+ database_version(&path).unwrap(),
+ Some(LATEST_SCHEMA_VERSION)
+ );
+ }
+}
+
+#[test]
+fn missing_original_backup_for_old_mixed_versions_refuses_without_adopting_data() {
+ let directory = crate::test_tempdir().unwrap();
+ let root = directory.path().join("storage");
+ let set = source_batch(&root, 24);
+ let backup = set.directory().to_owned();
+ commit_step(&root.join("live/control.db"), DatabaseKind::Control, 24);
+ let withheld = backup.with_file_name("withheld-original-batch");
+ fs::rename(&backup, &withheld).unwrap();
+ let paths = live_database_paths(&root.join("live"));
+ let before = paths.clone().map(|path| fs::read(path).unwrap());
+ let key = fs::read(root.join("master-key")).unwrap();
+ assert!(LocalStorageSet::open_for_daemon_startup(&root).is_err());
+ assert_eq!(paths.map(|path| fs::read(path).unwrap()), before);
+ assert_eq!(fs::read(root.join("master-key")).unwrap(), key);
+ assert!(
+ !backup.exists(),
+ "a missing original batch must not be replaced"
+ );
+ assert_eq!(
+ BackupSet::open(&crate::test_storage_authority(), withheld)
+ .unwrap()
+ .set_id(),
+ set.set_id()
+ );
+}
+
+#[test]
+fn prior_target24_batch_finishes_and_archives_before_a_new_current_batch() {
+ for persist_phase in [false, true] {
+ let directory = crate::test_tempdir().unwrap();
+ let root = directory.path().join("storage");
+ let mut set = source_batch(&root, 24);
+ let backup = set.directory().to_owned();
+ let source_bytes = fs::read(backup.join("control.db")).unwrap();
+ let old_id = set.set_id().to_owned();
+ let key = fs::read(root.join("master-key")).unwrap();
+ commit_step(&root.join("live/control.db"), DatabaseKind::Control, 24);
+ if persist_phase {
+ set.persist_phase(&test_writer_barrier(), BackupSetPhase::ControlMigrated)
+ .unwrap();
+ }
+ drop(set);
+ assert_latest_and_preserved(&root, &key);
+ let archived = backup
+ .parent()
+ .unwrap()
+ .join(format!("migration-set.{old_id}"));
+ let previous = BackupSet::open(&crate::test_storage_authority(), &archived).unwrap();
+ assert_eq!(previous.target_schema_version(), 24);
+ assert_eq!(previous.phase(), BackupSetPhase::Completed);
+ assert_eq!(previous.set_id(), old_id);
+ assert_eq!(fs::read(archived.join("control.db")).unwrap(), source_bytes);
+ let current = BackupSet::open(&crate::test_storage_authority(), &backup).unwrap();
+ assert_ne!(current.set_id(), old_id);
+ assert_eq!(current.control.manifest().schema_version, 24);
+ assert_eq!(current.target_schema_version(), LATEST_SCHEMA_VERSION);
+ assert_eq!(current.phase(), BackupSetPhase::Completed);
+ assert_latest_and_preserved(&root, &key);
+ assert_eq!(
+ BackupSet::open(&crate::test_storage_authority(), backup)
+ .unwrap()
+ .set_id(),
+ current.set_id()
+ );
+ }
+}
+
+#[test]
+fn current_batch_resumes_schema24_commit_for_each_recorded_next_store() {
+ for next in 0..3 {
+ let directory = crate::test_tempdir().unwrap();
+ let root = directory.path().join("storage");
+ let mut set = source_batch(&root, 25);
+ let backup = set.directory().to_owned();
+ let id = set.set_id().to_owned();
+ let source_bytes = fs::read(backup.join("control.db")).unwrap();
+ let key = fs::read(root.join("master-key")).unwrap();
+ let paths = live_database_paths(&root.join("live"));
+ for (index, kind) in [
+ DatabaseKind::Control,
+ DatabaseKind::Runtime,
+ DatabaseKind::Secrets,
+ ]
+ .into_iter()
+ .enumerate()
+ .take(next + 1)
+ {
+ commit_step(&paths[index], kind, 24);
+ if index < next {
+ commit_step(&paths[index], kind, 25);
+ let phase = [
+ BackupSetPhase::ControlMigrated,
+ BackupSetPhase::RuntimeMigrated,
+ ][index];
+ set.persist_phase(&test_writer_barrier(), phase).unwrap();
+ }
+ }
+ assert_eq!(
+ database_version(&paths[next]).unwrap(),
+ Some(24),
+ "pin the actual intermediate revision"
+ );
+ drop(set);
+ assert_latest_and_preserved(&root, &key);
+ let current = BackupSet::open(&crate::test_storage_authority(), &backup).unwrap();
+ assert_eq!(current.set_id(), id);
+ assert_eq!(current.phase(), BackupSetPhase::Completed);
+ assert_eq!(fs::read(backup.join("control.db")).unwrap(), source_bytes);
+ assert_latest_and_preserved(&root, &key);
+ }
+}
+
+#[test]
+fn intermediate_revision_without_its_identity_ledger_or_next_phase_is_preserved_and_refused() {
+ for fault in [
+ "identity",
+ "ledger",
+ "ahead_of_phase",
+ "phase_ahead",
+ "source",
+ ] {
+ let directory = crate::test_tempdir().unwrap();
+ let root = directory.path().join("storage");
+ let mut set = source_batch(&root, 25);
+ let paths = live_database_paths(&root.join("live"));
+ let index = usize::from(fault == "ahead_of_phase");
+ let kind = [DatabaseKind::Control, DatabaseKind::Runtime][index];
+ commit_step(&paths[index], kind, 24);
+ let connection = Connection::open(&paths[index]).unwrap();
+ match fault {
+ "identity" => {
+ connection
+ .execute("UPDATE storage_meta SET store_uuid='foreign-store'", [])
+ .unwrap();
+ }
+ "ledger" => {
+ connection
+ .execute("DELETE FROM schema_migrations WHERE version=24", [])
+ .unwrap();
+ }
+ "phase_ahead" => {
+ set.persist_phase(&test_writer_barrier(), BackupSetPhase::ControlMigrated)
+ .unwrap();
+ }
+ "source" => {
+ Connection::open(&paths[1])
+ .unwrap()
+ .execute("CREATE TABLE changed_source (value TEXT)", [])
+ .unwrap();
+ }
+ _ => {}
+ }
+ drop(connection);
+ let before = paths.clone().map(|path| fs::read(path).unwrap());
+ let key = fs::read(root.join("master-key")).unwrap();
+ let manifest = fs::read(set.directory().join("backup-set.manifest.json")).unwrap();
+ assert!(
+ LocalStorageSet::open_for_daemon_startup(&root).is_err(),
+ "{fault}"
+ );
+ assert_eq!(paths.map(|path| fs::read(path).unwrap()), before, "{fault}");
+ assert_eq!(fs::read(root.join("master-key")).unwrap(), key, "{fault}");
+ assert_eq!(
+ fs::read(set.directory().join("backup-set.manifest.json")).unwrap(),
+ manifest,
+ "{fault}"
+ );
+ }
+}
+
+#[test]
+fn completed_prior_batch_with_missing_or_blank_live_identity_is_not_archived() {
+ for (index, sql) in [
+ (0, "DELETE FROM storage_meta"),
+ (0, "UPDATE storage_meta SET store_uuid=''"),
+ (1, "DELETE FROM storage_meta"),
+ (1, "UPDATE storage_meta SET store_uuid=''"),
+ ] {
+ let directory = crate::test_tempdir().unwrap();
+ let root = directory.path().join("storage");
+ let mut set = source_batch(&root, 24);
+ let paths = live_database_paths(&root.join("live"));
+ for (path, kind) in paths.iter().zip([
+ DatabaseKind::Control,
+ DatabaseKind::Runtime,
+ DatabaseKind::Secrets,
+ ]) {
+ commit_step(path, kind, 24);
+ }
+ for phase in [
+ BackupSetPhase::ControlMigrated,
+ BackupSetPhase::RuntimeMigrated,
+ BackupSetPhase::SecretsMigrated,
+ BackupSetPhase::Completed,
+ ] {
+ set.persist_phase(&test_writer_barrier(), phase).unwrap();
+ }
+ Connection::open(&paths[index])
+ .unwrap()
+ .execute(sql, [])
+ .unwrap();
+ let before = paths.clone().map(|path| fs::read(path).unwrap());
+ let key = fs::read(root.join("master-key")).unwrap();
+ let backup = set.directory().to_owned();
+ let manifest = fs::read(backup.join("backup-set.manifest.json")).unwrap();
+ let source_bytes = fs::read(backup.join("control.db")).unwrap();
+ let archived = backup
+ .parent()
+ .unwrap()
+ .join(format!("migration-set.{}", set.set_id()));
+ assert!(LocalStorageSet::open_for_daemon_startup(&root).is_err());
+ assert_eq!(paths.map(|path| fs::read(path).unwrap()), before);
+ assert_eq!(fs::read(root.join("master-key")).unwrap(), key);
+ assert_eq!(
+ fs::read(backup.join("backup-set.manifest.json")).unwrap(),
+ manifest
+ );
+ assert_eq!(fs::read(backup.join("control.db")).unwrap(), source_bytes);
+ assert!(
+ !archived.exists(),
+ "invalid identity must fail before any backup rotation"
+ );
+ }
+}
diff --git a/crates/local-storage/src/migrations/worker_dependencies_v24.rs b/crates/local-storage/src/migrations/worker_dependencies_v24.rs
new file mode 100644
index 00000000..1b0ef1a1
--- /dev/null
+++ b/crates/local-storage/src/migrations/worker_dependencies_v24.rs
@@ -0,0 +1,45 @@
+//! Extend native ACP installation support without decoding or reserializing stored journals.
+
+pub(super) const CONTROL: &str = r#"
+CREATE TABLE worker_dependency_selections_v24 (
+ workspace_id TEXT NOT NULL,
+ harness TEXT NOT NULL CHECK(harness IN ('codex_cli','claude_code','qoder_cli')),
+ revision INTEGER NOT NULL
+ CHECK(typeof(revision) = 'integer' AND revision > 0),
+ selection_json TEXT NOT NULL,
+ owner_operation_id TEXT NOT NULL REFERENCES operations(operation_id),
+ updated_at INTEGER NOT NULL,
+ PRIMARY KEY(workspace_id, harness)
+);
+
+CREATE TABLE worker_dependency_selection_effects_v24 (
+ operation_id TEXT PRIMARY KEY REFERENCES operations(operation_id) ON DELETE CASCADE,
+ workspace_id TEXT NOT NULL,
+ harness TEXT NOT NULL CHECK(harness IN ('codex_cli','claude_code','qoder_cli')),
+ before_revision INTEGER NOT NULL
+ CHECK(typeof(before_revision) = 'integer' AND before_revision >= 0),
+ before_json TEXT,
+ before_owner_operation_id TEXT,
+ after_revision INTEGER NOT NULL
+ CHECK(typeof(after_revision) = 'integer' AND after_revision > 0),
+ after_json TEXT NOT NULL,
+ activated INTEGER NOT NULL DEFAULT 0 CHECK(activated IN (0,1)),
+ compensated INTEGER NOT NULL DEFAULT 0 CHECK(compensated IN (0,1)),
+ UNIQUE(workspace_id, harness, after_revision)
+);
+
+INSERT INTO worker_dependency_selections_v24
+ SELECT workspace_id, harness, revision, selection_json, owner_operation_id, updated_at
+ FROM worker_dependency_selections;
+INSERT INTO worker_dependency_selection_effects_v24
+ SELECT operation_id, workspace_id, harness, before_revision, before_json,
+ before_owner_operation_id, after_revision, after_json, activated, compensated
+ FROM worker_dependency_selection_effects;
+
+DROP TABLE worker_dependency_selection_effects;
+DROP TABLE worker_dependency_selections;
+ALTER TABLE worker_dependency_selections_v24 RENAME TO worker_dependency_selections;
+ALTER TABLE worker_dependency_selection_effects_v24 RENAME TO worker_dependency_selection_effects;
+CREATE INDEX worker_dependency_selection_effects_state
+ ON worker_dependency_selection_effects(activated, compensated, operation_id);
+"#;
diff --git a/crates/local-storage/src/migrations/worker_dependencies_v24_tests.rs b/crates/local-storage/src/migrations/worker_dependencies_v24_tests.rs
new file mode 100644
index 00000000..48c4409f
--- /dev/null
+++ b/crates/local-storage/src/migrations/worker_dependencies_v24_tests.rs
@@ -0,0 +1,405 @@
+//! Upgrade consumers use frozen schema-23 journals produced by the previous product.
+use super::*;
+use crate::{LocalStorageSet, backup::test_writer_barrier, test_tempdir as tempdir};
+use hiroute_domain::{
+ BeginOperationOutcome, CompensationOutcome, ControlRepositoryPort, EffectReconciliation,
+ OperationId, OperationState, OperationStepKind, OwnedEffectV1,
+};
+use serde_json::Value;
+
+const FIXTURE: &str = include_str!("fixtures/schema23-worker-operations.json");
+const TABLES: [&str; 5] = [
+ "operations",
+ "operation_steps",
+ "worker_dependency_selections",
+ "worker_dependency_selection_effects",
+ "writer_claim",
+];
+
+pub(super) fn cases() -> Vec<Value> {
+ let fixture: Value = serde_json::from_str(FIXTURE).unwrap();
+ assert_eq!(fixture["schema_version"], 23);
+ let cases = fixture["cases"].as_array().unwrap();
+ let matrix: std::collections::BTreeSet<_> = cases
+ .iter()
+ .map(|case| {
+ (
+ case["harness"].as_str().unwrap(),
+ case["stage"].as_str().unwrap(),
+ )
+ })
+ .collect();
+ let expected = ["codex_cli", "claude_code"]
+ .into_iter()
+ .flat_map(|harness| {
+ ["staged", "activated", "succeeded"]
+ .into_iter()
+ .map(move |stage| (harness, stage))
+ })
+ .collect();
+ assert_eq!(cases.len(), 6, "all original producer cases are required");
+ assert_eq!(matrix, expected);
+ cases.clone()
+}
+
+fn row_values(row: &Value) -> Vec<rusqlite::types::Value> {
+ row.as_array()
+ .unwrap()
+ .iter()
+ .map(|value| match value {
+ Value::Null => rusqlite::types::Value::Null,
+ Value::Number(number) => number.as_i64().unwrap().into(),
+ Value::String(text) => text.clone().into(),
+ _ => panic!("unexpected frozen SQL value"),
+ })
+ .collect()
+}
+
+pub(super) fn schema23_source(root: &Path, case: &Value) {
+ // Initialize only fresh key/store identities. Reconstruct the published v20 tables and
+ // rewind the no-op/runtime format revision; no current serializer produces legacy data.
+ drop(LocalStorageSet::open_for_daemon_startup(root).unwrap());
+ for path in live_database_paths(&root.join("live")) {
+ let connection = Connection::open(&path).unwrap();
+ if path.file_name().unwrap() == "control.db" {
+ connection
+ .execute_batch("DROP TABLE agent_surface_checks")
+ .unwrap();
+ connection
+ .execute_batch(agent_surface_checks_v22::CONTROL)
+ .unwrap();
+ connection
+ .execute_batch(
+ "DROP TABLE worker_dependency_selection_effects;
+ DROP TABLE worker_dependency_selections;",
+ )
+ .unwrap();
+ connection
+ .execute_batch(worker_dependencies_v20::CONTROL)
+ .unwrap();
+ for table in TABLES {
+ let data = &case["tables"][table];
+ let columns: Vec<_> = data["columns"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|v| v.as_str().unwrap())
+ .collect();
+ let parameters = vec!["?"; columns.len()].join(",");
+ let sql = format!(
+ "INSERT INTO {table} ({}) VALUES ({parameters})",
+ columns.join(",")
+ );
+ for row in data["rows"].as_array().unwrap() {
+ connection
+ .execute(&sql, rusqlite::params_from_iter(row_values(row)))
+ .unwrap();
+ }
+ }
+ }
+ connection
+ .execute("DELETE FROM schema_migrations WHERE version > 23", [])
+ .unwrap();
+ connection.pragma_update(None, "user_version", 23).unwrap();
+ }
+}
+
+pub(super) fn assert_frozen_rows(connection: &Connection, case: &Value) {
+ for table in TABLES {
+ let data = &case["tables"][table];
+ let mut statement = connection
+ .prepare(&format!("SELECT * FROM {table} ORDER BY 1,2"))
+ .unwrap();
+ let count = statement.column_count();
+ let actual: Vec<Vec<rusqlite::types::Value>> = statement
+ .query_map([], |row| (0..count).map(|i| row.get(i)).collect())
+ .unwrap()
+ .map(Result::unwrap)
+ .collect();
+ let expected: Vec<_> = data["rows"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(row_values)
+ .collect();
+ assert_eq!(
+ actual, expected,
+ "{table}: migration must retain raw bytes and ownership"
+ );
+ }
+}
+
+#[test]
+fn schema23_worker_journals_replay_and_compensate_after_production_startup() {
+ for case in cases() {
+ let directory = tempdir().unwrap();
+ let root = directory.path().join("storage");
+ schema23_source(&root, &case);
+ let key = fs::read(root.join("master-key")).unwrap();
+ let stores = LocalStorageSet::open_for_daemon_startup(&root).unwrap();
+ assert_eq!(fs::read(root.join("master-key")).unwrap(), key);
+ let store = stores.control();
+ store.with_connection(|connection| assert_frozen_rows(connection, &case));
+ let id: OperationId = serde_json::from_value(case["operation_id"].clone()).unwrap();
+ let mut operation = store.load_operation(&id).unwrap().unwrap();
+ assert!(store.operation_is_current(&operation).unwrap());
+ let recoverable = store.recoverable_operations().unwrap();
+ if operation.state.is_terminal() {
+ assert!(recoverable.is_empty());
+ } else {
+ assert_eq!(recoverable, vec![operation.clone()]);
+ }
+ assert_eq!(
+ store
+ .operation_for_idempotency(&operation.workspace_id, &operation.idempotency)
+ .unwrap(),
+ Some(operation.clone())
+ );
+ assert_eq!(
+ store.begin_local_operation(&operation).unwrap(),
+ BeginOperationOutcome::ExistingSame(Box::new(operation.clone()))
+ );
+ let effect: OwnedEffectV1 = serde_json::from_value(case["effect"].clone()).unwrap();
+ assert_eq!(
+ operation
+ .step(OperationStepKind::MaterializeSources)
+ .effects,
+ vec![effect.clone()]
+ );
+ let change = operation.plan.worker_dependency_selection().unwrap();
+ let harness = change.after_selection.harness;
+ let expected_revision = if case["stage"] == "staged" { 1 } else { 2 };
+ assert_eq!(
+ store
+ .worker_dependency_selection_revision(&operation.workspace_id, harness)
+ .unwrap(),
+ expected_revision
+ );
+ assert_eq!(
+ store
+ .apply_worker_dependency_selection(&id, &operation.workspace_id, change)
+ .unwrap(),
+ effect
+ );
+ let expected_state = if case["stage"] == "staged" {
+ EffectReconciliation::Staged(effect.clone())
+ } else {
+ EffectReconciliation::Applied(effect.clone())
+ };
+ assert_eq!(
+ store.observe_control(&id, &operation.workspace_id).unwrap(),
+ expected_state
+ );
+ // Idempotent journal/effect reads above must not even reserialize historical JSON.
+ store.with_connection(|connection| assert_frozen_rows(connection, &case));
+ for _ in 0..2 {
+ assert_eq!(store.activate_control(&effect).unwrap(), effect);
+ }
+ assert_eq!(
+ store
+ .worker_dependency_selection(&operation.workspace_id, harness)
+ .unwrap(),
+ Some((change.after_selection.clone(), 2))
+ );
+ let previous: OwnedEffectV1 =
+ serde_json::from_value(case["previous_effect"].clone()).unwrap();
+ assert_eq!(
+ store.compensate_control(&previous).unwrap(),
+ CompensationOutcome::OwnershipLost
+ );
+ if !operation.state.is_terminal() {
+ assert_eq!(
+ store.compensate_control(&effect).unwrap(),
+ CompensationOutcome::Compensated
+ );
+ assert_eq!(
+ store.compensate_control(&effect).unwrap(),
+ CompensationOutcome::AlreadyCompensated
+ );
+ assert_eq!(
+ store
+ .worker_dependency_selection_revision(&operation.workspace_id, harness)
+ .unwrap(),
+ 1
+ );
+ let frozen_effect = case["tables"]["worker_dependency_selection_effects"]["rows"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .find(|row| row[0] == case["operation_id"])
+ .unwrap();
+ store.with_connection(|connection| {
+ let restored: (String, String) = connection.query_row(
+ "SELECT selection_json, owner_operation_id FROM worker_dependency_selections",
+ [], |row| Ok((row.get(0)?, row.get(1)?)),
+ ).unwrap();
+ assert_eq!(
+ restored,
+ (
+ frozen_effect[4].as_str().unwrap().to_owned(),
+ frozen_effect[5].as_str().unwrap().to_owned()
+ )
+ );
+ });
+ operation.transition(OperationState::RollingBack).unwrap();
+ operation.transition(OperationState::RolledBack).unwrap();
+ store.finish_operation(&mut operation).unwrap();
+ assert!(store.operation_is_current(&operation).unwrap());
+ assert!(!store.writer_recovery_required().unwrap());
+ }
+ drop(stores);
+ let reopened = LocalStorageSet::open_for_daemon_startup(&root).unwrap();
+ assert_eq!(
+ reopened.control().load_operation(&id).unwrap(),
+ Some(operation)
+ );
+ assert_eq!(
+ BackupSet::open(
+ &crate::test_storage_authority(),
+ crate::upgrade_backup_root(&root).unwrap()
+ )
+ .unwrap()
+ .phase(),
+ BackupSetPhase::Completed
+ );
+ for path in live_database_paths(&root.join("live")) {
+ assert_eq!(
+ database_version(&path).unwrap(),
+ Some(LATEST_SCHEMA_VERSION)
+ );
+ }
+ }
+}
+
+#[test]
+fn schema23_interrupted_set_needs_its_complete_backup_and_resumes_at_production_startup() {
+ for persist_phase in [false, true] {
+ let directory = tempdir().unwrap();
+ let root = directory.path().join("storage");
+ let case = &cases()[0];
+ schema23_source(&root, case);
+ let live = root.join("live");
+ let backup = crate::upgrade_backup_root(&root).unwrap();
+ let binding = crate::LocalSecretStore::migration_binding(
+ &live.join("secrets.db"),
+ &root.join("master-key"),
+ )
+ .unwrap()
+ .unwrap();
+ let barrier = test_writer_barrier();
+ let mut coordinator = MigrationSetCoordinator::prepare(
+ &crate::test_storage_authority(),
+ &barrier,
+ &live,
+ &backup,
+ Some(&binding),
+ )
+ .unwrap();
+ drop(
+ crate::ControlStore::open_from_migration_set(
+ &crate::test_storage_authority(),
+ &live.join("control.db"),
+ &backup,
+ coordinator.expected_control_store_uuid().unwrap(),
+ coordinator.target_schema_version(),
+ )
+ .unwrap(),
+ );
+ if persist_phase {
+ coordinator.mark_control_migrated(&barrier).unwrap();
+ }
+ drop(coordinator);
+ // Both no manifest and a manifest whose source set is incomplete must fail closed.
+ let withheld = if persist_phase {
+ backup.join("runtime.db")
+ } else {
+ backup.clone()
+ };
+ let saved_backup = backup.with_file_name("withheld-source-backup");
+ fs::rename(&withheld, &saved_backup).unwrap();
+ let before = live_database_paths(&live).map(|path| fs::read(path).unwrap());
+ assert!(LocalStorageSet::open_for_daemon_startup(&root).is_err());
+ assert_eq!(
+ live_database_paths(&live).map(|path| fs::read(path).unwrap()),
+ before
+ );
+ fs::rename(saved_backup, &withheld).unwrap();
+ let stores = LocalStorageSet::open_for_daemon_startup(&root).unwrap();
+ stores
+ .control()
+ .with_connection(|connection| assert_frozen_rows(connection, case));
+ assert_eq!(
+ BackupSet::open(&crate::test_storage_authority(), backup)
+ .unwrap()
+ .phase(),
+ BackupSetPhase::Completed
+ );
+ }
+}
+
+#[test]
+fn completed_schema23_backup_is_archived_before_the_next_migration_batch() {
+ let directory = tempdir().unwrap();
+ let root = directory.path().join("storage");
+ schema23_source(&root, &cases()[0]);
+ let live = root.join("live");
+ let backup = crate::upgrade_backup_root(&root).unwrap();
+ let paths = live_database_paths(&live);
+ let binding = crate::LocalSecretStore::migration_binding(&paths[2], &root.join("master-key"))
+ .unwrap()
+ .unwrap();
+ let barrier = test_writer_barrier();
+ let mut previous = BackupSet::create_migration(
+ &barrier,
+ &backup,
+ &open_existing_for_snapshot(&paths[0]).unwrap(),
+ &open_existing_for_snapshot(&paths[1]).unwrap(),
+ &open_existing_for_snapshot(&paths[2]).unwrap(),
+ &binding.key_id,
+ 23,
+ )
+ .unwrap();
+ for phase in [
+ BackupSetPhase::ControlMigrated,
+ BackupSetPhase::RuntimeMigrated,
+ BackupSetPhase::SecretsMigrated,
+ BackupSetPhase::Completed,
+ ] {
+ previous.persist_phase(&barrier, phase).unwrap();
+ }
+ let previous_id = previous.set_id().to_owned();
+ let before = fs::read(backup.join("control.db")).unwrap();
+ drop(previous);
+ drop(LocalStorageSet::open_for_daemon_startup(&root).unwrap());
+ let archived = backup
+ .parent()
+ .unwrap()
+ .join(format!("migration-set.{previous_id}"));
+ assert_eq!(fs::read(archived.join("control.db")).unwrap(), before);
+ let current = BackupSet::open(&crate::test_storage_authority(), &backup).unwrap();
+ assert_ne!(current.set_id(), previous_id);
+ assert_eq!(current.target_schema_version(), LATEST_SCHEMA_VERSION);
+ assert_eq!(current.phase(), BackupSetPhase::Completed);
+ drop(LocalStorageSet::open_for_daemon_startup(&root).unwrap());
+}
+
+#[test]
+fn unmarked_schema23_is_refused_before_rotating_backups_or_creating_keys() {
+ let directory = tempdir().unwrap();
+ let root = directory.path().join("storage");
+ schema23_source(&root, &cases()[0]);
+ Connection::open(root.join("live/control.db"))
+ .unwrap()
+ .execute("DROP TABLE stable_storage_format", [])
+ .unwrap();
+ let paths = live_database_paths(&root.join("live"));
+ let before = paths.clone().map(|path| fs::read(path).unwrap());
+ let key = fs::read(root.join("master-key")).unwrap();
+ assert!(matches!(
+ LocalStorageSet::open_for_daemon_startup(&root),
+ Err(LocalStorageError::UpgradeSourceUnsupported)
+ ));
+ assert_eq!(paths.map(|path| fs::read(path).unwrap()), before);
+ assert_eq!(fs::read(root.join("master-key")).unwrap(), key);
+ assert!(!crate::upgrade_backup_root(&root).unwrap().exists());
+}
diff --git a/crates/local-storage/src/runtime/mod.rs b/crates/local-storage/src/runtime/mod.rs
index 76e76e10..d06e991f 100644
--- a/crates/local-storage/src/runtime/mod.rs
+++ b/crates/local-storage/src/runtime/mod.rs
@@ -44,6 +44,7 @@ impl RuntimeStore {
path: &Path,
migration_backup_root: &Path,
expected_store_uuid: &str,
+ target_schema_version: u32,
) -> Result<Self, LocalStorageError> {
Ok(Self {
startup_lock: None,
@@ -54,6 +55,7 @@ impl RuntimeStore {
migration_backup_root,
Some(expected_store_uuid),
None,
+ target_schema_version,
)?),
})
}
diff --git a/crates/local-storage/src/secrets/mod.rs b/crates/local-storage/src/secrets/mod.rs
index a3ec8864..73bf5ba5 100644
--- a/crates/local-storage/src/secrets/mod.rs
+++ b/crates/local-storage/src/secrets/mod.rs
@@ -114,13 +114,14 @@ impl LocalSecretStore {
master_key_path: &Path,
migration_backup_root: &Path,
binding: &MigrationSecretBinding,
+ target_schema_version: u32,
) -> Result<Self, LocalStorageError> {
Self::open_internal(
authority,
database_path,
master_key_path,
migration_backup_root,
- Some(binding),
+ Some((binding, target_schema_version)),
)
}
@@ -129,7 +130,7 @@ impl LocalSecretStore {
database_path: &Path,
master_key_path: &Path,
migration_backup_root: &Path,
- migration_binding: Option<&MigrationSecretBinding>,
+ migration_binding: Option<(&MigrationSecretBinding, u32)>,
) -> Result<Self, LocalStorageError> {
let existing_store = database_path.exists();
if !existing_store && has_backup_evidence(database_path, migration_backup_root)? {
@@ -155,14 +156,14 @@ impl LocalSecretStore {
if existing_store {
preflight_existing_store(database_path, &keys)?;
}
- if migration_binding.is_some_and(|binding| {
+ if migration_binding.is_some_and(|(binding, _)| {
binding.store_uuid != keys.store_uuid
|| binding.key_id != keys.key_id
|| binding.key_verifier != keys.verifier
}) {
return Err(LocalStorageError::Locked);
}
- let mut connection = if let Some(binding) = migration_binding {
+ let mut connection = if let Some((binding, target_schema_version)) = migration_binding {
open_database_from_set(
authority,
database_path,
@@ -170,6 +171,7 @@ impl LocalSecretStore {
migration_backup_root,
None,
Some(binding),
+ target_schema_version,
)?
} else {
open_database_with_key_id(
diff --git a/crates/local-storage/tests/canonical_compat/README.md b/crates/local-storage/tests/canonical_compat/README.md
index d54b9f60..087f818b 100644
--- a/crates/local-storage/tests/canonical_compat/README.md
+++ b/crates/local-storage/tests/canonical_compat/README.md
@@ -14,11 +14,12 @@ current-producer test preserves Operation identities and business inputs across
cold reopen, and verifies the original collaboration grant's positive and negative
authorization cases.
-This pre-MVP agents.connect.apply sample predates the supported schema22 upgrade
-sources and lacks their complete Plan/grant facts. It is registered as a frozen
-canonical fixture, not a production migration reader. Injecting its journal into
-a schema23 store without migration must be rejected; source22 migration is covered
-by the separately frozen upgrade-schema22 fixtures.
+This pre-MVP agents.connect.apply sample lacks the complete current Plan/grant
+facts. It is a frozen canonical fixture, not a production migration reader.
+Injecting its journal into a current store must be rejected. Production
+[startup admission](../../src/migrations/startup_format.rs) rejects unsupported
+source formats (including schema22) before mutation. Historical migration
+component tests do not establish a supported user-store upgrade path.
This fixture proves compatibility with the previous normal default graph; it is
not an inventory of user stores written by experimental order-sensitive binaries.
diff --git a/crates/observation/src/managed_text/README.md b/crates/observation/src/managed_text/README.md
index a63e81d1..c611a2c8 100644
--- a/crates/observation/src/managed_text/README.md
+++ b/crates/observation/src/managed_text/README.md
@@ -1,4 +1,4 @@
-# MVP-15 → MVP-20 managed-text internal interface
+# Managed-text internal interface
[简体中文](README.zh-CN.md)
@@ -10,7 +10,7 @@ derived from a Worker payload, environment variable, or reference alone.
## Writes and retries
-1. MVP-20 first creates a trusted task/run, then calls `managed_text_put(input, now_ms)`.
+1. The delegation service first creates a trusted task/run, then calls `managed_text_put(input, now_ms)`.
2. `source_event_id + source_revision + scope` identifies one event. A repeated call returns
the same reference. Changing purpose, original time, or import source causes `Conflict`
and does not refresh the seven-day deadline.
@@ -18,9 +18,9 @@ derived from a Worker payload, environment variable, or reference alone.
same chunk are retryable; different bytes conflict. A pending chunk is registered before
it is written and is published to readers only after the complete write succeeds.
4. `finish` commits the exact number of completed chunks and returns a Complete reference;
- MVP-20 then stores the business reference. There is no distributed transaction across
+ the delegation service then stores the business reference. There is no distributed transaction across
stores. A failed business commit reuses the original reference, while a content failure
- leaves MVP-20 responsible for preserving the real task result and missing-content state.
+ leaves the delegation service responsible for preserving the real task result and missing-content state.
`original_created_at_ms` and `now_ms` come from trusted production events and the server
clock. A history import must provide the still-visible original reference with the same
@@ -46,7 +46,7 @@ deletion before confirmation. The apply transaction first removes visibility and
persistent cleanup work; `gc` then removes at most 200 chunks per batch. Late events at or
before the cutoff do not restore content. Proven events after the cutoff may be written.
-MVP-20 uses `pending_native_cleanup(scope, after_generation, limit)` to recover unconfirmed
+The delegation service uses `pending_native_cleanup(scope, after_generation, limit)` to recover unconfirmed
native-cache cleanup. It handles only HiRoute-managed history in the same scope and at or
before the cutoff, and calls `native_gc_ack` only after actual success. Notifications may be
lost; active queries and continuation must still check the current reference. An apply retry
@@ -54,8 +54,15 @@ returns both current GC states and cannot claim full cleanup while either is pen
`expire_scope` is the retention-worker entry point, using each event's seven-day deadline and
the same native-cleanup protocol.
-Production maintenance schedules expired-scope discovery and batched object GC. Native cache
-cleanup still requires MVP-20 confirmation. Full session deletion and Application
-authorization remain to be integrated; tests for this interface do not establish MVP-15 or
-MVP-20 production-entry acceptance. The activity extension migration describes this branch's
-intent; the convergence owner owns the final schema number and public export.
+Production maintenance schedules expired-scope discovery and batched object GC.
+Application authorization and session deletion are wired through
+[`ObservationControl`](../../../application/src/observation_query/control/v2.rs)
+and [unified retention](../store/unified_retention.rs). Worker native cleanup is
+owned by the daemon's [maintenance consumer](../../../daemon/src/control/runtime/delegation_maintenance.rs),
+which claims pending work and acknowledges completion after actual success. It
+delegates bounded filesystem deletion to [native_cleanup.rs](../../../daemon/src/delegation/native_cleanup.rs).
+These paths are distinct from this storage interface's tests and the
+[observation fixture checks](../../../../tools/product-e2e/tests/local_observation.rs).
+Inspect the [installed CLI management journey](../../../daemon/tests/publication_process.rs) and
+[Worker read/continue journey](../../../../tools/product-e2e/tests/worker_read.rs)
+for production-entry evidence and its limits.
diff --git a/crates/observation/src/managed_text/README.zh-CN.md b/crates/observation/src/managed_text/README.zh-CN.md
index 7772646c..1f8971f0 100644
--- a/crates/observation/src/managed_text/README.zh-CN.md
+++ b/crates/observation/src/managed_text/README.zh-CN.md
@@ -1,4 +1,4 @@
-# MVP-15 → MVP-20 受管正文内部接口
+# 受管正文内部接口
[English](README.md)
@@ -9,13 +9,13 @@ Application / 委派执行服务必须用已认证的 task/run 构造 `ManagedTe
## 写入和重试
-1. 20 先创建可信 task/run,调用 `managed_text_put(input, now_ms)`。
+1. 委派执行服务先创建可信 task/run,调用 `managed_text_put(input, now_ms)`。
2. `source_event_id + source_revision + scope` 标识同一事件;重复调用返回同一引用。
改目的、原始时间或导入来源会产生 `Conflict`,不会刷新七天期限。
3. `append` 以从 0 开始的连续 ordinal 写块,每块 1~65536 bytes。
同块同 bytes 可重试,不同 bytes 冲突。待写块先登记,完整落盘后才对读者发布。
-4. `finish` 提交准确的已完成块数,取得 Complete 引用,再由 20 保存业务引用。
- 跨库无分布式事务;业务提交失败重用原引用,内容失败由 20 保留真实任务结果和缺失状态。
+4. `finish` 提交准确的已完成块数,取得 Complete 引用,再由委派执行服务保存业务引用。
+ 跨库无分布式事务;业务提交失败重用原引用,内容失败由委派执行服务保留真实任务结果和缺失状态。
`original_created_at_ms` 和 `now_ms` 来自可信生产事件/服务端时钟。
历史导入须给出仍可见的原引用,原截止时间必须相同。没有可证明来源时,
@@ -37,13 +37,19 @@ preview 的 cutoff/count/generation 过时则 Stale;确认之前零删除。
apply 的事务先撤可见性并登记持久化清理记录,然后由 `gc` 每批最多 200 个块回收。
cutoff 以内的迟到事件不会恢复正文;确证 cutoff 之后的新事件可写入。
-20 用 `pending_native_cleanup(scope, after_generation, limit)` 恢复未确认的原生缓存清理,
+委派执行服务用 `pending_native_cleanup(scope, after_generation, limit)` 恢复未确认的原生缓存清理,
仅处理同 scope、cutoff 内的 HiRoute 受管历史,实际成功后调用 `native_gc_ack`。
通知可以丢失,主动查询和继续仍须检查当前引用。apply 重试返回当前两个 GC 状态;
任一 pending 就不能宣称清理全部完成。`expire_scope` 供 retention worker 调度,
采用每个事件七天截止时间,并使用同一原生清理协议。
-生产 maintenance 已调度过期 scope 发现和分批对象 GC;原生缓存清理仍由20确认。
-本模块尚需接入完整的会话清理和 Application 授权;本接口测试不代表
-MVP-15 或 MVP-20 生产入口验收完成。activity 扩展迁移为本分支意图,最终 schema
-编号与公共导出由总协调收敛。
+生产 maintenance 已调度过期 scope 发现和分批对象 GC。
+Application 授权和会话删除已通过
+[`ObservationControl`](../../../application/src/observation_query/control/v2.rs)
+及[统一保留期处理](../store/unified_retention.rs)接入。
+Worker 原生缓存清理由 daemon 的[维护消费者](../../../daemon/src/control/runtime/delegation_maintenance.rs)
+领取待办并管理确认状态,实际成功后才确认完成;有界文件删除交给
+[native_cleanup.rs](../../../daemon/src/delegation/native_cleanup.rs)。
+本存储接口测试及[观察夹具检查](../../../../tools/product-e2e/tests/local_observation.rs)不能代替生产入口证据;
+请查阅[已安装 CLI 管理闭环](../../../daemon/tests/publication_process.rs)及
+[Worker 读取/继续场景](../../../../tools/product-e2e/tests/worker_read.rs)中的验证范围和限制。
diff --git a/decision-extensions/extensions/jev-decider/README.md b/decision-extensions/extensions/jev-decider/README.md
index 702e8427..02df9002 100644
--- a/decision-extensions/extensions/jev-decider/README.md
+++ b/decision-extensions/extensions/jev-decider/README.md
@@ -147,7 +147,49 @@ It returns:
`assessment` is optional. Its score is competence in `[0,1]`, not model confidence. Jev's three-level `0..2` Score is divided by two. Jev does not provide a textual reason here, so this implementation omits the optional `reason` field.
-To implement a different strategy, keep the HTTP validation and response contract, then replace `questions()` and `decision_response()` in `jev_decider/server.py`. Do not add vendor fields to the HiRoute request or make a second scoring call: use the five protocol fields as state and return one allowed branch with an optional competence assessment.
+## Code and responsibility map
+
+The production entry remains `jev_decider.server:main` → `create_app()` →
+`POST /v1/decisions`. Read these modules in request order:
+
+| Module | Responsibility |
+| --- | --- |
+| [settings.py](jev_decider/settings.py) | Deployment environment, bounded key/policy files and configuration validation |
+| [protocol.py](jev_decider/protocol.py) | Strict JSON and the existing five-field HiRoute request contract |
+| [decision.py](jev_decider/decision.py) | `prepare_decision()` applies existing policy precedence, trims whole turns and builds one Jev request; `decision_response()` validates Choice/Score and returns a branch plus optional prior-segment assessment; `reported_usage()` retains reported billing facts |
+| [server.py](jev_decider/server.py) | Authentication, whole-request deadline, queue/concurrency, upstream HTTP, response bounds, error mapping, diagnostics and service lifecycle |
+
+The decision module has no HTTP, environment, file, credential or session dependency.
+Its narrow `DecisionSettings` protocol describes only the non-secret fields this
+Jev implementation consumes; it is not a new provider registry or a general
+inference API. Existing public imports from `jev_decider.server` remain available
+as reexports of the same implementations. There is one implementation per operation.
+
+To change the existing Jev strategy, start at `questions()` and
+`decision_response()` in `decision.py`. Prompts, thresholds, policy precedence and
+context trimming affect decisions and require deliberate behavior review. Keep
+the HTTP contract: use the five fields as state, return one allowed branch and
+an optional assessment, and do not add a second scoring call.
+
+The shared [decision foundation map](../../../docs/code-map/decision-foundation.md)
+records provider references and the future purpose-specific contract owners.
+
+Future integration must keep four owners separate: general inference represents
+a bounded question/answer operation; a purpose policy decides what is being
+selected (currently smart-saving branches); a provider transport owns endpoint,
+authentication and vendor wire format; the calling product owns allowed choices
+and execution authorization. Model selection and tool selection need their own
+purpose and authorization contracts. This extraction adds neither use case nor a
+multi-provider or embedded service implementation.
+
+For natural-language branch selection, the caller owns stable IDs, descriptions
+and the frozen allowed set. This service's existing generic auto path only returns
+an allowed ID; it does not authorize execution or define a new fallback policy.
+The existing binary policy override and rules thresholds remain unchanged. An
+assessment concerns the prior execution suffix, separately from the new choice.
+Routing-round identity, publication pinning, source cancellation and selected vs
+executed branch attribution remain owned by HiRoute's
+[Gateway](../../../crates/gateway/README.md).
## Offline tests
@@ -185,6 +227,11 @@ python -m unittest -v
The suite covers auto/rules single-call behavior, the OAS route and rejection of old routes, first-round omission, standard proxy routing, formula boundaries, invalid optional Score, invalid probabilities and branch sets, whole-round trimming/partial marking, fixed-context rejection, strict input, inbound authentication, health isolation, upstream 401/402/429, timeout, oversized output, and concurrency. A real OpenRouter smoke test is intentionally opt-in and must not be placed in normal CI or retried automatically.
+Use the [capability test map](tests/README.md) to locate an assertion. Shared,
+independently expected decision cases run through both the HTTP service and the
+pure module. The pure contract can also run with only Python's standard library:
+`python -m unittest tests.test_decision -v`.
+
## Opt-in HiRoute → Jev smoke
After the offline suite passes, start this service with a real key file as shown above. From the repository root, run exactly the ignored production-path test against that local endpoint:
diff --git a/decision-extensions/extensions/jev-decider/README.zh-CN.md b/decision-extensions/extensions/jev-decider/README.zh-CN.md
index e36ad339..6de183cd 100644
--- a/decision-extensions/extensions/jev-decider/README.zh-CN.md
+++ b/decision-extensions/extensions/jev-decider/README.zh-CN.md
@@ -136,7 +136,16 @@ HiRoute 投影不含系统/开发者指令、reasoning、模型/计划身份或
评分是胜任度,不是置信度;Jev 的 `0..2` Score 除以二映射到 `[0,1]`。Jev 不提供文字 reason,本实现直接省略,不追加生成调用。无合法 Score 时仍可保留合法分支;模式必需输出非法则失败,不补调。
-修改 `jev_decider/server.py` 中上下文准备、`questions()` 和 `decision_response()` 即可实现自己的策略或供应商适配,保持 HiRoute 请求/响应合同不变。无需增加插件注册框架、会话库或第二个评分接口。
+生产入口仍为 `jev_decider.server:main` → `create_app()` → `POST /v1/decisions`。职责按以下入口分开:
+
+- [settings.py](jev_decider/settings.py):环境配置、受限凭据/策略文件读取及校验。
+- [protocol.py](jev_decider/protocol.py):严格 JSON 和现有五字段请求校验。
+- [decision.py](jev_decider/decision.py):无 I/O 的策略优先级、整轮裁剪、Jev 问题构造、Choice/Score 解释及实际用量提取。
+- [server.py](jev_decider/server.py):HTTP、认证、总超时、并发、响应上限、错误映射、日志及生命周期。原公开导入保留为同一实现的转导出。
+
+修改现有策略从 `decision.py` 的 `questions()` 和 `decision_response()` 开始;提示、阈值、覆盖优先级和裁剪变化都影响行为。保持 HiRoute 请求/响应合同,不增加第二个评分调用。本次职责拆分没有实现内置服务、多 provider 或工具选择。
+
+后续应区分通用推断、用途策略、provider 传输和调用方执行授权。自然语言条件由模型评估;稳定分支 ID、允许集合、发布版本及默认回退由调用方政策拥有,合法分支不直接授予执行能力。现有二分 policy 覆盖及 rules 阈值保持不变;上一段 assessment 与本次选择分开。完整阅读入口见 [English architecture map](README.md#code-and-responsibility-map)。
## 测试
@@ -148,6 +157,8 @@ python -m unittest -v
测试使用真实 HTTP handler 和受控上游,不读真实 key、不访问付费供应商。覆盖 auto/rules 单次调用、首轮无评分、公式边界、非法输出、裁剪、认证、代理、上游失败、超时及并发。
+按用户能力定位断言见 [English test map](tests/README.md)。HTTP 和纯模块共用独立预期的输入输出案例;纯模块合同也可仅使用 Python 标准库运行:`python -m unittest tests.test_decision -v`。
+
需要真实冒烟时,先启动持有真实 key 的本地服务,再从仓库根目录按仓库验证路由要求显式运行:
```sh
diff --git a/decision-extensions/extensions/jev-decider/jev_decider/decision.py b/decision-extensions/extensions/jev-decider/jev_decider/decision.py
new file mode 100644
index 00000000..3dc6cf98
--- /dev/null
+++ b/decision-extensions/extensions/jev-decider/jev_decider/decision.py
@@ -0,0 +1,265 @@
+"""Deterministic Jev request preparation and answer interpretation.
+
+This module performs no I/O and owns no sessions, credentials or deadlines.
+The optional trace dictionary receives only the existing diagnostic facts,
+including preparation facts when a later validation step fails.
+"""
+from __future__ import annotations
+
+import hashlib
+import json
+import math
+from dataclasses import dataclass
+from typing import Any, Protocol
+
+from .protocol import ProtocolError, encode_json
+
+
+class DecisionSettings(Protocol):
+ """Only the non-secret configuration consumed by a decision."""
+
+ mode: str
+ model: str
+ max_state_tokens: int
+ simple_threshold: float
+ competence_floor: float
+ branch_criteria: dict[str, str]
+ policy_configured: bool
+
+
+@dataclass(frozen=True)
+class PreparedDecision:
+ body: dict[str, Any]
+ target_trimmed: bool
+
+
+SIMPLE_BRANCH = "smart_saving_simple"
+
+
+COMPLEX_BRANCH = "smart_saving_complex"
+
+
+COMPETENCE_CRITERIA = [
+ "The branch was not competent for the task: it failed to make useful progress, repeatedly made avoidable errors, or required substantial correction.",
+ "The branch made useful but incomplete or uneven progress; the available evidence does not establish consistently competent execution.",
+ "The branch was competent for the task: it advanced or completed the work reliably with an appropriate process and no material correction.",
+]
+
+
+def criteria_hash(branches: dict[str, str]) -> str:
+ return hashlib.sha256(json.dumps(branches, sort_keys=True, ensure_ascii=False).encode()).hexdigest()
+
+
+def prepare_state(value: dict[str, Any], max_tokens: int) -> tuple[dict[str, Any], bool]:
+ state = {
+ "branches": value["branches"],
+ "latest_user": value["latest_user"],
+ "visible_conversation": list(value["visible_conversation"]),
+ "history_partial": value["history_partial"],
+ "assessment_from": value["assessment_from"],
+ }
+ original_from = value["assessment_from"]
+ removed = 0
+ while len(encode_json(state)) > max_tokens and state["visible_conversation"]:
+ state["visible_conversation"].pop(0)
+ removed += 1
+ if original_from is not None:
+ if removed >= len(value["visible_conversation"]):
+ state["assessment_from"] = None
+ else:
+ state["assessment_from"] = max(0, original_from - removed)
+ if removed:
+ state["history_partial"] = True
+ if len(encode_json(state)) > max_tokens:
+ raise ProtocolError("branches and latest_user exceed the configured Jev context budget")
+ target_trimmed = original_from is not None and removed > original_from
+ return state, target_trimmed
+
+
+def questions(mode: str, branches: dict[str, str], has_target: bool) -> dict[str, Any]:
+ if mode == "rules" and set(branches) != {SIMPLE_BRANCH, COMPLEX_BRANCH}:
+ raise ProtocolError("rules mode requires the two smart-saving branches")
+ if mode == "auto":
+ decision = {
+ "type": "choice",
+ "instructions": (
+ "Choose the best branch for the current routing round's latest_user. It may continue the "
+ "same user task, repeat prior text, or be a summary after a HiRoute rerouting boundary. "
+ "Consider the task's complexity and the visible history of how prior branches performed. "
+ "Preserve quality; use an economy branch only when it is appropriate for this work."
+ ),
+ "criteria": branches,
+ }
+ else:
+ decision = {
+ "type": "choice",
+ "instructions": (
+ "Classify the current routing round's latest_user by task complexity. It may continue the "
+ "same user task, repeat prior text, or be a summary. Use history only to resolve references "
+ "and understand the actual work; do not call a simple task complex merely because a prior "
+ "tool failed."
+ ),
+ "criteria": {
+ SIMPLE_BRANCH: branches[SIMPLE_BRANCH],
+ COMPLEX_BRANCH: branches[COMPLEX_BRANCH],
+ },
+ }
+ result: dict[str, Any] = {"branch" if mode == "auto" else "complexity": decision}
+ if has_target:
+ result["competence"] = {
+ "type": "score",
+ "instructions": (
+ "Rate whether the branch used by the assessable tail of visible_conversation was competent "
+ "for those routing rounds, including rounds with unknown terminal status. Consider progress, "
+ "tool activity, failed and recovered attempts, round trips, and explicit feedback in latest_user. "
+ "Repeated text, a summary, a continuation message, or silence is not by itself praise or a "
+ "complaint. Do not rate the current not-yet-executed routing round."
+ ),
+ "criteria": COMPETENCE_CRITERIA,
+ }
+ return result
+
+
+def _choice(answer: Any, branches: dict[str, str], *, probabilities: bool) -> tuple[str, dict[str, float]]:
+ if not isinstance(answer, dict) or answer.get("type") != "choice":
+ raise ProtocolError("missing or invalid Choice answer")
+ selected = answer.get("choice")
+ if selected not in branches:
+ raise ProtocolError("Choice answer selected an unknown branch")
+ if not probabilities:
+ return selected, {}
+ distribution = answer.get("probabilities")
+ if not isinstance(distribution, dict) or set(distribution) != set(branches):
+ raise ProtocolError("Choice probabilities do not match branches")
+ parsed: dict[str, float] = {}
+ for branch, probability in distribution.items():
+ if isinstance(probability, bool) or not isinstance(probability, (int, float)):
+ raise ProtocolError("Choice probability is not numeric")
+ probability = float(probability)
+ if not math.isfinite(probability) or not 0 <= probability <= 1:
+ raise ProtocolError("Choice probability is outside [0,1]")
+ parsed[branch] = probability
+ if not math.isclose(sum(parsed.values()), 1.0, abs_tol=1e-6):
+ raise ProtocolError("Choice probabilities do not sum to one")
+ if parsed[selected] + 1e-12 < max(parsed.values()):
+ raise ProtocolError("Choice is inconsistent with its probabilities")
+ return selected, parsed
+
+
+def _competence(answer: Any) -> float | None:
+ if not isinstance(answer, dict) or answer.get("type") != "score":
+ return None
+ score = answer.get("score")
+ if isinstance(score, bool) or not isinstance(score, (int, float)):
+ return None
+ score = float(score)
+ if not math.isfinite(score) or not 0 <= score <= 2:
+ return None
+ return score / 2
+
+
+def decision_response(
+ settings: DecisionSettings,
+ request: dict[str, Any],
+ upstream: Any,
+ target_trimmed: bool,
+ trace: dict[str, Any] | None = None,
+) -> dict[str, Any]:
+ trace = trace if trace is not None else {}
+ if not isinstance(upstream, dict) or not isinstance(upstream.get("answers"), dict):
+ raise ProtocolError("upstream response has no answers")
+ answers = upstream["answers"]
+ if settings.mode == "auto":
+ branch, _ = _choice(answers.get("branch"), request["branches"], probabilities=False)
+ trace.update(upstream_choice=branch, reason="auto_choice")
+ else:
+ selected, distribution = _choice(
+ answers.get("complexity"), request["branches"], probabilities=True
+ )
+ competence = _competence(answers.get("competence"))
+ branch = (
+ SIMPLE_BRANCH
+ if distribution[SIMPLE_BRANCH] >= settings.simple_threshold
+ and (competence is None or competence >= settings.competence_floor)
+ else COMPLEX_BRANCH
+ )
+ opportunity = distribution[SIMPLE_BRANCH] >= settings.simple_threshold
+ guard = competence is None or competence >= settings.competence_floor
+ trace.update(
+ upstream_choice=selected, probabilities=distribution,
+ simple_threshold=settings.simple_threshold,
+ competence_floor=settings.competence_floor,
+ simplicity_passed=opportunity, competence_passed=guard,
+ reason=("complexity_threshold" if not opportunity else
+ "competence_guard" if not guard else "economy_eligible"),
+ )
+ trace.update(
+ competence=_competence(answers.get("competence")),
+ competence_status=("missing" if "competence" not in answers else
+ "invalid" if _competence(answers["competence"]) is None else "valid"),
+ branch_id=branch,
+ )
+ response: dict[str, Any] = {"branch_id": branch}
+ if request["assessment_from"] is not None:
+ score = _competence(answers.get("competence"))
+ if score is not None:
+ response["assessment"] = {"score": score, "partial": target_trimmed}
+ return response
+
+
+def reported_usage(upstream: Any) -> dict[str, int | float] | None:
+ """Keep only reported numeric billing facts, never guess a missing charge."""
+ usage = upstream.get("usage") if isinstance(upstream, dict) else None
+ if not isinstance(usage, dict):
+ return None
+ result: dict[str, int | float] = {}
+ for name in ("input_tokens", "output_tokens"):
+ value = usage.get(name)
+ if type(value) is int and value >= 0:
+ result[name] = value
+ cost = usage.get("cost")
+ if type(cost) in (int, float) and cost >= 0:
+ try:
+ if math.isfinite(cost):
+ result["cost"] = cost
+ except OverflowError:
+ pass
+ return result or None
+
+
+def prepare_decision(
+ settings: DecisionSettings,
+ incoming: dict[str, Any],
+ trace: dict[str, Any] | None = None,
+) -> PreparedDecision:
+ """Prepare one upstream request from an already validated HiRoute request.
+
+ Policy precedence, whole-turn trimming and question text are the existing
+ service behavior. Neither preparation nor answer interpretation calls Jev.
+ """
+ trace = trace if trace is not None else {}
+ criteria_source = "request"
+ if set(incoming["branches"]) == {SIMPLE_BRANCH, COMPLEX_BRANCH}:
+ incoming = {**incoming, "branches": settings.branch_criteria}
+ criteria_source = "policy" if settings.policy_configured else "default"
+ elif settings.policy_configured:
+ raise ProtocolError("configured policy requires the two smart-saving branches")
+ trace.update(criteria_source=criteria_source,
+ criteria_sha256=criteria_hash(incoming["branches"]))
+ state, target_trimmed = prepare_state(incoming, settings.max_state_tokens)
+ trace.update(
+ input_turns=len(incoming["visible_conversation"]),
+ retained_turns=len(state["visible_conversation"]),
+ state_bytes=len(encode_json(state)), history_partial=state["history_partial"],
+ assessment_from=state["assessment_from"], target_trimmed=target_trimmed,
+ )
+ body = {
+ "model": settings.model,
+ "state": state,
+ "questions": questions(
+ settings.mode,
+ incoming["branches"],
+ state["assessment_from"] is not None,
+ ),
+ }
+ return PreparedDecision(body=body, target_trimmed=target_trimmed)
diff --git a/decision-extensions/extensions/jev-decider/jev_decider/protocol.py b/decision-extensions/extensions/jev-decider/jev_decider/protocol.py
new file mode 100644
index 00000000..72fe7ea8
--- /dev/null
+++ b/decision-extensions/extensions/jev-decider/jev_decider/protocol.py
@@ -0,0 +1,125 @@
+"""Strict HiRoute Decision API values and JSON encoding; no transport or I/O."""
+from __future__ import annotations
+
+import json
+from typing import Any
+
+
+class ProtocolError(ValueError):
+ pass
+
+
+class DuplicateField(ProtocolError):
+ pass
+
+
+def _strict_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
+ value: dict[str, Any] = {}
+ for key, item in pairs:
+ if key in value:
+ raise DuplicateField(f"duplicate field: {key}")
+ value[key] = item
+ return value
+
+
+def strict_json(data: bytes) -> Any:
+ try:
+ return json.loads(data, object_pairs_hook=_strict_object)
+ except (UnicodeDecodeError, json.JSONDecodeError, DuplicateField) as error:
+ raise ProtocolError("invalid JSON") from error
+
+
+def _exact(value: dict[str, Any], fields: set[str], optional: set[str] | None = None) -> None:
+ optional = optional or set()
+ if set(value) - fields - optional or fields - set(value):
+ raise ProtocolError("unexpected or missing field")
+
+
+def _text(value: Any, *, empty: bool = False) -> str:
+ if not isinstance(value, str) or (not empty and not value):
+ raise ProtocolError("expected text")
+ return value
+
+
+def _content_part(value: Any, *, tool: bool) -> None:
+ if not isinstance(value, dict):
+ raise ProtocolError("content part must be an object")
+ kind = value.get("kind")
+ if kind == "text":
+ _exact(value, {"kind", "text"})
+ _text(value["text"], empty=True)
+ elif kind == "unavailable":
+ _exact(value, {"kind", "source_kind"})
+ _text(value["source_kind"])
+ elif tool and kind == "tool_activity":
+ _exact(value, {"kind", "tool", "status"})
+ _text(value["tool"])
+ if value["status"] not in {"completed", "failed", "unknown"}:
+ raise ProtocolError("invalid tool status")
+ else:
+ raise ProtocolError("unsupported content part")
+
+
+def validate_hiroute_request(value: Any) -> dict[str, Any]:
+ if not isinstance(value, dict):
+ raise ProtocolError("request must be an object")
+ _exact(
+ value,
+ {
+ "branches",
+ "latest_user",
+ "visible_conversation",
+ "history_partial",
+ "assessment_from",
+ },
+ )
+ branches = value["branches"]
+ if not isinstance(branches, dict) or not branches:
+ raise ProtocolError("branches must be a non-empty object")
+ for branch, description in branches.items():
+ _text(branch)
+ _text(description)
+ latest = value["latest_user"]
+ if not isinstance(latest, list) or not latest:
+ raise ProtocolError("latest_user must be a non-empty array")
+ for part in latest:
+ _content_part(part, tool=False)
+ conversation = value["visible_conversation"]
+ if not isinstance(conversation, list):
+ raise ProtocolError("visible_conversation must be an array")
+ for turn in conversation:
+ if not isinstance(turn, dict):
+ raise ProtocolError("turn must be an object")
+ _exact(turn, {"branch_id", "user", "status", "steps"}, {"executed_branch_id"})
+ if turn["branch_id"] is not None:
+ _text(turn["branch_id"])
+ if "executed_branch_id" in turn:
+ _text(turn["executed_branch_id"])
+ if turn["status"] not in {"completed", "failed", "interrupted", "unknown"}:
+ raise ProtocolError("invalid turn status")
+ if not isinstance(turn["user"], list):
+ raise ProtocolError("turn user must be an array")
+ for part in turn["user"]:
+ _content_part(part, tool=False)
+ if not isinstance(turn["steps"], list):
+ raise ProtocolError("turn steps must be an array")
+ for step in turn["steps"]:
+ if not isinstance(step, list):
+ raise ProtocolError("step must be an array")
+ for part in step:
+ _content_part(part, tool=True)
+ if not isinstance(value["history_partial"], bool):
+ raise ProtocolError("history_partial must be boolean")
+ assessment_from = value["assessment_from"]
+ if assessment_from is not None and (
+ isinstance(assessment_from, bool)
+ or not isinstance(assessment_from, int)
+ or assessment_from < 0
+ or assessment_from >= len(conversation)
+ ):
+ raise ProtocolError("assessment_from is outside visible_conversation")
+ return value
+
+
+def encode_json(value: Any) -> bytes:
+ return json.dumps(value, ensure_ascii=False, separators=(",", ":")).encode()
diff --git a/decision-extensions/extensions/jev-decider/jev_decider/server.py b/decision-extensions/extensions/jev-decider/jev_decider/server.py
index 906eca93..76e271ed 100644
--- a/decision-extensions/extensions/jev-decider/jev_decider/server.py
+++ b/decision-extensions/extensions/jev-decider/jev_decider/server.py
@@ -1,28 +1,36 @@
+"""HTTP lifecycle for the official Jev decision service.
+
+Pure decisions live in decision.py; strict wire values in protocol.py; deployment
+configuration in settings.py. Imported public names remain available here for
+existing hosts that import jev_decider.server.
+"""
from __future__ import annotations
import asyncio
-import hashlib
import hmac
import json
import logging
-import math
import os
import time
import uuid
-from pathlib import Path
-from dataclasses import dataclass, field
from typing import Any
-from urllib.parse import urlsplit
from aiohttp import ClientError, ClientSession, ClientTimeout, web
+from .decision import (
+ COMPLEX_BRANCH, COMPETENCE_CRITERIA, SIMPLE_BRANCH, criteria_hash,
+ decision_response, prepare_decision, prepare_state, questions, reported_usage,
+)
+from .protocol import DuplicateField, ProtocolError, strict_json, validate_hiroute_request
+from .settings import (
+ DEFAULT_MODEL, DEFAULT_UPSTREAM, FORBIDDEN_INBOUND_HEADERS,
+ MAX_REQUEST_TIMEOUT_SECONDS, Settings, load_policy,
+)
+
-SIMPLE_BRANCH = "smart_saving_simple"
-COMPLEX_BRANCH = "smart_saving_complex"
-DEFAULT_MODEL = "typesafe/jev-1.13"
-DEFAULT_UPSTREAM = "https://openrouter.ai/api/alpha/decisions"
MAX_UPSTREAM_RESPONSE_BYTES = 64 * 1024
-MAX_REQUEST_TIMEOUT_SECONDS = 3600.0
+
+
LOGGER = logging.getLogger("jev_decider")
@@ -31,447 +39,6 @@ def log_event(event: str, **fields: Any) -> None:
"event": event, **fields}, ensure_ascii=False))
-FORBIDDEN_INBOUND_HEADERS = {
- "host",
- "content-length",
- "content-type",
- "transfer-encoding",
- "connection",
- "te",
- "trailer",
- "upgrade",
-}
-COMPETENCE_CRITERIA = [
- "The branch was not competent for the task: it failed to make useful progress, repeatedly made avoidable errors, or required substantial correction.",
- "The branch made useful but incomplete or uneven progress; the available evidence does not establish consistently competent execution.",
- "The branch was competent for the task: it advanced or completed the work reliably with an appropriate process and no material correction.",
-]
-
-
-class ProtocolError(ValueError):
- pass
-
-
-class DuplicateField(ProtocolError):
- pass
-
-
-def _strict_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
- value: dict[str, Any] = {}
- for key, item in pairs:
- if key in value:
- raise DuplicateField(f"duplicate field: {key}")
- value[key] = item
- return value
-
-
-def strict_json(data: bytes) -> Any:
- try:
- return json.loads(data, object_pairs_hook=_strict_object)
- except (UnicodeDecodeError, json.JSONDecodeError, DuplicateField) as error:
- raise ProtocolError("invalid JSON") from error
-
-
-def _exact(value: dict[str, Any], fields: set[str], optional: set[str] | None = None) -> None:
- optional = optional or set()
- if set(value) - fields - optional or fields - set(value):
- raise ProtocolError("unexpected or missing field")
-
-
-def _text(value: Any, *, empty: bool = False) -> str:
- if not isinstance(value, str) or (not empty and not value):
- raise ProtocolError("expected text")
- return value
-
-
-def _content_part(value: Any, *, tool: bool) -> None:
- if not isinstance(value, dict):
- raise ProtocolError("content part must be an object")
- kind = value.get("kind")
- if kind == "text":
- _exact(value, {"kind", "text"})
- _text(value["text"], empty=True)
- elif kind == "unavailable":
- _exact(value, {"kind", "source_kind"})
- _text(value["source_kind"])
- elif tool and kind == "tool_activity":
- _exact(value, {"kind", "tool", "status"})
- _text(value["tool"])
- if value["status"] not in {"completed", "failed", "unknown"}:
- raise ProtocolError("invalid tool status")
- else:
- raise ProtocolError("unsupported content part")
-
-
-def validate_hiroute_request(value: Any) -> dict[str, Any]:
- if not isinstance(value, dict):
- raise ProtocolError("request must be an object")
- _exact(
- value,
- {
- "branches",
- "latest_user",
- "visible_conversation",
- "history_partial",
- "assessment_from",
- },
- )
- branches = value["branches"]
- if not isinstance(branches, dict) or not branches:
- raise ProtocolError("branches must be a non-empty object")
- for branch, description in branches.items():
- _text(branch)
- _text(description)
- latest = value["latest_user"]
- if not isinstance(latest, list) or not latest:
- raise ProtocolError("latest_user must be a non-empty array")
- for part in latest:
- _content_part(part, tool=False)
- conversation = value["visible_conversation"]
- if not isinstance(conversation, list):
- raise ProtocolError("visible_conversation must be an array")
- for turn in conversation:
- if not isinstance(turn, dict):
- raise ProtocolError("turn must be an object")
- _exact(turn, {"branch_id", "user", "status", "steps"}, {"executed_branch_id"})
- if turn["branch_id"] is not None:
- _text(turn["branch_id"])
- if "executed_branch_id" in turn:
- _text(turn["executed_branch_id"])
- if turn["status"] not in {"completed", "failed", "interrupted", "unknown"}:
- raise ProtocolError("invalid turn status")
- if not isinstance(turn["user"], list):
- raise ProtocolError("turn user must be an array")
- for part in turn["user"]:
- _content_part(part, tool=False)
- if not isinstance(turn["steps"], list):
- raise ProtocolError("turn steps must be an array")
- for step in turn["steps"]:
- if not isinstance(step, list):
- raise ProtocolError("step must be an array")
- for part in step:
- _content_part(part, tool=True)
- if not isinstance(value["history_partial"], bool):
- raise ProtocolError("history_partial must be boolean")
- assessment_from = value["assessment_from"]
- if assessment_from is not None and (
- isinstance(assessment_from, bool)
- or not isinstance(assessment_from, int)
- or assessment_from < 0
- or assessment_from >= len(conversation)
- ):
- raise ProtocolError("assessment_from is outside visible_conversation")
- return value
-
-
-@dataclass(frozen=True)
-class Settings:
- mode: str
- api_key: str
- upstream_url: str
- model: str
- request_timeout_seconds: float
- max_state_tokens: int
- max_concurrency: int
- simple_threshold: float
- competence_floor: float
- inbound_header_name: str | None
- inbound_header_value: str | None
- branch_criteria: dict[str, str] = field(default_factory=lambda: load_policy(None))
- policy_configured: bool = False
-
- @classmethod
- def from_env(cls) -> "Settings":
- mode = os.getenv("JEV_MODE", "auto")
- key_file = os.getenv("OPENROUTER_API_KEY_FILE", "")
- if not key_file:
- raise RuntimeError("OPENROUTER_API_KEY_FILE is required")
- try:
- key_path = Path(key_file)
- if not key_path.is_absolute():
- raise RuntimeError("OPENROUTER_API_KEY_FILE must be an absolute path")
- key_bytes = key_path.read_bytes()
- except OSError as error:
- raise RuntimeError("OPENROUTER_API_KEY_FILE cannot be read") from error
- if len(key_bytes) > 16 * 1024:
- raise RuntimeError("OPENROUTER_API_KEY_FILE is too large")
- try:
- api_key = key_bytes.decode("utf-8").strip()
- except UnicodeDecodeError as error:
- raise RuntimeError("OPENROUTER_API_KEY_FILE must contain UTF-8 text") from error
- upstream_url = os.getenv("OPENROUTER_DECISIONS_URL", DEFAULT_UPSTREAM)
- timeout = _finite_env("JEV_REQUEST_TIMEOUT_SECONDS", 2.8)
- max_state_tokens = _positive_int_env("JEV_MAX_STATE_TOKENS", 24_000)
- max_concurrency = _positive_int_env("JEV_MAX_CONCURRENCY", 32)
- if mode == "auto" and (
- "JEV_SIMPLE_THRESHOLD" in os.environ
- or "JEV_COMPETENCE_FLOOR" in os.environ
- ):
- raise RuntimeError("rules thresholds are not accepted in auto mode")
- simple_threshold = _probability_env("JEV_SIMPLE_THRESHOLD", 0.80)
- competence_floor = _probability_env("JEV_COMPETENCE_FLOOR", 0.50)
- header_name = os.getenv("DECIDER_AUTH_HEADER_NAME")
- header_value = os.getenv("DECIDER_AUTH_HEADER_VALUE")
- if mode not in {"auto", "rules"}:
- raise RuntimeError("JEV_MODE must be auto or rules")
- if not api_key or any(character in api_key for character in "\r\n"):
- raise RuntimeError("OPENROUTER_API_KEY_FILE contains an invalid key")
- parsed = urlsplit(upstream_url)
- if parsed.scheme not in {"http", "https"} or not parsed.netloc or parsed.fragment:
- raise RuntimeError("OPENROUTER_DECISIONS_URL must be an HTTP(S) URL without a fragment")
- if timeout <= 0 or timeout > MAX_REQUEST_TIMEOUT_SECONDS:
- raise RuntimeError("JEV_REQUEST_TIMEOUT_SECONDS must be in (0, 3600]")
- if bool(header_name) != bool(header_value):
- raise RuntimeError("both DECIDER_AUTH_HEADER_NAME and DECIDER_AUTH_HEADER_VALUE are required")
- if header_name is not None and not _valid_header_name(header_name):
- raise RuntimeError("DECIDER_AUTH_HEADER_NAME is invalid")
- if header_value is not None and (
- not header_value or any(character in header_value for character in "\r\n")
- ):
- raise RuntimeError("DECIDER_AUTH_HEADER_VALUE is invalid")
- return cls(
- mode=mode,
- api_key=api_key,
- upstream_url=upstream_url,
- model=os.getenv("JEV_MODEL", DEFAULT_MODEL),
- request_timeout_seconds=timeout,
- max_state_tokens=max_state_tokens,
- max_concurrency=max_concurrency,
- simple_threshold=simple_threshold,
- competence_floor=competence_floor,
- inbound_header_name=header_name,
- inbound_header_value=header_value,
- branch_criteria=load_policy(os.getenv("JEV_POLICY_FILE")),
- policy_configured="JEV_POLICY_FILE" in os.environ,
- )
-
-
-def load_policy(filename: str | None) -> dict[str, str]:
- path = Path(filename) if filename is not None else Path(__file__).with_name("policy.default.json")
- if not path.is_absolute():
- raise RuntimeError("JEV_POLICY_FILE must be an absolute path")
- try:
- with path.open("rb") as stream:
- data = stream.read(4097)
- except OSError as error:
- raise RuntimeError("JEV_POLICY_FILE cannot be read") from error
- if len(data) > 4096:
- raise RuntimeError("JEV_POLICY_FILE must be at most 4096 bytes")
- try:
- data.decode("utf-8")
- value = strict_json(data)
- if not isinstance(value, dict) or set(value) != {"simple", "complex"}:
- raise ProtocolError("invalid policy fields")
- if any(not isinstance(text, str) or not text.strip() for text in value.values()):
- raise ProtocolError("invalid policy descriptions")
- # Validate escaped Unicode too, before a request attempts UTF-8 encoding.
- _encoded(value)
- except (ProtocolError, UnicodeError) as error:
- raise RuntimeError("JEV_POLICY_FILE requires UTF-8 JSON with nonempty simple and complex strings") from error
- return {SIMPLE_BRANCH: value["simple"], COMPLEX_BRANCH: value["complex"]}
-
-
-def criteria_hash(branches: dict[str, str]) -> str:
- return hashlib.sha256(json.dumps(branches, sort_keys=True, ensure_ascii=False).encode()).hexdigest()
-
-
-def _finite_env(name: str, default: float) -> float:
- try:
- value = float(os.getenv(name, str(default)))
- except ValueError as error:
- raise RuntimeError(f"{name} must be a finite number") from error
- if not math.isfinite(value):
- raise RuntimeError(f"{name} must be a finite number")
- return value
-
-
-def _positive_int_env(name: str, default: int) -> int:
- try:
- value = int(os.getenv(name, str(default)))
- except ValueError as error:
- raise RuntimeError(f"{name} must be a positive integer") from error
- if value <= 0:
- raise RuntimeError(f"{name} must be a positive integer")
- return value
-
-
-def _probability_env(name: str, default: float) -> float:
- value = _finite_env(name, default)
- if not 0 <= value <= 1:
- raise RuntimeError(f"{name} must be in [0, 1]")
- return value
-
-
-def _valid_header_name(value: str) -> bool:
- token = "!#$%&'*+-.^_`|~"
- return (
- 0 < len(value) <= 128
- and all(character.isascii() and (character.isalnum() or character in token) for character in value)
- and value.lower() not in FORBIDDEN_INBOUND_HEADERS
- )
-
-
-def _encoded(value: Any) -> bytes:
- return json.dumps(value, ensure_ascii=False, separators=(",", ":")).encode()
-
-
-def prepare_state(value: dict[str, Any], max_tokens: int) -> tuple[dict[str, Any], bool]:
- state = {
- "branches": value["branches"],
- "latest_user": value["latest_user"],
- "visible_conversation": list(value["visible_conversation"]),
- "history_partial": value["history_partial"],
- "assessment_from": value["assessment_from"],
- }
- original_from = value["assessment_from"]
- removed = 0
- while len(_encoded(state)) > max_tokens and state["visible_conversation"]:
- state["visible_conversation"].pop(0)
- removed += 1
- if original_from is not None:
- if removed >= len(value["visible_conversation"]):
- state["assessment_from"] = None
- else:
- state["assessment_from"] = max(0, original_from - removed)
- if removed:
- state["history_partial"] = True
- if len(_encoded(state)) > max_tokens:
- raise ProtocolError("branches and latest_user exceed the configured Jev context budget")
- target_trimmed = original_from is not None and removed > original_from
- return state, target_trimmed
-
-
-def questions(mode: str, branches: dict[str, str], has_target: bool) -> dict[str, Any]:
- if mode == "rules" and set(branches) != {SIMPLE_BRANCH, COMPLEX_BRANCH}:
- raise ProtocolError("rules mode requires the two smart-saving branches")
- if mode == "auto":
- decision = {
- "type": "choice",
- "instructions": (
- "Choose the best branch for the current routing round's latest_user. It may continue the "
- "same user task, repeat prior text, or be a summary after a HiRoute rerouting boundary. "
- "Consider the task's complexity and the visible history of how prior branches performed. "
- "Preserve quality; use an economy branch only when it is appropriate for this work."
- ),
- "criteria": branches,
- }
- else:
- decision = {
- "type": "choice",
- "instructions": (
- "Classify the current routing round's latest_user by task complexity. It may continue the "
- "same user task, repeat prior text, or be a summary. Use history only to resolve references "
- "and understand the actual work; do not call a simple task complex merely because a prior "
- "tool failed."
- ),
- "criteria": {
- SIMPLE_BRANCH: branches[SIMPLE_BRANCH],
- COMPLEX_BRANCH: branches[COMPLEX_BRANCH],
- },
- }
- result: dict[str, Any] = {"branch" if mode == "auto" else "complexity": decision}
- if has_target:
- result["competence"] = {
- "type": "score",
- "instructions": (
- "Rate whether the branch used by the assessable tail of visible_conversation was competent "
- "for those routing rounds, including rounds with unknown terminal status. Consider progress, "
- "tool activity, failed and recovered attempts, round trips, and explicit feedback in latest_user. "
- "Repeated text, a summary, a continuation message, or silence is not by itself praise or a "
- "complaint. Do not rate the current not-yet-executed routing round."
- ),
- "criteria": COMPETENCE_CRITERIA,
- }
- return result
-
-
-def _choice(answer: Any, branches: dict[str, str], *, probabilities: bool) -> tuple[str, dict[str, float]]:
- if not isinstance(answer, dict) or answer.get("type") != "choice":
- raise ProtocolError("missing or invalid Choice answer")
- selected = answer.get("choice")
- if selected not in branches:
- raise ProtocolError("Choice answer selected an unknown branch")
- if not probabilities:
- return selected, {}
- distribution = answer.get("probabilities")
- if not isinstance(distribution, dict) or set(distribution) != set(branches):
- raise ProtocolError("Choice probabilities do not match branches")
- parsed: dict[str, float] = {}
- for branch, probability in distribution.items():
- if isinstance(probability, bool) or not isinstance(probability, (int, float)):
- raise ProtocolError("Choice probability is not numeric")
- probability = float(probability)
- if not math.isfinite(probability) or not 0 <= probability <= 1:
- raise ProtocolError("Choice probability is outside [0,1]")
- parsed[branch] = probability
- if not math.isclose(sum(parsed.values()), 1.0, abs_tol=1e-6):
- raise ProtocolError("Choice probabilities do not sum to one")
- if parsed[selected] + 1e-12 < max(parsed.values()):
- raise ProtocolError("Choice is inconsistent with its probabilities")
- return selected, parsed
-
-
-def _competence(answer: Any) -> float | None:
- if not isinstance(answer, dict) or answer.get("type") != "score":
- return None
- score = answer.get("score")
- if isinstance(score, bool) or not isinstance(score, (int, float)):
- return None
- score = float(score)
- if not math.isfinite(score) or not 0 <= score <= 2:
- return None
- return score / 2
-
-
-def decision_response(
- settings: Settings,
- request: dict[str, Any],
- upstream: Any,
- target_trimmed: bool,
- trace: dict[str, Any] | None = None,
-) -> dict[str, Any]:
- trace = trace if trace is not None else {}
- if not isinstance(upstream, dict) or not isinstance(upstream.get("answers"), dict):
- raise ProtocolError("upstream response has no answers")
- answers = upstream["answers"]
- if settings.mode == "auto":
- branch, _ = _choice(answers.get("branch"), request["branches"], probabilities=False)
- trace.update(upstream_choice=branch, reason="auto_choice")
- else:
- selected, distribution = _choice(
- answers.get("complexity"), request["branches"], probabilities=True
- )
- competence = _competence(answers.get("competence"))
- branch = (
- SIMPLE_BRANCH
- if distribution[SIMPLE_BRANCH] >= settings.simple_threshold
- and (competence is None or competence >= settings.competence_floor)
- else COMPLEX_BRANCH
- )
- opportunity = distribution[SIMPLE_BRANCH] >= settings.simple_threshold
- guard = competence is None or competence >= settings.competence_floor
- trace.update(
- upstream_choice=selected, probabilities=distribution,
- simple_threshold=settings.simple_threshold,
- competence_floor=settings.competence_floor,
- simplicity_passed=opportunity, competence_passed=guard,
- reason=("complexity_threshold" if not opportunity else
- "competence_guard" if not guard else "economy_eligible"),
- )
- trace.update(
- competence=_competence(answers.get("competence")),
- competence_status=("missing" if "competence" not in answers else
- "invalid" if _competence(answers["competence"]) is None else "valid"),
- branch_id=branch,
- )
- response: dict[str, Any] = {"branch_id": branch}
- if request["assessment_from"] is not None:
- score = _competence(answers.get("competence"))
- if score is not None:
- response["assessment"] = {"score": score, "partial": target_trimmed}
- return response
-
-
async def health(_: web.Request) -> web.Response:
return web.json_response({"status": "ok"})
@@ -488,26 +55,6 @@ async def _bounded_response(response: Any) -> bytes:
return bytes(body)
-def reported_usage(upstream: Any) -> dict[str, int | float] | None:
- """Keep only reported numeric billing facts, never guess a missing charge."""
- usage = upstream.get("usage") if isinstance(upstream, dict) else None
- if not isinstance(usage, dict):
- return None
- result: dict[str, int | float] = {}
- for name in ("input_tokens", "output_tokens"):
- value = usage.get(name)
- if type(value) is int and value >= 0:
- result[name] = value
- cost = usage.get("cost")
- if type(cost) in (int, float) and cost >= 0:
- try:
- if math.isfinite(cost):
- result["cost"] = cost
- except OverflowError:
- pass
- return result or None
-
-
async def decide(request: web.Request) -> web.Response:
decision_id = uuid.uuid4().hex
started = time.monotonic()
@@ -530,30 +77,7 @@ async def decide(request: web.Request) -> web.Response:
async with asyncio.timeout(settings.request_timeout_seconds):
trace["phase"] = "validation"
incoming = validate_hiroute_request(strict_json(await request.read()))
- criteria_source = "request"
- if set(incoming["branches"]) == {SIMPLE_BRANCH, COMPLEX_BRANCH}:
- incoming = {**incoming, "branches": settings.branch_criteria}
- criteria_source = "policy" if settings.policy_configured else "default"
- elif settings.policy_configured:
- raise ProtocolError("configured policy requires the two smart-saving branches")
- trace.update(criteria_source=criteria_source,
- criteria_sha256=criteria_hash(incoming["branches"]))
- state, target_trimmed = prepare_state(incoming, settings.max_state_tokens)
- trace.update(
- input_turns=len(incoming["visible_conversation"]),
- retained_turns=len(state["visible_conversation"]),
- state_bytes=len(_encoded(state)), history_partial=state["history_partial"],
- assessment_from=state["assessment_from"], target_trimmed=target_trimmed,
- )
- body = {
- "model": settings.model,
- "state": state,
- "questions": questions(
- settings.mode,
- incoming["branches"],
- state["assessment_from"] is not None,
- ),
- }
+ prepared = prepare_decision(settings, incoming, trace)
session: ClientSession = request.app[CLIENT]
upstream_started = True
trace["phase"] = "queue"
@@ -562,7 +86,7 @@ async def decide(request: web.Request) -> web.Response:
trace.update(queue_ms=round((time.monotonic() - queued) * 1000, 2), phase="upstream")
async with session.post(
settings.upstream_url,
- json=body,
+ json=prepared.body,
headers={
"Authorization": f"Bearer {settings.api_key}",
"Content-Type": "application/json",
@@ -579,7 +103,9 @@ async def decide(request: web.Request) -> web.Response:
upstream = strict_json(await _bounded_response(upstream_response))
trace["upstream_usage"] = reported_usage(upstream)
trace["phase"] = "decision"
- result = decision_response(settings, state, upstream, target_trimmed, trace)
+ result = decision_response(
+ settings, prepared.body["state"], upstream, prepared.target_trimmed, trace
+ )
return finish(result)
except ProtocolError as error:
trace["validation_error"] = str(error)
@@ -623,7 +149,11 @@ async def _close_client(app: web.Application) -> None:
SETTINGS = web.AppKey("settings", Settings)
+
+
CLIENT = web.AppKey("client", ClientSession)
+
+
CONCURRENCY = web.AppKey("concurrency", asyncio.Semaphore)
diff --git a/decision-extensions/extensions/jev-decider/jev_decider/settings.py b/decision-extensions/extensions/jev-decider/jev_decider/settings.py
new file mode 100644
index 00000000..16dc2191
--- /dev/null
+++ b/decision-extensions/extensions/jev-decider/jev_decider/settings.py
@@ -0,0 +1,175 @@
+"""Deployment configuration and bounded policy/key-file loading."""
+from __future__ import annotations
+
+import math
+import os
+from dataclasses import dataclass, field
+from pathlib import Path
+from urllib.parse import urlsplit
+
+from .decision import COMPLEX_BRANCH, SIMPLE_BRANCH
+from .protocol import ProtocolError, encode_json, strict_json
+
+
+DEFAULT_MODEL = "typesafe/jev-1.13"
+
+
+DEFAULT_UPSTREAM = "https://openrouter.ai/api/alpha/decisions"
+
+
+MAX_REQUEST_TIMEOUT_SECONDS = 3600.0
+
+
+FORBIDDEN_INBOUND_HEADERS = {
+ "host",
+ "content-length",
+ "content-type",
+ "transfer-encoding",
+ "connection",
+ "te",
+ "trailer",
+ "upgrade",
+}
+
+
+@dataclass(frozen=True)
+class Settings:
+ mode: str
+ api_key: str
+ upstream_url: str
+ model: str
+ request_timeout_seconds: float
+ max_state_tokens: int
+ max_concurrency: int
+ simple_threshold: float
+ competence_floor: float
+ inbound_header_name: str | None
+ inbound_header_value: str | None
+ branch_criteria: dict[str, str] = field(default_factory=lambda: load_policy(None))
+ policy_configured: bool = False
+
+ @classmethod
+ def from_env(cls) -> "Settings":
+ mode = os.getenv("JEV_MODE", "auto")
+ key_file = os.getenv("OPENROUTER_API_KEY_FILE", "")
+ if not key_file:
+ raise RuntimeError("OPENROUTER_API_KEY_FILE is required")
+ try:
+ key_path = Path(key_file)
+ if not key_path.is_absolute():
+ raise RuntimeError("OPENROUTER_API_KEY_FILE must be an absolute path")
+ key_bytes = key_path.read_bytes()
+ except OSError as error:
+ raise RuntimeError("OPENROUTER_API_KEY_FILE cannot be read") from error
+ if len(key_bytes) > 16 * 1024:
+ raise RuntimeError("OPENROUTER_API_KEY_FILE is too large")
+ try:
+ api_key = key_bytes.decode("utf-8").strip()
+ except UnicodeDecodeError as error:
+ raise RuntimeError("OPENROUTER_API_KEY_FILE must contain UTF-8 text") from error
+ upstream_url = os.getenv("OPENROUTER_DECISIONS_URL", DEFAULT_UPSTREAM)
+ timeout = _finite_env("JEV_REQUEST_TIMEOUT_SECONDS", 2.8)
+ max_state_tokens = _positive_int_env("JEV_MAX_STATE_TOKENS", 24_000)
+ max_concurrency = _positive_int_env("JEV_MAX_CONCURRENCY", 32)
+ if mode == "auto" and (
+ "JEV_SIMPLE_THRESHOLD" in os.environ
+ or "JEV_COMPETENCE_FLOOR" in os.environ
+ ):
+ raise RuntimeError("rules thresholds are not accepted in auto mode")
+ simple_threshold = _probability_env("JEV_SIMPLE_THRESHOLD", 0.80)
+ competence_floor = _probability_env("JEV_COMPETENCE_FLOOR", 0.50)
+ header_name = os.getenv("DECIDER_AUTH_HEADER_NAME")
+ header_value = os.getenv("DECIDER_AUTH_HEADER_VALUE")
+ if mode not in {"auto", "rules"}:
+ raise RuntimeError("JEV_MODE must be auto or rules")
+ if not api_key or any(character in api_key for character in "\r\n"):
+ raise RuntimeError("OPENROUTER_API_KEY_FILE contains an invalid key")
+ parsed = urlsplit(upstream_url)
+ if parsed.scheme not in {"http", "https"} or not parsed.netloc or parsed.fragment:
+ raise RuntimeError("OPENROUTER_DECISIONS_URL must be an HTTP(S) URL without a fragment")
+ if timeout <= 0 or timeout > MAX_REQUEST_TIMEOUT_SECONDS:
+ raise RuntimeError("JEV_REQUEST_TIMEOUT_SECONDS must be in (0, 3600]")
+ if bool(header_name) != bool(header_value):
+ raise RuntimeError("both DECIDER_AUTH_HEADER_NAME and DECIDER_AUTH_HEADER_VALUE are required")
+ if header_name is not None and not _valid_header_name(header_name):
+ raise RuntimeError("DECIDER_AUTH_HEADER_NAME is invalid")
+ if header_value is not None and (
+ not header_value or any(character in header_value for character in "\r\n")
+ ):
+ raise RuntimeError("DECIDER_AUTH_HEADER_VALUE is invalid")
+ return cls(
+ mode=mode,
+ api_key=api_key,
+ upstream_url=upstream_url,
+ model=os.getenv("JEV_MODEL", DEFAULT_MODEL),
+ request_timeout_seconds=timeout,
+ max_state_tokens=max_state_tokens,
+ max_concurrency=max_concurrency,
+ simple_threshold=simple_threshold,
+ competence_floor=competence_floor,
+ inbound_header_name=header_name,
+ inbound_header_value=header_value,
+ branch_criteria=load_policy(os.getenv("JEV_POLICY_FILE")),
+ policy_configured="JEV_POLICY_FILE" in os.environ,
+ )
+
+
+def load_policy(filename: str | None) -> dict[str, str]:
+ path = Path(filename) if filename is not None else Path(__file__).with_name("policy.default.json")
+ if not path.is_absolute():
+ raise RuntimeError("JEV_POLICY_FILE must be an absolute path")
+ try:
+ with path.open("rb") as stream:
+ data = stream.read(4097)
+ except OSError as error:
+ raise RuntimeError("JEV_POLICY_FILE cannot be read") from error
+ if len(data) > 4096:
+ raise RuntimeError("JEV_POLICY_FILE must be at most 4096 bytes")
+ try:
+ data.decode("utf-8")
+ value = strict_json(data)
+ if not isinstance(value, dict) or set(value) != {"simple", "complex"}:
+ raise ProtocolError("invalid policy fields")
+ if any(not isinstance(text, str) or not text.strip() for text in value.values()):
+ raise ProtocolError("invalid policy descriptions")
+ # Validate escaped Unicode too, before a request attempts UTF-8 encoding.
+ encode_json(value)
+ except (ProtocolError, UnicodeError) as error:
+ raise RuntimeError("JEV_POLICY_FILE requires UTF-8 JSON with nonempty simple and complex strings") from error
+ return {SIMPLE_BRANCH: value["simple"], COMPLEX_BRANCH: value["complex"]}
+
+
+def _finite_env(name: str, default: float) -> float:
+ try:
+ value = float(os.getenv(name, str(default)))
+ except ValueError as error:
+ raise RuntimeError(f"{name} must be a finite number") from error
+ if not math.isfinite(value):
+ raise RuntimeError(f"{name} must be a finite number")
+ return value
+
+
+def _positive_int_env(name: str, default: int) -> int:
+ try:
+ value = int(os.getenv(name, str(default)))
+ except ValueError as error:
+ raise RuntimeError(f"{name} must be a positive integer") from error
+ if value <= 0:
+ raise RuntimeError(f"{name} must be a positive integer")
+ return value
+
+
+def _probability_env(name: str, default: float) -> float:
+ value = _finite_env(name, default)
+ if not 0 <= value <= 1:
+ raise RuntimeError(f"{name} must be in [0, 1]")
+ return value
+
+
+def _valid_header_name(value: str) -> bool:
+ token = "!#$%&'*+-.^_`|~"
+ return (
+ 0 < len(value) <= 128
+ and all(character.isascii() and (character.isalnum() or character in token) for character in value)
+ and value.lower() not in FORBIDDEN_INBOUND_HEADERS
+ )
diff --git a/decision-extensions/extensions/jev-decider/tests/README.md b/decision-extensions/extensions/jev-decider/tests/README.md
new file mode 100644
index 00000000..8864ffd5
--- /dev/null
+++ b/decision-extensions/extensions/jev-decider/tests/README.md
@@ -0,0 +1,45 @@
+# Decision service behavior tests
+
+Run `python -m unittest -v` from the extension directory with its declared
+dependencies available. Tests use the real HTTP handler and a loopback upstream;
+they neither load a real key nor call a paid provider.
+
+Start with the capability classes in [test_server.py](test_server.py):
+
+| Capability | Owning tests |
+| --- | --- |
+| Select an allowed branch, including a third natural-language branch; apply the existing binary rules policy | `BranchSelectionTests` |
+| Assess prior execution separately from the new choice; preserve whole turns and mark missing evidence | `HistoryAssessmentTests` |
+| Explain decisions and retain reported costs, including invalid decisions; never invent missing usage | `DecisionEvidenceTests` |
+| Enforce authentication, input/output bounds, one-call time budget, concurrency, proxy routing and health isolation | `ServiceBoundaryTests` |
+| Load bounded configuration and fail invalid policy files without silently replacing them | `SettingsTests` |
+
+[decision_cases.py](decision_cases.py) contains independent request, upstream
+answer and expected-output examples. One HTTP test runs those examples for binary
+auto, prior-segment assessment, the rules competence guard and generic auto
+selection. It checks the full upstream payload, exact prompts, response and one
+authenticated call. Four former success tests are represented by these four
+capabilities, rather than four copies of the launcher and response assertions.
+The generic case actually selects the third branch; it does not merely check
+that the third definition was forwarded. A fifth example retains the distinct
+binary-plus-extra-branch boundary: default smart-saving descriptions must not
+replace an extended request's definitions.
+
+[test_decision.py](test_decision.py) reuses those same examples at the pure
+module boundary, without credentials, HTTP or an event loop. Run it with
+`python -m unittest tests.test_decision -v`; no third-party dependency is needed.
+The HTTP invocation remains necessary to prove production wiring, single-call
+behavior and authentication. It shares expectations instead of maintaining a
+second set of almost identical fixtures.
+
+Literal prompts are a model-facing behavior contract, not a snapshot of source
+layout. Expectations never import producer prompts or calculate the expected
+branch through the production algorithm. Prompt changes require a deliberate
+contract update; moving Python functions does not.
+
+Keep the distinct threshold, partial-history, invalid optional Score, unknown
+branch, timeout, authentication and paid-failure-usage assertions. They cannot
+be replaced by a single successful branch-selection example. These tests prove
+the extension contract; HiRoute routing, publication, cancellation and actual
+business-model selection belong to the production Gateway tests linked in the
+[extension README](../README.md#opt-in-hiroute--jev-smoke).
diff --git a/decision-extensions/extensions/jev-decider/tests/decision_cases.py b/decision-extensions/extensions/jev-decider/tests/decision_cases.py
new file mode 100644
index 00000000..b3ef0194
--- /dev/null
+++ b/decision-extensions/extensions/jev-decider/tests/decision_cases.py
@@ -0,0 +1,116 @@
+"""Independent examples of the existing Jev request/answer contract.
+
+Expected prompts are deliberately literal: changing a prompt changes what the
+model is asked, even when the HTTP response shape stays the same. No expectation
+imports a producer constant or calls the decision implementation.
+"""
+
+AUTO_INSTRUCTIONS = (
+ "Choose the best branch for the current routing round's latest_user. It may continue the "
+ "same user task, repeat prior text, or be a summary after a HiRoute rerouting boundary. "
+ "Consider the task's complexity and the visible history of how prior branches performed. "
+ "Preserve quality; use an economy branch only when it is appropriate for this work."
+)
+RULES_INSTRUCTIONS = (
+ "Classify the current routing round's latest_user by task complexity. It may continue the "
+ "same user task, repeat prior text, or be a summary. Use history only to resolve references "
+ "and understand the actual work; do not call a simple task complex merely because a prior "
+ "tool failed."
+)
+ASSESSMENT_QUESTION = {
+ "type": "score",
+ "instructions": (
+ "Rate whether the branch used by the assessable tail of visible_conversation was competent "
+ "for those routing rounds, including rounds with unknown terminal status. Consider progress, "
+ "tool activity, failed and recovered attempts, round trips, and explicit feedback in latest_user. "
+ "Repeated text, a summary, a continuation message, or silence is not by itself praise or a "
+ "complaint. Do not rate the current not-yet-executed routing round."
+ ),
+ "criteria": [
+ "The branch was not competent for the task: it failed to make useful progress, repeatedly made avoidable errors, or required substantial correction.",
+ "The branch made useful but incomplete or uneven progress; the available evidence does not establish consistently competent execution.",
+ "The branch was competent for the task: it advanced or completed the work reliably with an appropriate process and no material correction.",
+ ],
+}
+
+
+def decision_cases() -> list[dict]:
+ policy = {
+ "smart_saving_simple": "Bounded changes following existing patterns.",
+ "smart_saving_complex": "Uncertain root causes and architectural tradeoffs.",
+ }
+ generic = {"translate": "Translate prose.", "code": "Write code.", "explain": "Explain a concept."}
+ previous = [{
+ "branch_id": "smart_saving_simple",
+ "executed_branch_id": "smart_saving_complex",
+ "user": [{"kind": "text", "text": "Previous task"}],
+ "status": "unknown",
+ "steps": [[{"kind": "tool_activity", "tool": "apply_patch", "status": "completed"}]],
+ }]
+ examples = [
+ ("auto_first_round", "auto", [], None,
+ {"answers": {"branch": {"type": "choice", "choice": "smart_saving_simple"}}},
+ {"branch_id": "smart_saving_simple"}),
+ ("auto_assesses_previous_execution", "auto", previous, 0,
+ {"answers": {"branch": {"type": "choice", "choice": "smart_saving_simple"},
+ "competence": {"type": "score", "score": 1.2}}},
+ {"branch_id": "smart_saving_simple", "assessment": {"score": 0.6, "partial": False}}),
+ ("rules_competence_guard", "rules", previous, 0,
+ {"answers": {"complexity": {"type": "choice", "choice": "smart_saving_simple",
+ "probabilities": {"smart_saving_simple": 0.95, "smart_saving_complex": 0.05}},
+ "competence": {"type": "score", "score": 0.2}}},
+ {"branch_id": "smart_saving_complex", "assessment": {"score": 0.1, "partial": False}}),
+ ("auto_selects_third_natural_language_branch", "auto", [], None,
+ {"answers": {"branch": {"type": "choice", "choice": "explain"}}},
+ {"branch_id": "explain"}),
+ ("auto_keeps_extended_smart_saving_definitions", "auto", [], None,
+ {"answers": {"branch": {"type": "choice", "choice": "explain"}}},
+ {"branch_id": "explain"}),
+ ]
+ cases = []
+ for name, mode, history, assessment_from, upstream, response in examples:
+ custom = name in {
+ "auto_selects_third_natural_language_branch",
+ "auto_keeps_extended_smart_saving_definitions",
+ }
+ branches = generic if custom else policy
+ if name == "auto_keeps_extended_smart_saving_definitions":
+ # Adding a branch must disable the exact-binary policy override.
+ branches = {
+ "smart_saving_simple": "Keep this incoming simple description.",
+ "smart_saving_complex": "Keep this incoming complex description.",
+ "explain": "Explain a concept.",
+ }
+ request = {
+ "branches": branches if custom else {
+ "smart_saving_simple": "Incoming simple description.",
+ "smart_saving_complex": "Incoming complex description.",
+ },
+ "latest_user": [{"kind": "text", "text": "Explain this change. 解释这个改动。"}],
+ "visible_conversation": history,
+ "history_partial": False,
+ "assessment_from": assessment_from,
+ }
+ expected_questions = {
+ "branch" if mode == "auto" else "complexity": {
+ "type": "choice",
+ "instructions": AUTO_INSTRUCTIONS if mode == "auto" else RULES_INSTRUCTIONS,
+ "criteria": branches,
+ },
+ }
+ if assessment_from is not None:
+ expected_questions["competence"] = ASSESSMENT_QUESTION
+ cases.append({
+ "name": name,
+ "mode": mode,
+ "settings": {} if custom else {"branch_criteria": policy},
+ "request": request,
+ "upstream": upstream,
+ "expected_upstream": {
+ "model": "typesafe/jev-1.13",
+ "state": {**request, "branches": branches},
+ "questions": expected_questions,
+ },
+ "expected_response": response,
+ })
+ return cases
diff --git a/decision-extensions/extensions/jev-decider/tests/test_decision.py b/decision-extensions/extensions/jev-decider/tests/test_decision.py
new file mode 100644
index 00000000..b4f8f4dc
--- /dev/null
+++ b/decision-extensions/extensions/jev-decider/tests/test_decision.py
@@ -0,0 +1,30 @@
+"""Run the same decision examples without HTTP, credentials or an event loop."""
+from __future__ import annotations
+
+from types import SimpleNamespace
+import unittest
+
+from jev_decider.decision import decision_response, prepare_decision
+from jev_decider.protocol import validate_hiroute_request
+from tests.decision_cases import decision_cases
+
+
+class DecisionContractTests(unittest.TestCase):
+ def test_decision_examples_do_not_require_a_service(self) -> None:
+ for case in decision_cases():
+ with self.subTest(capability=case["name"]):
+ settings = SimpleNamespace(
+ mode=case["mode"],
+ model="typesafe/jev-1.13",
+ max_state_tokens=24_000,
+ simple_threshold=0.8,
+ competence_floor=0.5,
+ branch_criteria=case["settings"].get("branch_criteria", {}),
+ policy_configured=bool(case["settings"]),
+ )
+ prepared = prepare_decision(settings, validate_hiroute_request(case["request"]))
+ self.assertEqual(prepared.body, case["expected_upstream"])
+ result = decision_response(
+ settings, prepared.body["state"], case["upstream"], prepared.target_trimmed
+ )
+ self.assertEqual(result, case["expected_response"])
diff --git a/decision-extensions/extensions/jev-decider/tests/test_server.py b/decision-extensions/extensions/jev-decider/tests/test_server.py
index e6366d7d..4ce21e1e 100644
--- a/decision-extensions/extensions/jev-decider/tests/test_server.py
+++ b/decision-extensions/extensions/jev-decider/tests/test_server.py
@@ -12,6 +12,7 @@ from aiohttp import web
from aiohttp.test_utils import TestClient, TestServer
from jev_decider.server import Settings, create_app, criteria_hash, load_policy
+from tests.decision_cases import ASSESSMENT_QUESTION, decision_cases
BRANCHES = {
@@ -101,7 +102,7 @@ def turn(label: str, status: str = "completed") -> dict:
}
-class DeciderHttpTests(unittest.IsolatedAsyncioTestCase):
+class HttpFixture(unittest.IsolatedAsyncioTestCase):
async def asyncSetUp(self) -> None:
self.calls: list[dict] = []
self.authorization_headers: list[str | None] = []
@@ -139,9 +140,11 @@ class DeciderHttpTests(unittest.IsolatedAsyncioTestCase):
self.upstream = TestServer(upstream_app)
await self.upstream.start_server()
+
async def asyncTearDown(self) -> None:
await self.upstream.close()
+
def settings(self, mode: str = "auto", **changes: object) -> Settings:
values = dict(
mode=mode,
@@ -161,33 +164,29 @@ class DeciderHttpTests(unittest.IsolatedAsyncioTestCase):
values["policy_configured"] = True
return Settings(**values)
+
async def client(self, settings: Settings) -> TestClient:
client = TestClient(TestServer(create_app(settings)))
await client.start_server()
self.addAsyncCleanup(client.close)
return client
- async def test_auto_asks_choice_and_score_in_one_upstream_request(self) -> None:
- client = await self.client(self.settings())
- response = await client.post("/v1/decisions", json=input_body([turn("old")], 0))
- self.assertEqual(response.status, 200)
- self.assertEqual(
- await response.json(),
- {
- "branch_id": "smart_saving_simple",
- "assessment": {"score": 0.6, "partial": False},
- },
- )
- self.assertEqual(len(self.calls), 1)
- self.assertEqual(set(self.calls[0]["questions"]), {"branch", "competence"})
- self.assertEqual(self.authorization_headers, ["Bearer secret"])
- async def test_first_turn_omits_score_question_and_assessment(self) -> None:
- client = await self.client(self.settings())
- response = await client.post("/v1/decisions", json=input_body())
- self.assertEqual(response.status, 200)
- self.assertEqual(await response.json(), {"branch_id": "smart_saving_simple"})
- self.assertEqual(set(self.calls[0]["questions"]), {"branch"})
+
+class BranchSelectionTests(HttpFixture):
+ async def test_decision_contract_examples_use_one_upstream_request(self) -> None:
+ for case in decision_cases():
+ with self.subTest(capability=case["name"]):
+ self.calls.clear()
+ self.authorization_headers.clear()
+ self.answer = case["upstream"]
+ client = await self.client(self.settings(case["mode"], **case["settings"]))
+ response = await client.post("/v1/decisions", json=case["request"])
+ self.assertEqual(response.status, 200)
+ self.assertEqual(await response.json(), case["expected_response"])
+ self.assertEqual(self.calls, [case["expected_upstream"]])
+ self.assertEqual(self.authorization_headers, ["Bearer secret"])
+ await client.close()
async def test_custom_policy_replaces_state_and_choice_for_both_modes(self) -> None:
for mode, question in (("auto", "branch"), ("rules", "complexity")):
@@ -210,6 +209,7 @@ class DeciderHttpTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(event["criteria_sha256"], criteria_hash(POLICY))
self.assertNotIn(POLICY["smart_saving_simple"], " ".join(captured.output))
+
async def test_custom_policy_does_not_override_low_competence(self) -> None:
self.answer = {"answers": {
"complexity": {"type": "choice", "choice": "smart_saving_simple",
@@ -220,8 +220,8 @@ class DeciderHttpTests(unittest.IsolatedAsyncioTestCase):
response = await client.post("/v1/decisions", json=input_body([turn("previous")], 0))
self.assertEqual(response.status, 200)
self.assertEqual((await response.json())["branch_id"], "smart_saving_complex")
- from jev_decider.server import COMPETENCE_CRITERIA
- self.assertEqual(self.calls[0]["questions"]["competence"]["criteria"], COMPETENCE_CRITERIA)
+ self.assertEqual(self.calls[0]["questions"]["competence"]["criteria"], ASSESSMENT_QUESTION["criteria"])
+
async def test_custom_policy_rejects_other_branches_before_upstream(self) -> None:
client = await self.client(self.settings(branch_criteria=POLICY))
@@ -231,6 +231,7 @@ class DeciderHttpTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(response.status, 400)
self.assertEqual(len(self.calls), 0)
+
async def test_custom_policy_counts_toward_context_budget(self) -> None:
# The same input fits without an override. Added definitions, not the
# original request, must be what causes the bounded-context rejection.
@@ -244,6 +245,122 @@ class DeciderHttpTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(response.status, 413)
self.assertEqual(len(self.calls), 0)
+
+ async def test_rules_formula_boundaries_and_missing_score(self) -> None:
+ client = await self.client(self.settings("rules"))
+ cases = [
+ (0.80, None, "smart_saving_simple"),
+ (0.799, 2.0, "smart_saving_complex"),
+ (0.90, 1.0, "smart_saving_simple"),
+ (0.90, 0.999, "smart_saving_complex"),
+ (0.90, 0.0, "smart_saving_complex"),
+ ]
+ for probability, score, expected in cases:
+ with self.subTest(probability=probability, score=score):
+ answers = {
+ "complexity": {
+ "type": "choice",
+ "choice": (
+ "smart_saving_simple"
+ if probability >= 0.5
+ else "smart_saving_complex"
+ ),
+ "probabilities": {
+ "smart_saving_simple": probability,
+ "smart_saving_complex": 1 - probability,
+ },
+ }
+ }
+ if score is not None:
+ answers["competence"] = {"type": "score", "score": score}
+ self.answer = {"answers": answers}
+ response = await client.post(
+ "/v1/decisions", json=input_body([turn("previous")], 0)
+ )
+ self.assertEqual(response.status, 200)
+ self.assertEqual((await response.json())["branch_id"], expected)
+
+
+ async def test_rules_rejects_non_binary_branches_before_upstream(self) -> None:
+ body = input_body()
+ body["branches"] = {"a": "A", "b": "B", "c": "C"}
+ client = await self.client(self.settings("rules"))
+ response = await client.post("/v1/decisions", json=body)
+ self.assertEqual(response.status, 400)
+ self.assertEqual(len(self.calls), 0)
+
+
+ async def test_rules_rejects_invalid_probability_distribution(self) -> None:
+ self.answer = {
+ "answers": {
+ "complexity": {
+ "type": "choice",
+ "choice": "smart_saving_simple",
+ "probabilities": {
+ "smart_saving_simple": 0.9,
+ "smart_saving_complex": 0.9,
+ },
+ }
+ }
+ }
+ client = await self.client(self.settings("rules"))
+ response = await client.post("/v1/decisions", json=input_body())
+ self.assertEqual(response.status, 502)
+ self.assertEqual(await response.json(), {"error": "upstream_invalid"})
+ self.assertEqual(len(self.calls), 1)
+
+
+
+class HistoryAssessmentTests(HttpFixture):
+ async def test_questions_treat_repeat_summary_and_unknown_as_valid_rounds_not_feedback(self) -> None:
+ client = await self.client(self.settings())
+ for latest in ("same task", "Summary: continue the same task"):
+ body = input_body([turn("same task")], 0)
+ body["latest_user"] = [{"kind": "text", "text": latest}]
+ body["visible_conversation"][0]["status"] = "unknown"
+ response = await client.post("/v1/decisions", json=body)
+ self.assertEqual(response.status, 200)
+ self.assertEqual(len(self.calls), 2)
+ questions = self.calls[0]["questions"]
+ self.assertIn("repeat prior text", questions["branch"]["instructions"])
+ self.assertIn("unknown terminal status", questions["competence"]["instructions"])
+ self.assertIn("not by itself praise or a complaint", questions["competence"]["instructions"])
+
+
+ async def test_invalid_optional_score_is_omitted_without_second_call(self) -> None:
+ self.answer["answers"]["competence"] = {"type": "score", "score": 9}
+ client = await self.client(self.settings())
+ response = await client.post("/v1/decisions", json=input_body([turn("old")], 0))
+ self.assertEqual(await response.json(), {"branch_id": "smart_saving_simple"})
+ self.assertEqual(len(self.calls), 1)
+
+
+ async def test_trimming_removes_whole_old_turns_and_marks_target_partial(self) -> None:
+ history = [turn("old-" + "x" * 400), turn("recent")]
+ client = await self.client(self.settings(max_state_tokens=900, branch_criteria=BRANCHES))
+ response = await client.post("/v1/decisions", json=input_body(history, 0))
+ body = await response.json()
+ self.assertEqual(response.status, 200, body)
+ self.assertTrue(body["assessment"]["partial"])
+ state = self.calls[0]["state"]
+ self.assertEqual([item["user"][0]["text"] for item in state["visible_conversation"]], ["recent"])
+ self.assertEqual(state["latest_user"][0]["text"], "Fix the typo.")
+ self.assertEqual(state["assessment_from"], 0)
+
+
+ async def test_trimmed_non_target_history_marks_state_partial_not_assessment(self) -> None:
+ history = [turn("old-" + "x" * 500), turn("target")]
+ client = await self.client(self.settings(max_state_tokens=1000, branch_criteria=BRANCHES))
+ response = await client.post("/v1/decisions", json=input_body(history, 1))
+ body = await response.json()
+ self.assertEqual(response.status, 200, body)
+ self.assertFalse(body["assessment"]["partial"])
+ self.assertTrue(self.calls[0]["state"]["history_partial"])
+ self.assertEqual(self.calls[0]["state"]["assessment_from"], 0)
+
+
+
+class DecisionEvidenceTests(HttpFixture):
async def test_without_policy_uses_builtin_definitions_and_logs_hash(self) -> None:
client = await self.client(self.settings())
with self.assertLogs("jev_decider", level="INFO") as captured:
@@ -257,14 +374,6 @@ class DeciderHttpTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(event["criteria_source"], "default")
self.assertEqual(event["criteria_sha256"], criteria_hash(expected))
- async def test_generic_auto_branches_keep_request_definitions_without_override(self) -> None:
- client = await self.client(self.settings())
- body = input_body()
- body["branches"] = {**BRANCHES, "third": "Another allowed branch"}
- response = await client.post("/v1/decisions", json=body)
- self.assertEqual(response.status, 200)
- self.assertEqual(self.calls[0]["state"]["branches"], body["branches"])
- self.assertEqual(self.calls[0]["questions"]["branch"]["criteria"], body["branches"])
async def test_logs_explain_rule_override_and_correlate_response(self) -> None:
self.answer = {"answers": {
@@ -289,6 +398,7 @@ class DeciderHttpTests(unittest.IsolatedAsyncioTestCase):
self.assertNotIn("Fix the typo", " ".join(captured.output))
self.assertNotIn("secret", " ".join(captured.output))
+
async def test_logs_guard_trim_and_failures(self) -> None:
self.answer = {"answers": {
"complexity": {"type": "choice", "choice": "smart_saving_simple",
@@ -313,6 +423,7 @@ class DeciderHttpTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(result["error"], "upstream_rejected")
self.assertEqual(result["phase"], "upstream")
+
async def test_timeout_logs_terminal_event(self) -> None:
self.upstream_delay = 0.1
client = await self.client(self.settings(request_timeout_seconds=0.02))
@@ -323,6 +434,7 @@ class DeciderHttpTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(result["error"], "upstream_timeout")
self.assertEqual(result["event"], "decision_completed")
+
async def test_logged_upstream_usage_is_reported_not_exposed_in_decision(self) -> None:
self.answer["usage"] = {"input_tokens": 476, "output_tokens": 0,
"cost": 0.000019992, "private": "USAGE_PRIVATE_SENTINEL"}
@@ -338,6 +450,7 @@ class DeciderHttpTests(unittest.IsolatedAsyncioTestCase):
self.assertNotIn("USAGE_PRIVATE_SENTINEL", " ".join(captured.output))
self.assertEqual(len(self.calls), 1)
+
async def test_missing_or_invalid_usage_never_blocks_or_invents_zero_cost(self) -> None:
client = await self.client(self.settings())
cases = [(None, None), ([], None), ("raw-usage", None), ({}, None),
@@ -359,6 +472,7 @@ class DeciderHttpTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(result["upstream_usage"], expected)
self.assertEqual(len(self.calls), len(cases))
+
async def test_paid_usage_is_retained_when_the_upstream_choice_is_invalid(self) -> None:
self.answer = {"answers": {}, "usage": {"input_tokens": 120, "cost": 0.00000504}}
client = await self.client(self.settings())
@@ -370,6 +484,9 @@ class DeciderHttpTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(result["upstream_usage"], {"input_tokens": 120, "cost": 0.00000504})
self.assertEqual(len(self.calls), 1)
+
+
+class ServiceBoundaryTests(HttpFixture):
async def test_openapi_route_is_served_without_legacy_aliases(self) -> None:
document = json.loads(
(Path(__file__).resolve().parents[3] / "api/decision.openapi.json").read_text()
@@ -385,19 +502,6 @@ class DeciderHttpTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(await response.json(), {"branch_id": "smart_saving_simple"})
self.assertEqual(len(self.calls), 1)
- async def test_questions_treat_repeat_summary_and_unknown_as_valid_rounds_not_feedback(self) -> None:
- client = await self.client(self.settings())
- for latest in ("same task", "Summary: continue the same task"):
- body = input_body([turn("same task")], 0)
- body["latest_user"] = [{"kind": "text", "text": latest}]
- body["visible_conversation"][0]["status"] = "unknown"
- response = await client.post("/v1/decisions", json=body)
- self.assertEqual(response.status, 200)
- self.assertEqual(len(self.calls), 2)
- questions = self.calls[0]["questions"]
- self.assertIn("repeat prior text", questions["branch"]["instructions"])
- self.assertIn("unknown terminal status", questions["competence"]["instructions"])
- self.assertIn("not by itself praise or a complaint", questions["competence"]["instructions"])
async def test_latest_user_remains_required_and_non_empty(self) -> None:
client = await self.client(self.settings())
@@ -412,6 +516,7 @@ class DeciderHttpTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(response.status, 400)
self.assertEqual(self.calls, [])
+
async def test_outbound_client_honors_standard_proxy_environment(self) -> None:
proxy_calls: list[str] = []
@@ -443,45 +548,6 @@ class DeciderHttpTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(len(proxy_calls), 1)
self.assertEqual(self.calls, [])
- async def test_rules_uses_complexity_for_opportunity_and_score_only_as_guard(self) -> None:
- self.answer = {
- "answers": {
- "complexity": {
- "type": "choice",
- "choice": "smart_saving_simple",
- "probabilities": {
- "smart_saving_simple": 0.95,
- "smart_saving_complex": 0.05,
- },
- },
- "competence": {"type": "score", "score": 0.2},
- }
- }
- client = await self.client(self.settings("rules"))
- response = await client.post("/v1/decisions", json=input_body([turn("old")], 0))
- body = await response.json()
- self.assertEqual(body["branch_id"], "smart_saving_complex")
- self.assertEqual(body["assessment"]["score"], 0.1)
- self.assertEqual(len(self.calls), 1)
-
- async def test_invalid_optional_score_is_omitted_without_second_call(self) -> None:
- self.answer["answers"]["competence"] = {"type": "score", "score": 9}
- client = await self.client(self.settings())
- response = await client.post("/v1/decisions", json=input_body([turn("old")], 0))
- self.assertEqual(await response.json(), {"branch_id": "smart_saving_simple"})
- self.assertEqual(len(self.calls), 1)
-
- async def test_trimming_removes_whole_old_turns_and_marks_target_partial(self) -> None:
- history = [turn("old-" + "x" * 400), turn("recent")]
- client = await self.client(self.settings(max_state_tokens=900, branch_criteria=BRANCHES))
- response = await client.post("/v1/decisions", json=input_body(history, 0))
- body = await response.json()
- self.assertEqual(response.status, 200, body)
- self.assertTrue(body["assessment"]["partial"])
- state = self.calls[0]["state"]
- self.assertEqual([item["user"][0]["text"] for item in state["visible_conversation"]], ["recent"])
- self.assertEqual(state["latest_user"][0]["text"], "Fix the typo.")
- self.assertEqual(state["assessment_from"], 0)
async def test_required_choice_failure_is_sanitized_and_not_retried(self) -> None:
self.answer = {"answers": {"branch": {"type": "choice", "choice": "other", "probabilities": {"other": 1.0}}}}
@@ -491,6 +557,7 @@ class DeciderHttpTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(await response.json(), {"error": "upstream_invalid"})
self.assertEqual(len(self.calls), 1)
+
async def test_upstream_rejections_are_sanitized_and_not_retried(self) -> None:
client = await self.client(self.settings())
for status in (401, 402, 429):
@@ -504,6 +571,7 @@ class DeciderHttpTests(unittest.IsolatedAsyncioTestCase):
)
self.assertEqual(len(self.calls), 3)
+
async def test_slow_upstream_consumes_single_request_budget_without_retry(self) -> None:
self.upstream_delay = 0.10
client = await self.client(self.settings(request_timeout_seconds=0.02))
@@ -512,6 +580,7 @@ class DeciderHttpTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(await response.json(), {"error": "upstream_timeout"})
self.assertEqual(len(self.calls), 1)
+
async def test_oversized_upstream_response_is_rejected(self) -> None:
self.upstream_body = json.dumps({"padding": "x" * (64 * 1024)}).encode()
client = await self.client(self.settings())
@@ -520,6 +589,7 @@ class DeciderHttpTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(await response.json(), {"error": "upstream_invalid"})
self.assertEqual(len(self.calls), 1)
+
async def test_fixed_state_over_budget_returns_413_without_upstream_call(self) -> None:
body = input_body()
body["latest_user"] = [{"kind": "text", "text": "x" * 500}]
@@ -528,6 +598,7 @@ class DeciderHttpTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(response.status, 413)
self.assertEqual(len(self.calls), 0)
+
async def test_concurrency_limit_bounds_simultaneous_upstream_calls(self) -> None:
self.upstream_delay = 0.05
client = await self.client(self.settings(max_concurrency=1))
@@ -539,6 +610,7 @@ class DeciderHttpTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(self.max_active_upstream, 1)
self.assertEqual(len(self.calls), 2)
+
async def test_optional_inbound_header_and_strict_request(self) -> None:
client = await self.client(self.settings(inbound_header_name="X-Decision-Key", inbound_header_value="value"))
denied = await client.post("/v1/decisions", json=input_body())
@@ -551,6 +623,7 @@ class DeciderHttpTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(invalid.status, 400)
self.assertEqual(len(self.calls), 0)
+
async def test_health_does_not_call_upstream(self) -> None:
client = await self.client(self.settings())
response = await client.get("/health")
@@ -558,76 +631,6 @@ class DeciderHttpTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(await response.json(), {"status": "ok"})
self.assertEqual(self.calls, [])
- async def test_trimmed_non_target_history_marks_state_partial_not_assessment(self) -> None:
- history = [turn("old-" + "x" * 500), turn("target")]
- client = await self.client(self.settings(max_state_tokens=1000, branch_criteria=BRANCHES))
- response = await client.post("/v1/decisions", json=input_body(history, 1))
- body = await response.json()
- self.assertEqual(response.status, 200, body)
- self.assertFalse(body["assessment"]["partial"])
- self.assertTrue(self.calls[0]["state"]["history_partial"])
- self.assertEqual(self.calls[0]["state"]["assessment_from"], 0)
-
- async def test_rules_formula_boundaries_and_missing_score(self) -> None:
- client = await self.client(self.settings("rules"))
- cases = [
- (0.80, None, "smart_saving_simple"),
- (0.799, 2.0, "smart_saving_complex"),
- (0.90, 1.0, "smart_saving_simple"),
- (0.90, 0.999, "smart_saving_complex"),
- (0.90, 0.0, "smart_saving_complex"),
- ]
- for probability, score, expected in cases:
- with self.subTest(probability=probability, score=score):
- answers = {
- "complexity": {
- "type": "choice",
- "choice": (
- "smart_saving_simple"
- if probability >= 0.5
- else "smart_saving_complex"
- ),
- "probabilities": {
- "smart_saving_simple": probability,
- "smart_saving_complex": 1 - probability,
- },
- }
- }
- if score is not None:
- answers["competence"] = {"type": "score", "score": score}
- self.answer = {"answers": answers}
- response = await client.post(
- "/v1/decisions", json=input_body([turn("previous")], 0)
- )
- self.assertEqual(response.status, 200)
- self.assertEqual((await response.json())["branch_id"], expected)
-
- async def test_rules_rejects_non_binary_branches_before_upstream(self) -> None:
- body = input_body()
- body["branches"] = {"a": "A", "b": "B", "c": "C"}
- client = await self.client(self.settings("rules"))
- response = await client.post("/v1/decisions", json=body)
- self.assertEqual(response.status, 400)
- self.assertEqual(len(self.calls), 0)
-
- async def test_rules_rejects_invalid_probability_distribution(self) -> None:
- self.answer = {
- "answers": {
- "complexity": {
- "type": "choice",
- "choice": "smart_saving_simple",
- "probabilities": {
- "smart_saving_simple": 0.9,
- "smart_saving_complex": 0.9,
- },
- }
- }
- }
- client = await self.client(self.settings("rules"))
- response = await client.post("/v1/decisions", json=input_body())
- self.assertEqual(response.status, 502)
- self.assertEqual(await response.json(), {"error": "upstream_invalid"})
- self.assertEqual(len(self.calls), 1)
if __name__ == "__main__":
diff --git a/docs/code-map/README.md b/docs/code-map/README.md
new file mode 100644
index 00000000..6b86c049
--- /dev/null
+++ b/docs/code-map/README.md
@@ -0,0 +1,30 @@
+# Code map
+
+Start with a user capability and one representative test, then follow the
+production owner. This map describes the current implementation and its executable
+contracts; it is navigation, not a second requirements system. Update it when
+ownership or entry points change.
+
+| User capability | Contract area | Production owners | Representative tests / local guide |
+| --- | --- | --- | --- |
+| Add model sources and inspect usable models | Model connections | [Application](../../crates/application/src/compute_management), [native integrations](../../crates/integrations/src/model_connections), [daemon assembly](../../crates/daemon/src/control/runtime/model_connections.rs) | [Typed/fixture contracts](../../tools/product-e2e/tests/compute_pool.rs); [installed CLI journey](../../crates/daemon/tests/publication_process.rs) |
+| Create and publish a routing plan | Routing plans | [Authoring and lifecycle](../../crates/application/src/routing), [compiler](../../crates/application/src/compiler), [domain types](../../crates/domain/src/routing) | [Compiler/fixture contracts](../../tools/product-e2e/tests/routing_plans.rs); [installed CLI journey](../../crates/daemon/tests/publication_process.rs) |
+| Connect, edit and safely disable an Agent | Agent connections | [Application transaction](../../crates/application/src/agent_connection), [filesystem adapters](../../crates/integrations/src/agents), [Desktop feature](../../apps/desktop/src/features/agents/README.md) | [Settings ordering](../../crates/application/src/operations/tests/settings_tail.rs), [daemon product entry](../../crates/daemon/src/control/runtime/settings_profile_tests.rs) |
+| Select saved additional Qoder model routes while keeping task collaboration independent | Agent connections | [Shared settings transaction](../../crates/application/src/agent_connection/settings), [native provider ownership](../../crates/integrations/src/agents/qoder_native/README.md), [Desktop model editor](../../apps/desktop/src/features/agents/QoderModelEditor.tsx) | [Ordinary native startup journey](../../crates/daemon/tests/support/qoder_model_product.py), [five Qoder journeys and evidence limits](../../tools/product-e2e/tests/QODER_DELEGATION.md) |
+| Route a model request and apply bounded fallback | Request routing | [Gateway map](../../crates/gateway/README.md), [execution core](../../crates/gateway-core/src) | [Real listener scenarios](../../tools/e2e-harness/tests/p0_gateway_runtime.rs) |
+| Ask an external service to select a branch | [Decision API](../../decision-extensions/api/README.md) | [Gateway classification](../../crates/gateway/src/core_runtime/classification.rs), [Jev reference service](../../decision-extensions/extensions/jev-decider/README.md) | [Jev tests](../../decision-extensions/extensions/jev-decider), real listener classifier scenarios above |
+| Delegate, read and continue Worker tasks | Agent delegation | [Application authorization](../../crates/application/src/delegation), [daemon execution](../../crates/daemon/src/delegation), [OS launcher](../../crates/daemon/src/delegation/local_worker/README.md) | [Worker lifecycle](../../tools/product-e2e/tests/worker_delegation.rs), [read/continue](../../tools/product-e2e/tests/worker_read.rs) |
+| Inspect sessions, content, cost and quality | Session history, usage | [Authorized queries](../../crates/application/src/observation_query), [observation](../../crates/observation/src), [managed content](../../crates/observation/src/managed_text/README.md) | [Fixture contracts](../../tools/product-e2e/tests/local_observation.rs); [installed CLI journey](../../crates/daemon/tests/publication_process.rs) |
+| Manage the local service through CLI or Desktop | Shared access | [client-core](../../crates/client-core/src), [CLI](../../crates/cli/src), [Desktop host](../../apps/desktop/src-tauri/src), [control socket](../../crates/daemon/src/control) | [Real process journey](../../tools/product-e2e/tests/control_shell.rs), [Desktop test map](../../apps/desktop/tests/README.md) |
+
+Read [architecture and ownership](architecture.md) for cross-module changes,
+[tests as product documentation](testing.md) before changing coverage, and
+[remaining cleanup work](maintenance.md) before starting another refactor.
+For later decision features, read the [provider and consumer boundaries](decision-foundation.md).
+Before extending Worker ecosystems, read the [native context, route and history owners](worker-context.md).
+
+For an Agent implementation task, first identify the capability, its state owner,
+and the failing or representative scenario. Give parallel contributors disjoint
+file ownership; reserve shared contracts, manifests and generated registries for
+one convergence owner. Prefer extracting a cohesive responsibility beside its
+consumers over moving unrelated code into a global utility directory.
diff --git a/docs/code-map/architecture.md b/docs/code-map/architecture.md
new file mode 100644
index 00000000..e942b265
--- /dev/null
+++ b/docs/code-map/architecture.md
@@ -0,0 +1,98 @@
+# Architecture and ownership
+
+[Code map](README.md) · [Test map](testing.md)
+
+## Control and execution paths
+
+The CLI and Desktop share `client-core`; the Desktop host projects safe DTOs to
+the WebView. Requests enter the daemon's control service and the Application
+workflows. Application owns business planning and authorization through ports;
+the daemon assembles concrete adapters. `domain` owns typed business invariants,
+`application-api` owns control DTOs, `local-storage` owns durable state, and
+`integrations` owns effects against external Agent configurations and services.
+
+This is an ownership map, not a claim that every existing dependency is clean.
+`LocalControlAdapter` still assembles many responsibilities. Follow its focused
+runtime modules before extending the central facade; do not start a broad facade
+rewrite as a prerequisite for a local feature.
+
+Published plans and grants feed the Gateway. Protocol adapters normalize ingress;
+planning and classification select from the admitted publication; `gateway-core`
+owns provider-neutral execution, attempt and output budgets; the runtime driver
+resolves and contacts upstreams. Preserve authentication, pinned publication,
+source cancellation and total deadlines across a decision call. A model's branch
+choice is untrusted input and must pass the allowed-branch check before execution.
+
+Observation contains business evidence, managed content, queries and valuation.
+It is not all optional telemetry: AgentTurn output capture and Worker continuation
+use it. `query_v2/relation.rs` also maintains relations; the directory name does
+not imply a read-only boundary. Diagnostic logging is a separate concern and must
+not determine business success.
+
+## State and lifecycle rules to preserve
+
+| Boundary | Authority / invariant | Read next |
+| --- | --- | --- |
+| Agent configuration | Configure/Edit publishes service state and a receipt before the file tail. Ordinary Disable conditionally restores files before withdrawing service/grants. A conflict preserves the user file and original grant; repair requires a fresh preview/operation. | [Settings transaction](../../crates/application/src/agent_connection/settings/transaction.rs), [ordering tests](../../crates/application/src/operations/tests/settings_tail.rs) |
+| Native target registration | Enumerating an unused Agent target is not access authority or a global startup dependency. Actual access, durable markers and accepted-operation recovery retain strict path and permission checks. | [Artifact store](../../crates/local-storage/src/control/mod.rs), [permission boundaries](../../crates/local-storage/src/agents/native_registration_tests.rs), [real startup entry](../../crates/daemon/tests/publication_process.rs) |
+| Historical Agent revoke tails | Already sealed service-first revoke tails have a separate recovery reader. Do not unify this path with ordinary Disable by treating their ordering as interchangeable. | [Legacy recovery tests](../../crates/daemon/src/control/runtime/settings_profile_legacy_tests.rs), [compatibility registry](../../contracts/compatibility-support.v1.json) |
+| Committed Operation journal | The domain checkpoint and stored journal must agree in one database snapshot before publication or a native effect. Preserve immutable Plan bytes and generation/identity guards. Historical mutable JSON objects may differ only in member order; content changes must still fail. | [Domain checkpoint](../../crates/domain/src/operation/journal.rs), [storage verification](../../crates/local-storage/src/control/journal.rs), [Plan publication consumer](../../crates/local-storage/src/control/plans/publication.rs), [Skill activation consumer](../../crates/daemon/src/control/runtime/effects/tests/skill_activation.rs), [transaction guards](../../crates/local-storage/src/control/transaction_v2_tests.rs), [original upgrade fixtures](../../crates/local-storage/src/migrations/fixtures/README.md) |
+| Fresh profile deletion | Untouched proof binds the current store instance and exact marker. A stage directory alone is not proof that deletion never started; unknown state after reopen fails closed. | [Profile lifecycle tests](../../crates/daemon/src/control/runtime/settings_profile_tests.rs) |
+| Worker lifecycle | Result completion, OS process stop, body availability and permission to Continue are separate facts. Finalization and cleanup require the exact ownership lease/root identity. | [Finalization](../../crates/daemon/src/delegation/finalization.rs), [launcher](../../crates/daemon/src/delegation/local_worker/README.md) |
+| Managed content | Every read checks current authorization and visibility. Hidden/deleted/expired content cannot be restored by cached references; native cleanup is acknowledged only after success. | [Managed-text contract](../../crates/observation/src/managed_text/README.md) |
+| Storage and compatibility | Current producers have one ingestion contract. Frozen historical fixtures do not imply production upgrade support. | [Startup format admission](../../crates/local-storage/src/migrations/startup_format.rs), [compatibility registry](../../contracts/compatibility-support.v1.json) |
+
+## Extension boundaries
+
+**Agent ecosystems.** Treat discovery, reading configuration, importing model
+sources, configuring a connection, restoring owned changes, launching a client
+and running a Worker as separate capabilities. Recognizing an installation does
+not authorize writes or imply Worker support. Start a new ecosystem in its native
+adapter and the [Agent feature](../../apps/desktop/src/features/agents/README.md);
+reuse the existing Application transaction and confirmation contracts. Verify
+real configuration precedence and restoration semantics before generalizing.
+
+Qoder illustrates why these capabilities stay separate. Its main-Agent selection
+adds explicit Plan routes without importing native models or taking over the
+native default. Its collaboration Skill remains independent, and Worker routing
+uses transient frozen-task overrides rather than the persistent model provider.
+The [shared selection](../../crates/domain/src/agents/settings.rs) defines user
+intent; the [native budget policy](../../crates/domain/src/agents/qoder_model.rs)
+is shared by persistent models and Workers. Do not duplicate that policy in a
+renderer or turn a successful Skill check into model verification. Native live
+checks must bind the original client session to the Gateway's receipt authority.
+The [Gateway compiler boundary](../../crates/gateway/src/publication/trust.rs)
+derives expected execution trust from the same verified compilation as request
+authorization. A Plan projection's digest is not the executable alias digest;
+do not reconstruct that identity in an Agent adapter or relax receipt equality.
+Its persistent provider's fixed bearer header uses an explicit local model-grant
+entry; ordinary Responses and transient Worker authority keep their existing
+authentication channels. See [Gateway ingress authentication](../../crates/gateway/src/core_runtime/inbound_auth_tests.rs)
+and [real listener authority](../../tools/e2e-harness/tests/p0_gateway_request_authority.rs)
+before changing a native provider's endpoint.
+The [native provider guide](../../crates/integrations/src/agents/qoder_native/README.md)
+maps JSONC ownership, protected credential delivery and conditional restoration;
+the [persisted-model journey](../../crates/daemon/tests/support/qoder_model_product.py)
+documents the normal startup path independently of Worker overrides.
+The guide also maps backend facts, protected file execution, retry and Live checks.
+Installed native budgets constrain both admission and Install of later Plan updates;
+a parked native file tail keeps the original Operation's Control ownership until
+its exact retry succeeds. Keep these guards with the shared transaction rather
+than treating native configuration as an independent file write.
+
+**Decisions.** The external Decision API can return an allowed branch ID, but the
+current product authoring, materialization and execution policies still contain
+binary smart-saving assumptions. See the [Gateway map](../../crates/gateway/README.md)
+for those locations. Jev currently remains an external reference service. Its
+pure request preparation, scoring and validation can be studied independently of
+its HTTP server; extraction does not establish an in-process runtime or a new
+provider protocol.
+
+Built-in Jev, configurable System One providers, natural-language custom branches
+and tool-set selection are separate future feature work. The
+[decision foundation](decision-foundation.md) records verified provider differences,
+consumer ownership and the tool-selection exploration. Define
+default branch, overlap, no-match, failure and re-selection behavior before
+changing the authoring/publication contract. Preserve selected versus executed
+branch attribution and ownership of the previous stage's assessment. Do not add
+a rules DSL or a generic plugin SDK in anticipation of these tasks.
diff --git a/docs/code-map/decision-foundation.md b/docs/code-map/decision-foundation.md
new file mode 100644
index 00000000..ab4ed8d2
--- /dev/null
+++ b/docs/code-map/decision-foundation.md
@@ -0,0 +1,96 @@
+# Foundation for decision providers and consumers
+
+[Architecture](architecture.md) · [Gateway map](../../crates/gateway/README.md)
+
+This is an engineering boundary note, researched on 2026-10-03. Built-in Jev,
+configurable System One providers, natural-language routing branches and tool-set
+selection are future features, not capabilities introduced by this cleanup.
+
+## Verified provider differences
+
+System One describes a class of structured decision models; Jev is TypeSafe's
+model. Keep the model, serving provider and decision purpose distinct. The common
+shape is a state and typed questions, rather than a chat completion. See
+[TypeSafe's concepts](https://docs.typesafe.ai/concepts/system-one).
+
+| Service | Documented evaluation endpoint and model example | Integration implication |
+| --- | --- | --- |
+| TypeSafe | `https://api.typesafe.ai/v1/systemone`, `jev-latest` | Bearer authentication; `model`, `state`, `questions`; typed answers and input/output usage. [API reference](https://docs.typesafe.ai/api) |
+| OpenRouter | `https://openrouter.ai/api/alpha/decisions`, `typesafe/jev-1.13` | Dedicated Decisions API; model IDs and cost-bearing usage belong to this provider. [Official tutorial](https://openrouter.ai/blog/tutorials/how-to-use-jev/) |
+| Alibaba Cloud Model Studio | `https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/systemone`, `decision-model-preview`; Singapore has a different regional host | Workspace and region participate in endpoint identity; the documented response includes `request_id`, `usage.input_tokens` and `latency_ms`. [API reference](https://help.aliyun.com/zh/model-studio/decision-model-api) |
+| System One hosted service | `https://system-one.dev/v1/systemone`, `jev-latest` | Its advertised request limits and credit accounting differ from token billing; hosted availability is distinct from SDK adapters. [API](https://system-one.dev/en/api), [service scope](https://system-one.dev/en/about) |
+
+The references describe Choice, Score and Noul primitives. They do not establish
+identical predictions, calibration, limits or failure semantics. The Model Studio
+API page currently gives conflicting Score limits (2–10 in parameter details,
+2–255 in its limits section); resolve that before claiming broad compatibility.
+No authenticated provider call was made for this research. Treat documentation
+examples as contract leads, not frozen live responses or latency evidence.
+
+## Responsibilities to keep separate
+
+| Responsibility | Current owner / next extension seam | Must not absorb |
+| --- | --- | --- |
+| Configuration and credentials | Existing Application/control and secret-management paths; future provider kind, endpoint and model selection | Credentials in WebView DTOs, prompts or fixture snapshots |
+| Provider transport | Current Jev service shell; future adapter owns path construction, auth, wire encoding, limits, errors and usage normalization | Smart-saving thresholds, tool retention policy, execution permission |
+| Typed evaluation | Pure input preparation and Choice/Score validation in the Jev reference implementation; future reusable evaluation contract | A mandatory model-route or HTTP-server lifecycle dependency for every consumer |
+| Model routing policy | Gateway classification plus the current smart-saving preset | Tool-set fallback or tool execution |
+| Tool-set policy | Future consumer of evaluation at existing ContextHold boundaries | A second session state machine or a new permission system |
+| Effect admission and execution | Gateway planning/runtime and existing client permissions | Authority granted merely because a model returned a name or probability |
+
+Future provider configuration should explicitly identify protocol/adapter,
+endpoint, credential reference and model. Do not overload the business model pool
+or copy a provider switch into each decision consumer. Preserve missing usage as
+unknown rather than zero; preserve provider identity and resolved model in
+evidence. Capabilities and limits should come from the verified provider contract.
+These are design inputs, not new DTOs or a plugin framework in this batch.
+
+Existing Jev smart-saving questions and threshold behavior remain a named policy.
+Extracting pure logic does not make that policy appropriate for every use case.
+A model-route answer selects one allowed branch; tool filtering may retain several
+capability groups. Do not force a tool set into a single route's result type.
+
+The current five-field HiRoute `/v1/decisions` contract is specifically a branch
+decision envelope. It is distinct from the provider's `state/questions` protocol.
+Keep that public envelope stable during cleanup; future tool selection needs its
+own purpose-specific input and result validation over a shared evaluation seam.
+Do not smuggle tool catalogs into branch descriptions or expose raw system prompts,
+credentials and tool arguments by treating every internal context as model state.
+
+## Tool selection context
+
+Future tool selection needs the following engineering constraints established
+before implementation:
+
+- Reuse allowed ContextHold decision boundaries; keep the selected tool set stable
+ during the execution segment. Inspect [ContextHold](../../crates/gateway/src/context_hold)
+ and [classification](../../crates/gateway/src/core_runtime/classification.rs).
+- Select only from tools currently declared by the client, preferably using
+ namespace/capability summaries. Filter definitions without deleting historical
+ calls/results or rewriting their IDs. Existing protocol adapters remain owners
+ of valid wire projection.
+- Uncertain, failed or invalid selection retains the original tool set. This is
+ a tool-selection policy, not the model-routing fallback policy.
+- Resolve explicit `tool_choice`, delayed discovery, changing catalogs, retries,
+ model switches and restart reuse before implementation. A hidden capability
+ cannot be assumed discoverable by the model later.
+- Selection does not expand authorization or execute tools. Do not introduce a
+ new persistence or plugin system merely to cache a selection.
+
+A token reduction alone does not demonstrate task success. Keep stochastic
+quality evidence separate from deterministic protocol and ownership regressions.
+
+## Durable tests for the future feature tasks
+
+| Suite | Stable product assertion |
+| --- | --- |
+| Provider contract fixtures | Same question intent can be encoded for each supported provider; normalize answers, errors and usage without fabricating missing fields; reject malformed and foreign options |
+| Routing policy | Allowed branch selection, thresholds, fallback, deadline/cancel behavior and previous-stage assessment attribution remain intact |
+| Tool selection policy | Retained set is a subset of the current catalog; mandatory/explicitly selected tools and protocol constraints are honored; invalid/failed decisions preserve the original set |
+| Continuation and projection | Selection remains stable inside ContextHold; allowed boundaries re-evaluate; history, tool IDs and results remain unchanged through the real listener |
+| Live quality evaluation | Paired repeated tasks with fixed model/Agent/tool versions; compare completion, missed tools, total latency/cost and cache effects, including decision overhead |
+
+Keep deterministic contract tests separate from stochastic model evaluation. First
+validate tool selection independently of model routing, then measure their
+combination. Future tasks should define outcomes and independent expected values
+before adding new provider adapters or decision consumers.
diff --git a/docs/code-map/maintenance.md b/docs/code-map/maintenance.md
new file mode 100644
index 00000000..3ba0d847
--- /dev/null
+++ b/docs/code-map/maintenance.md
@@ -0,0 +1,37 @@
+# Engineering cleanup ledger
+
+[Code map](README.md)
+
+This ledger records responsibility and test concerns; it does not authorize a
+broad rewrite. Test churn alone does not establish redundancy or code decay.
+
+## Review causes, not counts
+
+- Build current-state fixtures through the current producer and deserialize them
+ through real consumers. Keep one legal setup per boundary; see the
+ [testing guide](testing.md).
+- Keep historical fixtures only for supported recovery contracts. The
+ [compatibility registry](../../contracts/compatibility-support.v1.json) records
+ their owner, reason and removal condition.
+- Preserve assessment attribution, history restoration, authorization and cleanup
+ regressions even when implementation changes require updating their fixtures.
+ A stable product assertion matters more than a stable test line count.
+
+## First batch and remaining work
+
+| Area | First foundation batch | Next bounded step / exit criterion |
+| --- | --- | --- |
+| Agent UI ownership | Group current ecosystem forms, state and request construction under one feature; make dispatch explicit | Use the Qoder integration to assess shared boundaries before adding another adapter abstraction; preserve connect/restore scenarios |
+| Worker native context | [Native user-context reuse and skill inheritance](worker-context.md) | For each new ecosystem, verify native context and per-run overrides; preserve exact continuation, configuration non-pollution, ownership and retention |
+| Decision coupling | Separate existing Jev pure policy from HTTP hosting; give Gateway name resolution a narrow owner | [Separate provider transport from routing/tool policies](decision-foundation.md); future tasks own built-in Jev, provider configuration, natural-language branches and ContextHold tool selection |
+| False-green checks | Bind schema convergence to the authoritative production source; select required browser scenarios by stable identity | Gate tests must reject missing or changed production facts even when a fixture still contains the expected token |
+| Test discovery and layout | Add a product map; replace selected dynamic source-shape checks with behavioral coverage | Consolidate only after recording preserved unique assertions and the layer that owns each one |
+| Large control assembly | Document `LocalControlAdapter` and runtime owners | Extract one cohesive port/consumer during a real feature; avoid a facade-wide rewrite |
+| Worker and observation | Correct stale local ownership docs | Review embedded fixtures, shared process harnesses and constant-only assertions independently; preserve lease, cleanup and content-visibility fault cases |
+| Recovery and compatibility | Document current Configure/Edit, ordinary Disable and legacy-tail distinctions | Keep recent recovery code stable; change only with a concrete failing lifecycle scenario |
+
+For the next feature, compare how many responsibilities it touches, whether state
+has one owner, how much unrelated code the agent must read, and whether tests change
+because the product contract changed or because internal structure moved. Record
+examples in the feature handoff. Prefer a small concrete improvement over a new
+global score, a file-size target or another layer of generic abstractions.
diff --git a/docs/code-map/testing.md b/docs/code-map/testing.md
new file mode 100644
index 00000000..42db74e5
--- /dev/null
+++ b/docs/code-map/testing.md
@@ -0,0 +1,189 @@
+# Tests as product documentation
+
+[Code map](README.md) · [Desktop scenarios](../../apps/desktop/tests/README.md)
+
+Organize navigation around user capabilities; keep tests physically beside the
+layer that can exercise each invariant precisely. Product-oriented does not mean
+turning every test into a slow UI journey. A small deterministic test of restoring
+a user file after a conflict documents a product promise better than a repeated
+happy-path end-to-end test.
+
+## What each layer proves
+
+| Layer | Appropriate assertion | Evidence limit |
+| --- | --- | --- |
+| Pure state / policy | User intent produces the right request; admitted branches, thresholds and scores behave as specified | Does not prove dispatch or a running service |
+| Component with filesystem / database / controlled service | Conflict, rollback, ownership, authorization, timeout and recovery at a real boundary | Does not prove all production wiring |
+| Desktop React + mock IPC | Visible controls, edits, pending/error feedback and commands sent by a user journey | Does not prove Tauri, daemon effects or native clipboard |
+| Desktop [native command authority check](../../apps/desktop/tests/ui-consistency.test.mjs) | Registered bundled commands, generated ACL entries and explicit main-window permissions agree | Does not prove an actual WebView invocation; compilation and mock IPC alone can miss a denied command |
+| Desktop Rust consumer compilation with `desktop-pilot --all-targets` through the managed Mac configuration | Shared contract changes compile through the Tauri bridge, protected Session and test consumers; Pilot includes `desktop-runtime` and supplies the configured ACL manifest | Does not execute tests or prove native behavior; featureless checks omit the bridge |
+| Real CLI/daemon or Gateway listener with controlled upstream | Production composition, published plans, actual upstream attempts and durable effects | Does not prove a live model's quality or every OS |
+| Native Desktop / real Agent harness / live provider | The selected real integration path | Environment-specific; record platform and revision |
+| Frozen compatibility or expected-red fixture | A historical reader/rejection rule, or an intentionally incomplete composition | Not evidence of current product completion |
+
+The shared [publication fixture's `Product.cli`](../../crates/daemon/tests/support/publication_product.py)
+is command notation for internal Local Control preparation, not the standalone CLI.
+Its protected-input/grant channel belongs to the daemon that the fixture starts;
+it cannot be attached to an already running Desktop. Prepare sources before handing
+that instance to Desktop, then perform protected user mutations through the real UI.
+Native main-Agent delegation separately invokes the actual public Worker CLI.
+
+Start from the representative cases in the [capability map](README.md). In
+`tools/product-e2e`, inspect the declared proof level: `transaction_recovery.rs`
+includes expected-red composition, `gateway_adapter_contract.rs` is component
+coverage, and `product_oracle.rs` tests the oracle itself. A file named `product`
+or a zero exit status alone is not acceptance evidence. Likewise, a test that
+reads `green` from a scenario/golden file validates the recorded contract, not
+that the journey ran. Compute, routing and observation fixture checks link to
+the real `installed_standalone_cli_completes_the_headless_management_loop` in
+[publication_process.rs](../../crates/daemon/tests/publication_process.rs); keep
+those evidence levels distinct.
+
+## Keep useful assertions, reduce accidental coupling
+
+Name a scenario by the user's initial state, action and observable result. Arrange
+current state through the current producer or a legal fixture builder; keep the
+expected outcome independent of that builder. Freeze legacy bytes separately and
+register their owner and removal condition in the compatibility registry.
+For durable JSON, pair independent historical producer bytes with recovery through
+the current production consumer. Preserve the failing package/feature selection:
+package-level and workspace-level `--all-features` can resolve different dependency
+features, including JSON object ordering. A current-serializer golden cannot prove
+that an older committed journal remains recoverable.
+
+Generic discovery and CLI journeys should require the capabilities they exercise
+and unique identities, rather than freeze the total number of registered Agents.
+Keep exact inventory completeness checks at the registry/catalog boundary. Adding
+an ecosystem should extend its own product assertions without forcing unrelated
+process, privacy or configuration journeys to change their expected list length.
+For Agent settings, start from the shared enable/adjust/disable and blocked-action
+recovery journeys in the [feature guide](../../apps/desktop/src/features/agents/README.md).
+Compare an added ecosystem's interactions with existing ones before turning a new
+button or status label into an expected result. Assert saved intent, independent
+facets and recoverable failures; retain UI detail assertions only where the
+durable product contract requires that detail.
+
+A saved integration must be tested through normal startup reading that saved
+configuration. A fixture that injects an endpoint, provider, credential or settings
+override can prove a transient launch path but cannot prove persistent connection
+setup. Keep configuration writers on an explicitly selected acceptance context;
+borrowed daily login for a read-only Worker journey is not authority to write its
+model providers. Reuse the same production control and upstream oracle, with a
+small native launch leaf for each distinct startup contract.
+
+For a new ecosystem, reuse [Agent product support](../../crates/daemon/tests/support/agent_product_support.py)
+for product settings Preview → Apply → current-status reads and bounded native CLI
+execution with private output capture. Keep native argv, configuration ownership,
+terminal-result parsing and independent business assertions in the ecosystem leaf.
+The process helper proves neither a model request nor a successful task by itself.
+[NativeContextUpstream](../../crates/daemon/tests/support/native_context_fixture.py)
+owns the Responses/Messages transport and counts every model POST attempt, including
+rejected credentials, endpoints and models. Zero-request assertions use this count
+(zero for an unused source, or no increase across an operation); an empty event
+ledger cannot detect requests rejected before recording. Keep the ledger for
+positive route/history assertions. New journeys should not replace the HTTP handler
+to add observation, and regressions must prove the business assertion rejects a
+real rejected HTTP attempt, not just that the counter increments.
+
+Before copying a native journey, identify which shared path already owns setup,
+source routing, exact Continue, cancellation and cleanup. Add a new native leaf
+only for an actual protocol/configuration difference. Keep native-history layout
+witnesses isolated and version-specific; do not share production code that computes
+the same expected answer with its test oracle. Register a new helper's actual
+consumers in the test planner, including its cheap fault/ownership checks.
+
+A conflict fixture also needs a positive control: establish that the native client
+would consume its provider, hook or auxiliary-model setting before claiming the
+managed launch defeats that setting. Keep this expensive native proof distinct
+from exhaustive deterministic merge, drift and restore tests. Observing a process
+exit or a model's own success text never replaces the Gateway receipt and exact
+route/authorization assertions.
+
+When exercising a real store, keep its fresh storage directory separate from
+fixture executables and native workspaces. Production correctly refuses to
+initialize over unrelated files; a fixture must not weaken that guard to finish
+setup. Borrowed user context, product storage and temporary run materials also
+have different cleanup owners—represent those roots explicitly in the fixture.
+Reusing native HOME for login and Skills must not reuse HiRoute test receipts.
+Give each product instance a private `HIROUTE_WORKER_RECEIPT_DIR` and propagate it
+to public CLI subprocesses, including those launched by the main Agent. Otherwise
+an old receipt can replay a different daemon's operation for the same working
+directory and idempotency key. Keep that namespace stable within the instance for
+retry assertions, and retain the production revision/idempotency guards.
+When a native acceptance fixture needs a writable Skill target, it may create a
+new empty leaf with explicit permissions and recorded ownership; the production
+operation must still install and restore the actual Skill. Never normalize a
+pre-existing user's directories to make a test pass. Cleanup checks the recorded
+directory identity, permissions and emptiness before removing it. Separate
+private-HOME negative cases prove that unsafe targets remain rejected and cannot
+block unrelated startup merely by being registered.
+
+Before starting a native journey, locate its explicit inputs, borrowed/writable
+roots, cleanup owners and required outcomes in the acceptance entry guide; the
+[Qoder run contract](../../tools/product-e2e/tests/QODER_DELEGATION.md#run-contract)
+is one example. If preparation or cleanup fails, report that stage and retain the
+first product failure. A fixture check, successful setup or process exit cannot
+stand in for the declared business outcomes. Scope UI readiness checks to the
+current feature and expected target; a matching list on another mounted page
+does not establish that the Agent list has loaded.
+
+Prefer behavior over source layout: rendering and request assertions survive a
+component move; regexes for a local variable name do not. Keep source checks only
+for intentional static policies (for example forbidden credentials or public
+contract tokens). Select browser scenarios by stable IDs/capabilities, not array
+positions or translated display names, and require both a nonempty selection and
+completion of every required scenario.
+
+Before deleting or consolidating a test, identify its unique failure condition and
+assertion. Keep crash/reopen, cancellation, foreign-file conflict, stale preview,
+authorization, timeout and compatibility cases even when happy paths overlap.
+Two layers may intentionally protect the same promise against different failures.
+Do not replace these checks with constants, snapshots of implementation structure,
+or expected values computed by the production algorithm under test.
+
+For a behavior-preserving refactor, commit representative behavior tests before
+moving production code. For a faulty gate, demonstrate that a realistic bad case
+fails, then fix the gate. A passing synthetic test of the gate must not substitute
+for running it against the actual production source.
+
+## Select and report validation
+
+Storage upgrade recovery is a product promise, separate from native model-call
+verification. The [fixed crash-boundary scenarios](../../crates/local-storage/src/migrations/upgrade_batch_recovery_tests.rs)
+exercise missing original backups, interrupted prior batches and real intermediate
+SQL commits through daemon startup. They reuse frozen producer journals, preserve
+keys and backup ownership, and pin historical versions rather than generating an
+interruption by upgrading straight to `LATEST_SCHEMA_VERSION`. A new migration
+must review the whole accepted source-to-target chain and these restart boundaries.
+
+1. Run `python3 scripts/test-plan.py --base <exact-base>`; add `--integration` when
+ combining branches. Explain any semantic scope adjustment using changed
+ behavior and affected consumers.
+2. Follow the selected plan and [CI check definitions](../github-actions-validation.md). Use the configured backend,
+ frontend and native environments. Validate committed Rust candidates through
+ `scripts/validation.py` with the feature plan, phase and related run IDs.
+ Follow shared contracts through existing serialized fixtures and
+ [client transport tests](../../crates/client-core/tests/transport.rs), as well as
+ CLI and Desktop consumers, even when those files have no diff. Keep exact wire
+ and completeness checks (for example, every supported Worker harness); update
+ obsolete fixtures instead of weakening response validation. Run the plan's
+ `native_checks` early; enabling the correct feature and compiling existing
+ consumers catches type drift without adding per-field tests.
+3. Diagnose focused failures before retrying. Freeze the candidate after focused
+ success; complete the selected final checks once. Required cases left
+ unexecuted remain pending, not green.
+4. Record exact revision, command, selected cases, run/report location, platform,
+ outcome and evidence limits. Preserve unchanged-code evidence at its original
+ SHA. Review the slowest three measured modules once: record the measured cost,
+ smallest useful improvement and assertions to preserve, or explain deferral.
+
+Review test churn by cause, not just count: product changes, new regressions,
+fixture/schema repairs, source-layout assertions and harness repairs need
+different remedies. Line count, coverage percentage and test count are signals
+for review; none is an automatic cleanup target.
+
+When changing scenario selection, inspect every importing fixture page as well as
+the main runner. Standalone editor pages must request stable scenario IDs and
+required IDs too; positional slices can silently select different cases after
+another feature adds scenarios. Keep their retained assertions visible in the
+fixture result, even when the main suite exercises the same components.
diff --git a/docs/code-map/worker-context.md b/docs/code-map/worker-context.md
new file mode 100644
index 00000000..52ba0e9b
--- /dev/null
+++ b/docs/code-map/worker-context.md
@@ -0,0 +1,152 @@
+# Worker native context, route and history
+
+[Code map](README.md)
+
+A delegated task uses the product instance's effective native user context to find
+skills, while HiRoute controls the frozen Plan, per-run credential and permission
+policy. A task owns its HiRoute metadata; the native client owns borrowed user
+configuration and history. This page locates those responsibilities. Executable tests define the boundaries described here; validation reports must
+record their exact revision, environment and scenario outcomes.
+
+## Follow a task through its owners
+
+| Product question | Read this owner | Boundary to preserve |
+| --- | --- | --- |
+| How does Desktop confirm a Worker installation? | [React selection](../../apps/desktop/src/features/WorkerDependencies.tsx), [native preparation and confirmation](../../apps/desktop/src-tauri/src/bridge/worker_tasks.rs), [protected submission and recovery](../../apps/desktop/src-tauri/src/session/worker_dependencies.rs) | Native preparation validates the shared launch shape and canonical file metadata before freezing the selection in a window-bound, expiring, single-use confirmation. Qoder contains only a CLI; Codex/Claude retain their adapter requirements. The confirmed canonical request feeds the shared digest and revision plan; discovery is not authority. |
+| Why does a selected CLI survive restart and upgrade? | [Validated launch form](../../crates/domain/src/delegation/installation.rs), [selection storage](../../crates/local-storage/src/control/worker_dependencies.rs), [upgrade](../../crates/local-storage/src/migrations/worker_dependencies_v24.rs) | Harness chooses native ACP or adapter ACP. Preserve previous selection and Operation bytes during migration; resume interrupted upgrades only through the existing complete three-store backup coordinator. |
+| Where does an Agent learn the valid installation and Plan request shape? | [Worker schema producer](../../crates/application-api/src/generated/worker.rs), [Plan schema producer](../../crates/application-api/src/generated/plan_authoring.rs), [generator](../../crates/cli/src/bin/generate_cli_contract.rs), [published schemas](../../contracts/cli) | The Rust `generated/` directory contains producer source; `contracts/cli` contains its output. Update both request families when adding a harness. Generate twice, retain old adapter requirements and native-only forbidden fields, then run the [exact artifact gate](../../crates/cli/tests/contracts.rs). |
+| Did a Worker submission reach the daemon? | [CLI submission](../../crates/cli/src/worker.rs), [local submission receipts](../../crates/cli/src/worker/receipt.rs), [daemon task admission](../../crates/daemon/src/control/runtime/delegation_tasks.rs) | The CLI rejects a reused submission key with different selectors or intent before transport. A local receipt conflict is distinct from daemon admission. Product fixtures borrowing native HOME must still give HiRoute receipts their own directory, stable for replay within one scenario and separate between scenarios. |
+| How does a Qoder main Agent prove it can use task routing? | [Metadata discovery and checks](../../crates/integrations/src/agents/qoder_discovery.rs), [native Skill/CLI verification](../../crates/integrations/src/agents/qoder_probe.rs), [product journey](../../tools/product-e2e/tests/QODER_DELEGATION.md) | A pre-install capability check does not prove the installed user Skill; either scoped check is distinct from actual delegation. Installed-Skill evidence binds the actual user target and trusted CLI result; failed rechecks invalidate prior evidence. These backend facts do not require a separate settings-page verification step. Borrowed HOME is not an isolation claim. |
+| Which user resources does this Worker see? | [Installation](../../crates/daemon/src/delegation/installation.rs), [native context](../../crates/daemon/src/delegation/profile/native_context.rs) | New tasks use effective HOME plus explicit CODEX_HOME, CLAUDE_CONFIG_DIR or QODER_CONFIG_DIR. Pilot/service overrides are authoritative; executable location does not identify a different user's home. |
+| Which endpoint, model and credential can it use? | [Profile guide](../../crates/daemon/src/delegation/profile/README.md), [Codex](../../crates/daemon/src/delegation/profile/codex.rs), [Claude](../../crates/daemon/src/delegation/profile/claude.rs), [Qoder](../../crates/daemon/src/delegation/profile/qoder.rs) | Apply native startup/session overrides without editing shared settings. Credentials stay transient. Qoder's shared native settings renderer lives in integrations; Gateway retains the frozen Plan's upstream reasoning authority. |
+| Can the native client use the frozen Plan's context and output budget? | [Qoder Plan projection](../../crates/integrations/src/agents/qoder_budget.rs), [shared budget policy](../../crates/domain/src/agents/qoder_model.rs), [shared native renderer](../../crates/integrations/src/agents/qoder.rs), [budget contract and limits](../../crates/daemon/src/delegation/profile/README.md) | Project both context and output from the frozen Plan into native model metadata. Reject unknown or unusable budgets before launch. Gateway output capping alone cannot prove the native client's compaction reservation; preserve the small-window real-Agent journey and version-specific native control. |
+| Who admits its requests and attributes them to the right Worker? | [Run authority](../../crates/daemon/src/delegation/run_authority.rs), [Gateway admission and observation metadata](../../crates/gateway/src/dispatch/run.rs) | Profile construction alone cannot admit a request. The sealed Plan and run must agree on the typed harness, and the Gateway must accept its current observation identity while rejecting unknown values. Check both consumers when adding an ecosystem. |
+| Has the native session accepted the planned model? | [ACP model confirmation](../../crates/daemon/src/delegation/acp/model.rs) | New and restored sessions confirm the profile's exact native model ID before prompt. Qoder adds its native provider prefix only here; the Plan alias stays unchanged. Missing or ambiguous capability fails explicitly. |
+| What exactly does Continue restore? | [Native history binding](../../crates/daemon/src/delegation/profile/native_history.rs), [resume](../../crates/daemon/src/delegation/executor/resume.rs) | Bind exact context and native ID, then restore that session with a fresh run credential. Never adopt the newest file or silently create a replacement session. |
+| Who starts and stops processes? | [OS launcher guide](../../crates/daemon/src/delegation/local_worker/README.md), [execution](../../crates/daemon/src/delegation/executor.rs) | Explicit argv/env/materials and owned process groups; no native configuration parsing or inferred history deletion in the launcher. |
+| Can two Workers start against a cold Codex root? | [Startup coordination](../../crates/daemon/src/delegation/lifecycle/startup.rs), [ACP initialize receipt](../../crates/daemon/src/delegation/acp/mod.rs) | Only same-daemon, same borrowed config-root spawn/initialize is coordinated. Release before New/Load and prompt; no per-root task concurrency limit or native SQLite access. |
+| What remains after hiding or expiring content? | [Read authorization](../../crates/daemon/src/control/runtime/delegation_reads.rs), [Continue](../../crates/daemon/src/control/runtime/delegation_continue.rs), [maintenance](../../crates/daemon/src/control/runtime/delegation_maintenance.rs), [owned cleanup](../../crates/daemon/src/delegation/native_cleanup.rs) | HiRoute read/Continue authorization and physical native retention are different. Borrowed history is never a cleanup target. |
+
+## State and lifetime
+
+The private task root stores the context descriptor, exact-session binding and
+Codex alias catalog. Private run roots store temporary files and token-free
+launchers. Neither root grants ownership of the borrowed HOME/config tree.
+Continue reads the original descriptor instead of today's service environment.
+Claude requires its exact transcript to be published before successful completion;
+Codex and Qoder restoration are confirmed by the native ACP load operation,
+without scanning the user's history store.
+
+Old Codex/Claude tasks without a borrowed-context descriptor keep their existing private-root
+recovery and cleanup behavior. This one recovery reader is registered in the
+[compatibility registry](../../contracts/compatibility-support.v1.json); corruption
+or a partially missing new binding must not be interpreted as an old task.
+
+Permission policy and resource discovery are separate. Claude exposes Skill in
+the approve-all profile and reads user/project/local settings. Restricted profiles
+keep their narrower tool sets. Ambient MCP and ordinary hooks have explicit
+Claude overrides; that is not a promise that all plugins, managed hooks or Codex
+extensions are universally enabled or disabled. Native permissions run under the
+same OS account and do not make HOME a security sandbox.
+
+## Recover an unconfirmed Codex initializer
+
+A failed or cancelled initialization retains its exact process identity until
+the existing owned-stop path confirms the scope stopped without unknown residuals.
+Later starts against that root return `Busy` after acquiring the bounded startup
+gate; they do not wait indefinitely or silently retry a prompt. Other roots and
+Claude do not acquire this gate. A successful version-checked initialize releases
+it immediately, before native session creation or restoration.
+
+Retry cancellation of the original run through the existing Worker Cancel action.
+The [public handler](../../crates/daemon/src/control/runtime/delegation_tasks.rs)
+wakes cancellation even when the receipt is replayed. Once the active lifecycle
+has detached, the [dispatcher](../../crates/daemon/src/delegation/dispatcher.rs)
+calls [owned stop](../../crates/daemon/src/delegation/lifecycle.rs) for that run's
+persisted process identity. Only verified stop of that exact object clears its
+unconfirmed startup occupancy. No automatic periodic retry is promised here.
+
+If the original process binding could not be persisted, or its stop still cannot
+be verified, cancellation cannot manufacture the missing ownership evidence.
+Acknowledging residuals is not a stop receipt and does not clear this gate. A
+daemon restart discards this in-memory coordination state; it does not prove old
+processes stopped and does not remove the existing residual-cleanup obligation.
+This coordination cannot serialize another daemon or a user's independent native
+CLI, and creates no lock files in the borrowed root.
+
+## Read the tests as product documentation
+
+Start with [Worker native acceptance](../../tools/product-e2e/tests/WORKER_NATIVE_CONTEXT.md).
+The `worker_native_context` target has separate core and boundary journeys for
+Codex and Claude. [Qoder task routing](../../tools/product-e2e/tests/QODER_DELEGATION.md)
+has its own explicit-login target, including the real main-Agent user Skill →
+public CLI → Worker path; a preinstallation probe cannot substitute for that path. Its case map identifies their product assertions and the component
+contracts they do not execute; an ignored test or an unexecuted outcome is not a
+successful product check.
+
+| Behavior to understand | Representative executable evidence |
+| --- | --- |
+| Select one executable Qoder CLI without adapter placeholders; reject invalid components and preserve the exact confirmed selection | [Native installation boundary tests](../../apps/desktop/src-tauri/src/bridge/worker_dependencies_tests.rs), alongside the React `qoder.installation.single-cli` scenario in [Desktop tests](../../apps/desktop/tests/README.md). The native tests also retain window ownership, one-shot use, replacement and expiry guarantees. |
+| Enable or restore a main Agent's collaboration without configuring its models; preserve Skill ownership and report drift | [Independent collaboration facts](../../crates/daemon/src/control/runtime/settings_facts/qoder.rs), [public settings transaction scenarios](../../crates/daemon/src/control/runtime/settings_entry_qoder_tests.rs) (historically registered beneath native_model tests; these are collaboration tests) |
+| Upgrade an existing CLI selection while an operation is staged, activated or complete; replay and conditionally restore its owner | [Original producer fixture and provenance](../../crates/local-storage/src/migrations/fixtures/README.md), [production startup upgrade scenarios](../../crates/local-storage/src/migrations/worker_dependencies_v24_tests.rs) |
+| Discover and invoke user/project skills; Continue the same session after restart and replacement of the Plan's source/model | [Real installed native Worker entry](../../tools/product-e2e/tests/worker_native_context.rs), [core journey](../../crates/daemon/tests/support/native_context_product.py) |
+| Route simultaneous tasks independently in one native context; cancel one native tool while its neighbor completes; refuse Continue when its exact transcript is missing | [Boundary journey](../../crates/daemon/tests/support/native_context_boundaries.py), [boundary assertion guide](../../crates/daemon/tests/support/NATIVE_CONTEXT_BOUNDARIES.md) |
+| Keep native tool summaries and automatic compaction on the frozen route, then Continue the same compacted session | [Qoder auxiliary-route journey](../../crates/daemon/tests/support/qoder_compaction_product.py), [version-pinned evidence limits](../../tools/product-e2e/tests/QODER_DELEGATION.md) |
+| Token-free native startup, shared settings unchanged, restricted tools preserved | [Profile tests](../../crates/daemon/src/delegation/profile/tests.rs), [native context tests](../../crates/daemon/src/delegation/profile/native_context.rs) |
+| Exact history identity and borrowed/owned retention | [History contracts](../../crates/daemon/src/delegation/profile/native_history_tests.rs), [material lifetime tests](../../crates/daemon/src/delegation/profile/materials_tests.rs) |
+| Model selection must succeed before prompt | [ACP boundary](../../crates/daemon/src/delegation/acp/mod.rs) and its model/session tests |
+| Cold starts share only their initialize window; waiting respects cancel/deadline and fresh authority; exact cancellation recovery clears an uncertain initializer | [Lifecycle startup journeys](../../crates/daemon/src/delegation/lifecycle/tests/startup.rs), [identity and gate contracts](../../crates/daemon/src/delegation/lifecycle/startup/tests.rs) |
+| Revoke the exact run credential and stop owned processes through precise failure branches | [Journal contracts](../../crates/daemon/src/delegation/persistent_journal_tests.rs), [local process boundary](../../crates/daemon/tests/local_worker_platform.rs), [separate lifecycle journey](../../tools/product-e2e/tests/worker_delegation.rs) |
+| Read/Continue must reject hidden or expired task content; maintenance preserves borrowed history and neighboring task metadata | [Read/Continue journey](../../tools/product-e2e/tests/worker_read.rs), [real-store maintenance tests](../../crates/daemon/src/control/runtime/delegation_maintenance_tests.rs) |
+
+Before a real-Agent run, use the acceptance guide's
+[cheap preflight contracts](../../tools/product-e2e/tests/WORKER_NATIVE_CONTEXT.md#cheap-preflight-contracts).
+For Qoder, first read the [run contract](../../tools/product-e2e/tests/QODER_DELEGATION.md#run-contract)
+to distinguish borrowed login, fixture-owned materials and dedicated model-setting
+writes. Each has a separate cleanup owner; native HOME is not a Product temporary root.
+The [fixture checks](../../scripts/test-native-context-product.py) exercise actual
+SSE wire discriminators/order, private newly created directory ancestors and the
+selected native client's context budget. The
+[boundary oracle checks](../../scripts/test-native-context-boundaries.py) reject
+cross-routing, fabricated child completion and replacement native history.
+These checks validate the test inputs and verdicts without claiming native-client
+or Desktop behavior; keep them separate from the product assertions above.
+
+Use the [test planner](../../scripts/test-plan.py) for affected checks and explicit
+real-Agent commands. The normal Rust suite compiles ignored native targets but
+does not execute them. Linux headless and macOS Desktop use real daemon, Gateway,
+CLI/adapter and native Agent processes; a controlled upstream establishes routing
+and tool/history behavior, not live-model answer quality. Keep assertion-specific
+low-level tests when they cover ownership, credentials or cancellation more
+precisely than a broad product scenario.
+
+Changes to the shared Worker installation request or its native consumers require
+the configured macOS Desktop compile/test gate with `desktop-pilot --all-targets`
+and the same-candidate frontend directory. Use
+[validation.py](../../scripts/validation.py) to select the configured build host.
+Pilot includes `desktop-runtime`; without runtime the native bridge is excluded. Node, Vite, browser fixtures
+and Linux backend checks cannot establish that the typed Desktop consumer compiles.
+The installation unit-test filter is `bridge::worker_tasks::tests`; real Desktop
+selection and task execution remain separate Pilot acceptance evidence.
+
+## Adding an ecosystem
+
+First establish native launch form, resource/config precedence, exact restore
+semantics and history ownership. Keep client-specific behavior in the profile or
+native integration leaf; share the existing admission, lifecycle, Gateway and OS
+launcher. A native ACP executable must not be forced into a fictitious Node
+adapter shape. A client that exposes resume instead of load needs an explicit
+restore capability, not a hidden new-session fallback.
+
+Main-Agent provider scanning/Preview/Apply, Worker execution, subscription model
+discovery and calling HiRoute tools are separate capabilities. Confirm each
+through its production entry. Main-Agent settings reuse the common interaction
+owners in the [Agent feature guide](../../apps/desktop/src/features/agents/README.md);
+native protocol differences alone do not justify new user verification steps or
+status badges. Future System One/Jev providers and model/tool
+selection belong to the [decision foundations](decision-foundation.md); this
+Worker change does not implement built-in Jev.
+
+The implementation retains
+HiRoute's explicit environment and ownership contracts rather than importing an
+entire daemon environment or copying a user's configuration tree.
diff --git a/docs/contract-convergence.md b/docs/contract-convergence.md
index 8acd9dd6..cfd1ac30 100644
--- a/docs/contract-convergence.md
+++ b/docs/contract-convergence.md
@@ -26,7 +26,25 @@ families in tests remain governed by the subject path rules.
inventory entry, a multi-version production family not classified by one subject, or a registered
legacy token outside its allowed paths. This catches both producer and consumer drift without
treating arbitrary prose or third-party fixtures as production contracts. It also pins database
-schema V17 and the unversioned `control.sock` endpoint.
+schema V23 from the single production declaration
+`LATEST_SCHEMA_VERSION` in `crates/local-storage/src/migrations/mod.rs`, and retains the
+unversioned `control.sock` endpoint. The schema gate accepts exactly one plain, unattributed
+top-level constant declaration in that source. Conditional declarations (including nested
+`cfg`/`cfg_attr` expressions), module/macro bodies, comments and string literals cannot satisfy
+it. Duplicate declarations and malformed lexical input fail. Inner file attributes require an
+explicit gate review because they can condition the entire module; the checker does not evaluate
+Rust configuration expressions. Matching literals in fixtures or other files cannot satisfy the
+gate. This narrow lexical check is not a replacement for Rust compilation.
+
+The local-storage owner owns both the schema and startup support policy. The current startup
+path accepts a fresh store or the current V23 format; existing schema 22 and other unsupported
+formats fail closed, as specified in [storage upgrades](upgrade-storage-design.md) and implemented
+in `crates/local-storage/src/migrations/startup_format.rs`. The version pin is an explicit review
+gate, not a claim that this Python script executes migration or recovery semantics. A schema
+change must review the production declaration, startup policy and its Rust contract tests, then
+update `EXPECTED_DATABASE_SCHEMA_VERSION` in the checker. Do not relax the gate by adding a
+fixture literal or a second live producer. `python3 scripts/test-contract-convergence.py` checks
+the gate itself, including changed production versions masked by historical fixtures.
Desktop bridge owns `hiroute.web-confirmation/v1`, the local Tauri event between its native backend
and bundled WebView confirmation host. V1 is the only emitted and accepted version; there is no
diff --git a/scripts/check-contract-convergence.py b/scripts/check-contract-convergence.py
index 423563f4..659e6043 100755
--- a/scripts/check-contract-convergence.py
+++ b/scripts/check-contract-convergence.py
@@ -10,6 +10,11 @@ from pathlib import Path
REGISTRY_PATH = Path("contracts/compatibility-support.v1.json")
+# Storage owns the production declaration and startup support policy. A schema change
+# must deliberately update this gate after reviewing migrations/startup_format.rs and
+# docs/upgrade-storage-design.md; fixtures cannot satisfy it. This is not a migration test.
+DATABASE_SCHEMA_SOURCE = "crates/local-storage/src/migrations/mod.rs"
+EXPECTED_DATABASE_SCHEMA_VERSION = 25
VERSION_SUFFIX = re.compile(r"/v[0-9]+")
INTERNAL_CONTRACT = re.compile(r"hiroute(?:\.[a-z0-9][a-z0-9-]*)+/v[0-9]+")
VALID_MODES = {
@@ -135,6 +140,101 @@ def without_cfg_test_items(source):
return "".join(output)
+def schema_source_tokens(source):
+ """Lex only enough Rust to distinguish this gate's declaration from text.
+
+ This is not a Rust parser or a cfg evaluator. Literals stay opaque, nested
+ comments are skipped, and malformed lexical input fails closed.
+ """
+ raw_string = re.compile(r'(?:b|c)?r(#{0,255})"')
+ quoted_string = re.compile(r'(?:b|c)?"(?:\\[\s\S]|[^"\\])*"')
+ character = re.compile(r"(?:b)?'(?:\\(?:u\{[0-9a-fA-F_]+\}|x[0-9a-fA-F]{2}|[^\n])|[^'\\\n])'")
+ token = re.compile(r"[A-Za-z_]\w*|[0-9][0-9_]*|.")
+ position = 0
+ while position < len(source):
+ if source[position].isspace():
+ position += 1
+ elif source.startswith("//", position):
+ end = source.find("\n", position)
+ position = len(source) if end < 0 else end
+ elif source.startswith("/*", position):
+ depth = 1
+ position += 2
+ while depth and position < len(source):
+ if source.startswith("/*", position):
+ depth += 1
+ position += 2
+ elif source.startswith("*/", position):
+ depth -= 1
+ position += 2
+ else:
+ position += 1
+ if depth:
+ raise ValueError("unterminated block comment")
+ elif match := raw_string.match(source, position):
+ ending = '"' + match[1]
+ end = source.find(ending, match.end())
+ if end < 0:
+ raise ValueError("unterminated raw string")
+ position = end + len(ending)
+ yield "<literal>"
+ elif source.startswith(('"', 'b"', 'c"'), position):
+ match = quoted_string.match(source, position)
+ if not match:
+ raise ValueError("unterminated string")
+ position = match.end()
+ yield "<literal>"
+ elif match := character.match(source, position):
+ position = match.end()
+ yield "<literal>"
+ else:
+ match = token.match(source, position)
+ position = match.end()
+ yield match[0]
+
+
+def database_schema_declarations(source):
+ # Positive allowlist: one plain, unattributed module-level const. Do not infer
+ # production availability from arbitrary cfg/cfg_attr expressions or macros.
+ versions = []
+ item = []
+ stack = []
+ pairs = {"(": ")", "[": "]", "{": "}"}
+ declaration = re.compile(r"pub const LATEST_SCHEMA_VERSION : u32 = ([0-9][0-9_]*) ;")
+ for token in schema_source_tokens(source):
+ if not stack:
+ item.append(token)
+ if item[-2:] == ["#", "!"]:
+ raise ValueError("inner attributes require an explicit schema gate review")
+ if token in pairs:
+ stack.append(pairs[token])
+ elif token in pairs.values():
+ if not stack or stack.pop() != token:
+ raise ValueError("unbalanced delimiters")
+ if not stack and token in {";", "}"}:
+ if any(item[index:index + 2] == ["const", "LATEST_SCHEMA_VERSION"]
+ for index in range(len(item) - 1)):
+ match = declaration.fullmatch(" ".join(item))
+ versions.append(match[1] if match else None)
+ item = []
+ if stack:
+ raise ValueError("unclosed delimiter")
+ return versions
+
+
+def audit_database_schema(root):
+ try:
+ versions = database_schema_declarations(load_text(root, DATABASE_SCHEMA_SOURCE))
+ except ValueError as error:
+ return [f"database schema: {DATABASE_SCHEMA_SOURCE}: {error}"]
+ if len(versions) != 1 or versions[0] is None:
+ return [f"database schema: {DATABASE_SCHEMA_SOURCE} must contain exactly one unconditional, unattributed top-level LATEST_SCHEMA_VERSION declaration"]
+ version = int(versions[0].replace("_", ""))
+ if version != EXPECTED_DATABASE_SCHEMA_VERSION:
+ return [f"database schema: {DATABASE_SCHEMA_SOURCE} declares V{version}; current storage requires V{EXPECTED_DATABASE_SCHEMA_VERSION} (storage owner must review schema and startup support policy together)"]
+ return []
+
+
def discover_production_contracts(texts):
occurrences = {}
for path, source in texts.items():
@@ -296,8 +396,7 @@ def audit(root, registry, paths=None):
if contract in value:
errors.append(f"{path}: forbidden contract reintroduced: {contract}")
joined = "\n".join(texts.values())
- if "pub const LATEST_SCHEMA_VERSION: u32 = 17;" not in joined:
- errors.append("local database latest schema must remain V17")
+ errors.extend(audit_database_schema(root))
if "control-v1.sock" in joined:
errors.append("legacy Local Control socket name reintroduced")
return sorted(set(errors))
diff --git a/scripts/ci-shards.py b/scripts/ci-shards.py
index ae911e2a..fc4f67e3 100755
--- a/scripts/ci-shards.py
+++ b/scripts/ci-shards.py
@@ -83,9 +83,11 @@ INTEGRATION_SHARDS = {
("hiroute-product-e2e", "gateway_adapter_contract"),
("hiroute-product-e2e", "local_observation"),
("hiroute-product-e2e", "product_oracle"),
+ ("hiroute-product-e2e", "qoder_delegation"),
("hiroute-product-e2e", "routing_plans"),
("hiroute-product-e2e", "transaction_recovery"),
("hiroute-product-e2e", "worker_delegation"),
+ ("hiroute-product-e2e", "worker_native_context"),
("hiroute-product-e2e", "worker_read"),
},
"integration-smoke": {
diff --git a/scripts/desktop-pilot.py b/scripts/desktop-pilot.py
index 3a17ca30..697d1e8d 100755
--- a/scripts/desktop-pilot.py
+++ b/scripts/desktop-pilot.py
@@ -106,7 +106,21 @@ def launch_environment(
HIROUTE_DESKTOP_TEST_ROOT=str(data),
)
if process_home is not None:
+ # The explicit synthetic context must not authenticate through a caller's
+ # inherited provider variables. Leave ordinary non-isolated launches alone.
+ for key in list(environment):
+ if key.startswith(("OPENAI_", "ANTHROPIC_", "AZURE_", "AWS_", "GOOGLE_", "VERTEX_", "QODER_")) or key in (
+ "CODEX_CONFIG", "CODEX_API_KEY", "CLAUDE_CODE_OAUTH_TOKEN", "GEMINI_API_KEY",
+ "OPENROUTER_API_KEY", "HIROUTE_RUN_TOKEN", "CLAUDE_CODE_USE_BEDROCK",
+ "CLAUDE_CODE_USE_VERTEX", "CLAUDE_CODE_USE_FOUNDRY",
+ ):
+ environment.pop(key)
environment["HOME"] = str(process_home)
+ # Workers borrow the product instance's native context. An isolated HOME must
+ # not retain native config locators pointing into the caller's daily account.
+ environment["CODEX_HOME"] = str(process_home / ".codex")
+ environment["CLAUDE_CONFIG_DIR"] = str(process_home / ".claude")
+ environment["QODER_CONFIG_DIR"] = str(process_home / ".qoder")
if diagnostic_override is not None:
environment[DIAGNOSTIC_LEVEL_ENV] = diagnostic_override
return environment
@@ -617,23 +631,43 @@ def record_started_processes(row: dict) -> list[int]:
return [item["pid"] for item in members]
-def owned_process_group(row: dict) -> list[int]:
+def owned_process_group(row: dict, *, stopping: bool = False) -> list[int]:
pid = int(row["pid"])
pgid = int(row["pgid"])
- members = [item for item in process_rows() if item["pgid"] == pgid]
- if not members:
- return []
- if pgid != pid:
- raise ValueError("recorded process group is not led by the launched Desktop PID")
+ snapshot = process_rows()
recorded = {int(item["pid"]): item for item in row.get("process_identities", [])}
- if not recorded:
- raise ValueError("session has no process start identities; refusing to signal")
- for item in members:
- expected = recorded.get(item["pid"])
- if expected is None:
- raise ValueError(f"process group contains unrecorded PID {item['pid']}; refusing to signal")
- verify_process_identity(row, item, expected)
- return [item["pid"] for item in members]
+ exited = set()
+ while True:
+ if any(item["pid"] in exited for item in snapshot):
+ raise ValueError("an exited PID reappeared during stop; refusing to signal")
+ members = [item for item in snapshot if item["pgid"] == pgid]
+ if not members:
+ return []
+ if pgid != pid:
+ raise ValueError("recorded process group is not led by the launched Desktop PID")
+ if not recorded:
+ raise ValueError("session has no process start identities; refusing to signal")
+ for item in members:
+ expected = recorded.get(item["pid"])
+ if expected is None:
+ raise ValueError(f"process group contains unrecorded PID {item['pid']}; refusing to signal")
+ try:
+ verify_process_identity(row, item, expected)
+ except ProcessLookupError:
+ if not stopping:
+ raise
+ latest = process_rows()
+ if any(current["pid"] == item["pid"] for current in latest):
+ raise
+ # TERM/KILL can win between ps and the native identity query. Only
+ # confirmed absence is normal exit; revalidate the complete fresh
+ # snapshot before another signal, including any newly seen member.
+ # Each retry removes a different recorded PID, so this is bounded.
+ exited.add(item["pid"])
+ snapshot = latest
+ break
+ else:
+ return [item["pid"] for item in members]
def stop_group(row: dict, timeout: float = 12.0) -> list[int]:
@@ -644,16 +678,16 @@ def stop_group(row: dict, timeout: float = 12.0) -> list[int]:
os.killpg(pgid, signal.SIGTERM)
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
- if not owned_process_group(row):
+ if not owned_process_group(row, stopping=True):
return members
time.sleep(0.1)
- remaining = owned_process_group(row)
+ remaining = owned_process_group(row, stopping=True)
if remaining:
os.killpg(pgid, signal.SIGKILL)
deadline = time.monotonic() + 2.0
- while time.monotonic() < deadline and owned_process_group(row):
+ while time.monotonic() < deadline and owned_process_group(row, stopping=True):
time.sleep(0.05)
- remaining = owned_process_group(row)
+ remaining = owned_process_group(row, stopping=True)
if remaining:
raise RuntimeError(f"process group still has verified members after SIGKILL: {remaining}")
return members
@@ -663,7 +697,7 @@ def pilot_config(args: argparse.Namespace) -> int:
frontend = Path(args.frontend_dist).resolve(strict=True)
if not frontend.is_dir() or not (frontend / "index.html").is_file():
raise ValueError(f"frontend dist must contain index.html: {frontend}")
- repository = Path(__file__).resolve().parent.parent
+ repository = Path(args.repo).resolve(strict=True) if args.repo else Path(__file__).resolve().parent.parent
config_path = repository / "apps/desktop/src-tauri/tauri.pilot.conf.json"
production_path = repository / "apps/desktop/src-tauri/tauri.conf.json"
config = json.loads(config_path.read_text(encoding="utf-8"))
@@ -849,9 +883,11 @@ def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(description=__doc__)
subparsers = parser.add_subparsers(dest="action", required=True)
configure = subparsers.add_parser(
- "config", help="print the isolated TAURI_CONFIG merge for an already-built frontend"
+ "config", allow_abbrev=False,
+ help="print the isolated TAURI_CONFIG merge for an already-built frontend"
)
configure.add_argument("--frontend-dist", required=True)
+ configure.add_argument("--repo", help="repository containing the Desktop config; defaults to this script's checkout")
configure.set_defaults(function=pilot_config)
launch = subparsers.add_parser("start", help="start one isolated instrumented Desktop")
launch.add_argument("--app", required=True, help="absolute or relative path to hiroute-desktop")
diff --git a/scripts/test-agent-product-support.py b/scripts/test-agent-product-support.py
new file mode 100644
index 00000000..291893d6
--- /dev/null
+++ b/scripts/test-agent-product-support.py
@@ -0,0 +1,99 @@
+#!/usr/bin/env python3
+"""Shared native product-fixture mechanics; no native Agent or product acceptance claim."""
+import os
+from pathlib import Path
+import subprocess
+import sys
+import tempfile
+from types import SimpleNamespace
+import unittest
+
+sys.dont_write_bytecode = True
+sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'crates/daemon/tests/support'))
+from agent_product_support import apply_settings, run_native_command
+
+
+class SettingsJourneyTests(unittest.TestCase):
+ def test_each_facet_applies_the_accepted_preview_and_observes_current_state(self):
+ for facet in ('model', 'collaboration'):
+ for intent in ('configure', 'restore'):
+ with self.subTest(facet=facet, intent=intent):
+ calls = []
+ spec = {'context_id': 'context', facet: {'intent': intent}}
+ canonical = dict(spec, access_token={'intent': 'keep'})
+ state = {'state': 'configured', 'collaboration': {'state': 'restored'}}
+ command = 'agents restore' if intent == 'restore' else 'agents connect'
+
+ def preview(name, body):
+ calls.append(name)
+ if name == 'agents connect status':
+ self.assertEqual(body['context_id'], 'context')
+ return state
+ self.assertEqual(body, {'spec': spec})
+ return {'applicable': True, 'spec': canonical, 'accept_digest': 'accepted',
+ 'dependency_digest': 'dependencies', 'expected_revisions': {'settings': 7},
+ 'resident_service': {'login_item_required': True}}
+
+ def apply(name, body):
+ calls.append(name)
+ self.assertEqual(body, {'spec': canonical, 'accept_digest': 'accepted',
+ 'dependency_digest': 'dependencies', 'expected_revisions': {'settings': 7},
+ 'idempotency_key': 'one-operation',
+ 'login_item': {'before': 'not_registered', 'after': 'enabled', 'created': True}})
+ return 0, {'data': {'state': 'succeeded'}}
+
+ _, observed = apply_settings(SimpleNamespace(preview=preview, cli=apply), spec, 'one-operation', facet)
+ self.assertIs(observed, state)
+ self.assertEqual(calls, [command + ' preview', command + ' apply', 'agents connect status'])
+
+ def test_blocked_or_unfinished_operations_cannot_be_reported_as_configured(self):
+ for applicable in (False, True):
+ calls = []
+ def preview(command, body):
+ calls.append(command)
+ self.assertNotEqual(command, 'agents connect status')
+ return dict(applicable=applicable, spec=body['spec'], accept_digest='a',
+ dependency_digest='d', expected_revisions={})
+ def apply(command, body):
+ calls.append(command)
+ return 0, {'data': {'state': 'awaiting_confirmation'}}
+ with self.assertRaises(AssertionError):
+ apply_settings(SimpleNamespace(preview=preview, cli=apply),
+ {'context_id': 'c', 'model': {'intent': 'configure'}}, 'key', 'model')
+ self.assertEqual(len(calls), 2 if applicable else 1)
+
+
+class NativeProcessTests(unittest.TestCase):
+ def setUp(self):
+ self.root = tempfile.TemporaryDirectory()
+ self.addCleanup(self.root.cleanup)
+ self.product = SimpleNamespace(project=Path(self.root.name), env=dict(os.environ), outputs=[])
+
+ def test_output_is_retained_privately_and_native_verdict_stays_with_the_caller(self):
+ code = "import os,sys; print(os.environ['FIXTURE_VALUE']); print('private-stderr',file=sys.stderr)"
+ output = run_native_command(self.product, [sys.executable, '-c', code], timeout=5,
+ label='fixture', env=dict(self.product.env, FIXTURE_VALUE='receipt'))
+ self.assertEqual(output, b'receipt\n')
+ self.assertEqual(self.product.outputs, [b'receipt\n', b'private-stderr\n'])
+ with self.assertRaisesRegex(AssertionError, '^fixture failed; inspect private diagnostics$'):
+ run_native_command(self.product, [sys.executable, '-c', "print('private-failure');exit(2)"],
+ timeout=5, label='fixture')
+ self.assertIn(b'private-failure\n', self.product.outputs)
+
+ def test_timeout_reaps_its_process_and_preserves_an_independent_neighbor(self):
+ neighbor = subprocess.Popen([sys.executable, '-c', 'import time;time.sleep(30)'], start_new_session=True)
+ try:
+ code = 'import os,signal,time;signal.signal(signal.SIGTERM,signal.SIG_IGN);print(os.getpid(),flush=True);time.sleep(30)'
+ with self.assertRaisesRegex(AssertionError, '^fixture exceeded its deadline$'):
+ run_native_command(self.product, [sys.executable, '-c', code], timeout=1, label='fixture')
+ pid = int(self.product.outputs[0])
+ with self.assertRaises(ProcessLookupError):
+ os.kill(pid, 0)
+ self.assertIsNone(neighbor.poll())
+ finally:
+ neighbor.terminate()
+ neighbor.wait(timeout=5)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/scripts/test-contract-convergence.py b/scripts/test-contract-convergence.py
index dae31234..502a8ee1 100755
--- a/scripts/test-contract-convergence.py
+++ b/scripts/test-contract-convergence.py
@@ -44,8 +44,13 @@ class ContractConvergenceTests(unittest.TestCase):
root = Path(directory)
files = {
"crates/domain/src/schema.rs": (
- 'pub const LATEST_SCHEMA_VERSION: u32 = 17;\n"hiroute.sample/v2"'
+ '"hiroute.sample/v2"'
),
+ "crates/local-storage/src/migrations/mod.rs": (
+ "pub const LATEST_SCHEMA_VERSION: u32 = 25;\n"
+ ),
+ # Historical/test text must never stand in for the production declaration.
+ "tests/old_schema_fixture.rs": "pub const LATEST_SCHEMA_VERSION: u32 = 17;",
**files,
}
for path, content in files.items():
@@ -54,6 +59,101 @@ class ContractConvergenceTests(unittest.TestCase):
target.write_text(content)
return MODULE.audit(root, value or registry(), files)
+ def test_database_schema_change_is_not_hidden_by_a_fixture(self):
+ for version in (17, 22, 23, 24, 26):
+ with self.subTest(version=version):
+ errors = self.run_audit({
+ "legacy.rs": '"hiroute.sample/v1"',
+ "crates/local-storage/src/migrations/mod.rs": (
+ f"pub const LATEST_SCHEMA_VERSION: u32 = {version};\n"
+ ),
+ "tests/current_schema_fixture.rs": "pub const LATEST_SCHEMA_VERSION: u32 = 25;",
+ })
+ self.assertTrue(any("database schema" in error for error in errors), errors)
+
+ def test_database_schema_requires_the_authoritative_production_declaration(self):
+ for source in (
+ "// declaration removed\n",
+ "#[cfg(test)]\nmod fixture {\n pub const LATEST_SCHEMA_VERSION: u32 = 25;\n}\n",
+ "/*\npub const LATEST_SCHEMA_VERSION: u32 = 25;\n*/\n",
+ "pub const LATEST_SCHEMA_VERSION: u32 = 25;\npub const LATEST_SCHEMA_VERSION: u32 = 26;\n",
+ ):
+ with self.subTest(source=source):
+ errors = self.run_audit({
+ "legacy.rs": '"hiroute.sample/v1"',
+ "crates/local-storage/src/migrations/mod.rs": source,
+ "tests/current_schema_fixture.rs": "pub const LATEST_SCHEMA_VERSION: u32 = 25;",
+ })
+ self.assertTrue(any("database schema" in error for error in errors), errors)
+
+ def test_database_schema_requires_an_unconditional_top_level_constant(self):
+ declaration = "pub const LATEST_SCHEMA_VERSION: u32 = 25;\n"
+ for source in (
+ "#[cfg(all(unix, test))]\n" + declaration,
+ "#[cfg(any(unix, test))]\n" + declaration,
+ "#[cfg(not(test))]\n" + declaration,
+ '#[cfg_attr(unix, cfg(test))]\n' + declaration,
+ "#[cfg(\n all(unix, test)\n)]\n" + declaration,
+ declaration + "#[cfg(test)]\n" + declaration,
+ "#![cfg(test)]\nuse std::fs;\n" + declaration,
+ "mod fixture {\n" + declaration + "}\n",
+ "fixture! {\n" + declaration + "}\n",
+ "const FIXTURE: () = {\n" + declaration + "};\n",
+ ):
+ with self.subTest(source=source):
+ errors = self.run_audit({
+ "legacy.rs": '"hiroute.sample/v1"',
+ "crates/local-storage/src/migrations/mod.rs": source,
+ })
+ self.assertTrue(any("database schema" in error for error in errors), errors)
+
+ def test_database_schema_fails_closed_on_unterminated_lexical_input(self):
+ declaration = "pub const LATEST_SCHEMA_VERSION: u32 = 25;\n"
+ for suffix in ('/* unclosed', 'const TEXT: &str = r#"unclosed',
+ 'const TEXT: &str = "unclosed', 'mod fixture {', ']'):
+ with self.subTest(suffix=suffix):
+ errors = self.run_audit({
+ "legacy.rs": '"hiroute.sample/v1"',
+ "crates/local-storage/src/migrations/mod.rs": declaration + suffix,
+ })
+ self.assertTrue(any("database schema" in error for error in errors), errors)
+
+ def test_database_schema_ignores_literal_and_comment_declarations(self):
+ declaration = "pub const LATEST_SCHEMA_VERSION: u32 = 25;\n"
+ for source in (
+ 'const FIXTURE: &str = "\n' + declaration + '";\n',
+ 'const FIXTURE: &str = r"\n' + declaration + '";\n',
+ 'const FIXTURE: &str = r##"\n' + declaration + '"##;\n',
+ 'const FIXTURE: &[u8] = br#"\n' + declaration + '"#;\n',
+ 'const FIXTURE: &std::ffi::CStr = cr#"\n' + declaration + '"#;\n',
+ "/* outer /* nested */\n" + declaration + "*/\n",
+ ):
+ with self.subTest(source=source):
+ errors = self.run_audit({
+ "legacy.rs": '"hiroute.sample/v1"',
+ "crates/local-storage/src/migrations/mod.rs": source,
+ })
+ self.assertTrue(any("database schema" in error for error in errors), errors)
+
+ def test_database_schema_accepts_only_the_real_constant_among_decoys(self):
+ source = '''// Rust syntax inside literals cannot change the declaration's scope.
+const TEXT: &str = r##"/* } ;
+pub const LATEST_SCHEMA_VERSION: u32 = 17;
+"##;
+const QUOTE: &str = "\\\" }";
+const BRACE: char = '}';
+/* outer /* nested */ pub const LATEST_SCHEMA_VERSION: u32 = 17; */
+#[cfg(all(unix, test))]
+mod fixture {
+pub const LATEST_SCHEMA_VERSION: u32 = 17;
+}
+pub const LATEST_SCHEMA_VERSION: u32 = 25;
+'''
+ self.assertEqual(self.run_audit({
+ "legacy.rs": '"hiroute.sample/v1"',
+ "crates/local-storage/src/migrations/mod.rs": source,
+ }), [])
+
def test_registered_recovery_path_is_green(self):
self.assertEqual(self.run_audit({"legacy.rs": '"hiroute.sample/v1"'}), [])
diff --git a/scripts/test-desktop-pilot.py b/scripts/test-desktop-pilot.py
index 4670f52a..241997f4 100644
--- a/scripts/test-desktop-pilot.py
+++ b/scripts/test-desktop-pilot.py
@@ -7,6 +7,8 @@ import json
import os
from pathlib import Path
import signal
+import subprocess
+import sys
import tempfile
import unittest
from unittest import mock
@@ -19,6 +21,49 @@ pilot = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(pilot)
+class ConfigurationTests(unittest.TestCase):
+ def test_relocated_driver_uses_explicit_repository_and_local_default_still_works(self):
+ with tempfile.TemporaryDirectory() as temporary:
+ root = Path(temporary).resolve()
+ repository = root / "repository"
+ config_root = repository / "apps/desktop/src-tauri"
+ config_root.mkdir(parents=True)
+ production = {"app": {"windows": [{"label": "main", "title": "repository window"}]}}
+ overlay = {"identifier": "fixture.pilot", "app": {"windows": []}}
+ (config_root / "tauri.conf.json").write_text(json.dumps(production))
+ (config_root / "tauri.pilot.conf.json").write_text(json.dumps(overlay))
+ frontend = root / "frontend"
+ frontend.mkdir()
+ (frontend / "index.html").write_text("fixture")
+ for explicit_repository in (True, False):
+ with self.subTest(explicit_repository=explicit_repository):
+ scripts = root / "tooling-bundle" if explicit_repository else repository / "scripts"
+ scripts.mkdir()
+ driver = scripts / "desktop-pilot.py"
+ driver.write_text(Path(pilot.__file__).read_text())
+ command = [sys.executable, str(driver), "config", "--frontend-dist", str(frontend)]
+ if explicit_repository:
+ command += ["--repo", str(repository)]
+ result = subprocess.run(command, text=True, capture_output=True)
+ self.assertEqual(result.returncode, 0, result.stderr)
+ config = json.loads(result.stdout)
+ self.assertEqual(config["identifier"], "fixture.pilot")
+ self.assertEqual(config["build"], {"frontendDist": str(frontend)})
+ self.assertEqual(config["app"]["windows"], [
+ {"label": "main", "title": "repository window", "incognito": True}
+ ])
+ if explicit_repository:
+ # A wrapper-injected --repo must not be overridden via an abbreviation.
+ rejected = subprocess.run(
+ [*command, "--rep", str(root / "different-repository")],
+ text=True, capture_output=True,
+ )
+ self.assertEqual(rejected.returncode, 2, rejected.stderr)
+ self.assertIn("unrecognized arguments: --rep", rejected.stderr)
+ self.assertEqual(json.loads((config_root / "tauri.conf.json").read_text()), production)
+ self.assertEqual(json.loads((config_root / "tauri.pilot.conf.json").read_text()), overlay)
+
+
class ProcessOwnershipTests(unittest.TestCase):
def setUp(self):
self.temporary = tempfile.TemporaryDirectory()
@@ -142,6 +187,144 @@ class ProcessOwnershipTests(unittest.TestCase):
[mock.call(101, signal.SIGTERM), mock.call(101, signal.SIGKILL)],
)
+ def test_owned_child_exiting_between_stop_snapshot_and_identity_read_is_stopped(self):
+ members = [self.member(101, 1, 101), self.member(102, 101, 101)]
+ for unavailable in ("start_time", "executable"):
+ with self.subTest(unavailable=unavailable):
+ starts = ["app-start", "daemon-start", "daemon-start"]
+ executables = [self.app, self.daemon, self.daemon]
+ if unavailable == "start_time":
+ starts[-1] = ProcessLookupError("process exited after ps")
+ else:
+ executables[-1] = ProcessLookupError("process exited after start identity")
+ with mock.patch.object(
+ pilot, "process_rows", side_effect=[members, [members[1]], []]
+ ), mock.patch.object(
+ pilot, "process_start_time", side_effect=starts
+ ), mock.patch.object(
+ pilot, "process_executable", side_effect=executables
+ ), mock.patch.object(pilot.os, "killpg") as killpg:
+ stopped = pilot.stop_group(self.row, timeout=0)
+ self.assertEqual(stopped, [101, 102])
+ killpg.assert_called_once_with(101, signal.SIGTERM)
+
+ def test_unresolved_pid_still_present_after_stop_is_not_assumed_exited(self):
+ members = [self.member(101, 1, 101), self.member(102, 101, 101)]
+ for current in (members[1], self.member(102, 1, 202)):
+ with self.subTest(current_group=current["pgid"]):
+ with mock.patch.object(
+ pilot, "process_rows", side_effect=[members, [members[1]], [current]]
+ ), mock.patch.object(
+ pilot, "process_start_time",
+ side_effect=["app-start", "daemon-start", ProcessLookupError("identity unavailable")],
+ ), mock.patch.object(
+ pilot, "process_executable", side_effect=self.executable
+ ), mock.patch.object(pilot.os, "killpg") as killpg:
+ with self.assertRaisesRegex(ProcessLookupError, "identity unavailable"):
+ pilot.stop_group(self.row, timeout=0)
+ killpg.assert_called_once_with(101, signal.SIGTERM)
+
+ def test_replaced_child_after_sigterm_refuses_further_signal(self):
+ members = [self.member(101, 1, 101), self.member(102, 101, 101)]
+ with mock.patch.object(
+ pilot, "process_rows", side_effect=[members, [members[1]]]
+ ), mock.patch.object(
+ pilot, "process_start_time", side_effect=["app-start", "daemon-start", "new-daemon-start"]
+ ), mock.patch.object(
+ pilot, "process_executable", side_effect=self.executable
+ ), mock.patch.object(pilot.os, "killpg") as killpg:
+ with self.assertRaisesRegex(ValueError, "PID 102 was reused"):
+ pilot.stop_group(self.row, timeout=0)
+ killpg.assert_called_once_with(101, signal.SIGTERM)
+
+ def test_exit_race_rechecks_new_group_members_before_declaring_stop_complete(self):
+ members = [self.member(101, 1, 101), self.member(102, 101, 101)]
+ with mock.patch.object(
+ pilot, "process_rows", side_effect=[members, [members[1]], [self.member(103, 1, 101)]]
+ ), mock.patch.object(
+ pilot, "process_start_time",
+ side_effect=["app-start", "daemon-start", ProcessLookupError("exited")],
+ ), mock.patch.object(
+ pilot, "process_executable", side_effect=self.executable
+ ), mock.patch.object(pilot.os, "killpg") as killpg:
+ with self.assertRaisesRegex(ValueError, "unrecorded PID 103"):
+ pilot.stop_group(self.row, timeout=0)
+ killpg.assert_called_once_with(101, signal.SIGTERM)
+
+ def test_child_exiting_during_sigkill_wait_is_also_stopped(self):
+ members = [self.member(101, 1, 101), self.member(102, 101, 101)]
+ with mock.patch.object(
+ pilot, "process_rows", side_effect=[members, [members[1]], [members[1]], [], []]
+ ), mock.patch.object(
+ pilot, "process_start_time",
+ side_effect=["app-start", "daemon-start", "daemon-start", ProcessLookupError("exited")],
+ ), mock.patch.object(
+ pilot, "process_executable", side_effect=self.executable
+ ), mock.patch.object(
+ pilot.time, "monotonic", side_effect=[0, 1, 2, 3]
+ ), mock.patch.object(pilot.os, "killpg") as killpg:
+ stopped = pilot.stop_group(self.row, timeout=0)
+ self.assertEqual(stopped, [101, 102])
+ self.assertEqual(
+ killpg.call_args_list,
+ [mock.call(101, signal.SIGTERM), mock.call(101, signal.SIGKILL)],
+ )
+
+ @unittest.skipUnless(sys.platform == "darwin", "requires the native macOS process identity API")
+ def test_native_macos_exit_between_ps_and_proc_pidinfo_completes_stop(self):
+ # Desktop's native build already requires the platform C compiler. Build an
+ # owned fixture: relocated Apple system binaries may be killed before exec.
+ subprocess.run(
+ ["/usr/bin/cc", "-x", "c", "-", "-o", str(self.app)],
+ input="#include <unistd.h>\nint main(void) { sleep(30); return 0; }\n",
+ text=True,
+ capture_output=True,
+ check=True,
+ )
+ self.app.chmod(0o700)
+ self.row["artifacts"]["app"] = pilot.executable_artifact(self.app)
+ process = subprocess.Popen([str(self.app), "30"], start_new_session=True)
+ real_rows = pilot.process_rows
+ real_start_time = pilot.process_start_time
+ try:
+ self.row.update(pid=process.pid, pgid=process.pid, process_identities=[{
+ "pid": process.pid,
+ "role": "app",
+ "start_time": real_start_time(process.pid),
+ "executable": str(pilot.process_executable(process.pid)),
+ }])
+ snapshots = []
+ native_lookup_failures = []
+
+ def snapshot_with_one_exit_race():
+ if len(snapshots) == 1:
+ # Deliver the already observed ps snapshot after the real TERM
+ # exits/reaps our child. proc_pidinfo must run against the OS.
+ process.wait(timeout=5)
+ snapshots.append(snapshots[0])
+ return snapshots[0]
+ current = real_rows()
+ snapshots.append(current)
+ return current
+
+ def native_start_time(pid):
+ try:
+ return real_start_time(pid)
+ except ProcessLookupError:
+ native_lookup_failures.append(pid)
+ raise
+
+ with mock.patch.object(
+ pilot, "process_rows", side_effect=snapshot_with_one_exit_race
+ ), mock.patch.object(pilot, "process_start_time", side_effect=native_start_time):
+ self.assertEqual(pilot.stop_group(self.row, timeout=0), [process.pid])
+ self.assertEqual(native_lookup_failures, [process.pid])
+ self.assertIsNotNone(process.returncode)
+ finally:
+ if process.poll() is None:
+ os.killpg(process.pid, signal.SIGKILL)
+ process.wait(timeout=5)
+
class ManagedBuildTests(unittest.TestCase):
SHA = "a" * 40
@@ -403,13 +586,35 @@ class ExistingDataRootTests(unittest.TestCase):
temporary = self.session / "tmp"
for path in (runtime, temporary):
path.mkdir(mode=0o700)
- with mock.patch.dict(os.environ, {"HOME": "/real-user-home"}):
+ with mock.patch.dict(os.environ, {"HOME": "/real-user-home",
+ "CODEX_HOME": "/daily-codex",
+ "CLAUDE_CONFIG_DIR": "/daily-claude",
+ "QODER_CONFIG_DIR": "/daily-qoder"}):
environment = pilot.launch_environment(runtime, temporary, self.data, self.data)
+ self.assertEqual(os.environ["CODEX_HOME"], "/daily-codex")
self.assertEqual(environment["HOME"], str(self.data))
+ self.assertEqual(environment["CODEX_HOME"], str(self.data / ".codex"))
+ self.assertEqual(environment["CLAUDE_CONFIG_DIR"], str(self.data / ".claude"))
+ self.assertEqual(environment["QODER_CONFIG_DIR"], str(self.data / ".qoder"))
self.assertEqual(environment["HIROUTE_DESKTOP_TEST_ROOT"], str(self.data))
self.assertEqual(environment["XDG_RUNTIME_DIR"], str(runtime))
self.assertEqual(environment["TMPDIR"], str(temporary))
+ def test_isolated_native_context_does_not_borrow_provider_credentials(self):
+ variables = {key: 'synthetic-parent-value' for key in (
+ 'OPENAI_API_KEY', 'ANTHROPIC_AUTH_TOKEN', 'CLAUDE_CODE_OAUTH_TOKEN',
+ 'CODEX_CONFIG', 'CODEX_API_KEY', 'AWS_PROFILE', 'GOOGLE_APPLICATION_CREDENTIALS',
+ 'OPENROUTER_API_KEY', 'AZURE_OPENAI_API_KEY', 'HIROUTE_RUN_TOKEN',
+ 'CLAUDE_CODE_USE_BEDROCK', 'QODER_PERSONAL_ACCESS_TOKEN', 'QODER_MODEL',
+ 'QODER_SUBAGENT_MODEL')}
+ with mock.patch.dict(os.environ, variables):
+ isolated = pilot.launch_environment(self.session, self.session, self.data, self.data)
+ ordinary = pilot.launch_environment(self.session, self.session, self.data, None)
+ for key in variables:
+ self.assertNotIn(key, isolated)
+ self.assertEqual(ordinary[key], variables[key])
+ self.assertEqual(os.environ[key], variables[key])
+
class DiagnosticLevelSelectionTests(unittest.TestCase):
def setUp(self):
diff --git a/scripts/test-native-context-boundaries.py b/scripts/test-native-context-boundaries.py
new file mode 100644
index 00000000..74d58a1a
--- /dev/null
+++ b/scripts/test-native-context-boundaries.py
@@ -0,0 +1,218 @@
+#!/usr/bin/env python3
+"""Focused oracle/owned-shell checks, not real Agent acceptance."""
+import http.client
+import json
+import os
+from pathlib import Path
+import signal
+import subprocess
+import sys
+import tempfile
+import threading
+from types import SimpleNamespace
+import unittest
+from unittest.mock import patch
+
+sys.dont_write_bytecode = True
+REPO = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(REPO / 'crates/daemon/tests/support'))
+import native_context_boundaries as boundary
+from native_context_fixture import prepare
+
+
+class NativeBoundaryTests(unittest.TestCase):
+ def setUp(self):
+ self.temporary = tempfile.TemporaryDirectory()
+ self.addCleanup(self.temporary.cleanup)
+ self.root = Path(self.temporary.name)
+ home, project = self.root / 'home', self.root / 'project'
+ home.mkdir()
+ project.mkdir()
+ self.fixture = prepare(home, home / '.codex', project, 'codex')
+
+ def body(self, fixture, complete=False):
+ state = fixture['boundary']
+ body = {'tools': [{'name': 'exec_command'}], 'input': [
+ {'role': 'user', 'content': state['marker'] + ' '.join(
+ skill['discovery'] for skill in fixture['skills'])}]}
+ if complete:
+ body['input'].append({'type': 'function_call_output', 'call_id': 'native_context_execute',
+ 'output': ' '.join(skill[key] for skill in fixture['skills']
+ for key in ('contents', 'executed'))})
+ return body
+
+ def test_cross_routed_request_fails_before_tool_execution(self):
+ target = boundary.prepare_heartbeat(self.fixture, 'target')
+ body = self.body(target)
+ body['input'][0]['content'] = body['input'][0]['content'].replace('WORKER-target', 'WORKER-neighbor')
+ with self.assertRaisesRegex(AssertionError, 'other task source'):
+ boundary.boundary_decision(target, body)
+
+ def test_both_public_submissions_enter_before_either_returns(self):
+ fixtures = [boundary.prepare_heartbeat(self.fixture, role) for role in ('target', 'neighbor')]
+ arrived = threading.Barrier(2)
+
+ def accepted(product, command, prompt):
+ arrived.wait(timeout=1)
+ plan = command.split('--plan ', 1)[1].split()[0]
+ self.assertIn('WORKER-' + plan, prompt)
+ return 0, {'data': {'task_id': 'task-' + plan, 'run_id': 'run-' + plan}}
+
+ with patch.object(boundary, 'worker_cli', side_effect=accepted):
+ runs = boundary.submit_concurrent_workers(SimpleNamespace(project=self.root), fixtures,
+ ('target', 'neighbor'))
+ self.assertEqual([run['task_id'] for run in runs], ['task-target', 'task-neighbor'])
+
+ def test_concurrent_submission_does_not_hide_one_rejection(self):
+ fixtures = [boundary.prepare_heartbeat(self.fixture, role) for role in ('target', 'neighbor')]
+
+ def accepted(product, command, prompt):
+ if 'WORKER-neighbor' in prompt:
+ raise AssertionError('neighbor admission rejected')
+ return 0, {'data': {'task_id': 'target', 'run_id': 'run'}}
+
+ with patch.object(boundary, 'worker_cli', side_effect=accepted):
+ with self.assertRaisesRegex(AssertionError, 'neighbor admission rejected'):
+ boundary.submit_concurrent_workers(SimpleNamespace(project=self.root), fixtures,
+ ('target', 'neighbor'))
+
+ def test_heartbeat_requires_completed_native_skill_receipts(self):
+ target = boundary.prepare_heartbeat(self.fixture, 'target')
+ action = boundary.boundary_decision(target, self.body(target))
+ self.assertEqual(action['id'], 'native_context_execute')
+ action = boundary.boundary_decision(target, self.body(target, True))
+ self.assertEqual(action['id'], 'native_context_heartbeat_target')
+ self.assertIn(target['boundary']['script'], action['arguments']['cmd'])
+
+ def test_tool_result_does_not_substitute_for_actual_child_receipt(self):
+ target = boundary.prepare_heartbeat(self.fixture, 'target')
+ body = self.body(target, True)
+ body['input'].append({'type': 'function_call_output', 'call_id': 'native_context_heartbeat_target',
+ 'output': target['receipt']})
+ with patch.object(boundary, 'wait_until', side_effect=AssertionError('child not finished')):
+ with self.assertRaisesRegex(AssertionError, 'child not finished'):
+ boundary.boundary_decision(target, body)
+
+ def test_owned_shell_stop_has_no_effect_on_neighbor_heartbeat(self):
+ target = boundary.prepare_heartbeat(self.fixture, 'target')
+ neighbor = boundary.prepare_heartbeat(self.fixture, 'neighbor')
+ processes = []
+ try:
+ for fixture in (target, neighbor):
+ processes.append(subprocess.Popen(['/bin/sh', fixture['boundary']['script']],
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
+ start_new_session=True))
+ boundary.wait_until(lambda: all(boundary.heartbeat_size(item) > 0 for item in (target, neighbor)),
+ 'fixture heartbeat absent', 5)
+ # Signal only the child group created and still held by this test, never
+ # the PID read by the product oracle. No native Agent is launched here.
+ os.killpg(processes[0].pid, signal.SIGTERM)
+ processes[0].wait(timeout=5)
+ boundary.assert_cancelled_child_and_live_neighbor(target, neighbor)
+ Path(neighbor['boundary']['release']).touch()
+ processes[1].wait(timeout=5)
+ self.assertEqual(Path(neighbor['boundary']['done']).read_text().strip(), neighbor['receipt'])
+ finally:
+ for fixture in (target, neighbor):
+ Path(fixture['boundary']['release']).touch()
+ for process in processes:
+ if process.poll() is None:
+ os.killpg(process.pid, signal.SIGTERM)
+ process.wait(timeout=5)
+
+ def history(self):
+ root = Path(self.fixture['config']) / 'sessions'
+ root.mkdir()
+ path = root / 'native-task.jsonl'
+ path.write_text(json.dumps({'type': 'session_meta', 'payload': {'id': 'original-session'}})
+ + '\n' + json.dumps({'text': self.fixture['receipt']}) + '\n')
+ return path
+
+ def test_missing_history_rejection_restores_only_its_owned_transcript(self):
+ history = self.history()
+ original = history.read_bytes()
+ with patch.object(boundary, 'worker_cli', return_value=(6, {
+ 'error': {'code': 'CAPABILITY_UNAVAILABLE'}})):
+ result = boundary.missing_history_refuses_new_session(
+ object(), self.fixture, {'task_id': 'task', 'run_id': 'run'}, [])
+ self.assertEqual(result['native_session_id'], 'original-session')
+ self.assertEqual(history.read_bytes(), original)
+
+ def test_accepted_missing_history_must_fail_without_a_new_native_session(self):
+ history = self.history()
+ original = history.read_bytes()
+ with patch.object(boundary, 'worker_cli', return_value=(0, {'data': {'run_id': 'failed-load'}})), \
+ patch.object(boundary, 'wait_for_worker_result', return_value={'result': None}) as wait:
+ boundary.missing_history_refuses_new_session(
+ object(), self.fixture, {'task_id': 'task', 'run_id': 'run'}, [])
+ self.assertEqual(wait.call_args.kwargs['expected'], 'failed')
+ self.assertEqual(history.read_bytes(), original)
+
+ def test_missing_history_rejects_new_attempts_even_when_the_source_rejects_them(self):
+ history = self.history()
+ original = history.read_bytes()
+ task = {'task_id': 'task', 'run_id': 'run'}
+ for protocol in ('responses', 'messages'):
+ for rejection, status in (('credential', 401), ('endpoint', 404), ('model', 400)):
+ source = boundary.NativeContextUpstream(self.root)
+ try:
+ def rejected_request():
+ connection = http.client.HTTPConnection(*source.server.server_address, timeout=3)
+ try:
+ connection.request('POST', '/v1/' + ('wrong' if rejection == 'endpoint' else protocol),
+ json.dumps({'model': 'wrong' if rejection == 'model' else source.model}),
+ {'Authorization': 'Bearer ' + ('wrong' if rejection == 'credential' else source.token)})
+ response = connection.getresponse()
+ response.read()
+ self.assertEqual(response.status, status)
+ finally:
+ connection.close()
+
+ rejected_request() # A pre-existing attempt is not a new prompt from Continue.
+ for outcome in ((6, {'error': {'code': 'CAPABILITY_UNAVAILABLE'}}),
+ (0, {'data': {'run_id': 'failed-load'}})):
+ with self.subTest(protocol=protocol, rejection=rejection, accepted=outcome[0] == 0), \
+ patch.object(boundary, 'wait_for_worker_result', return_value={'result': None}):
+ with patch.object(boundary, 'worker_cli', return_value=outcome):
+ boundary.missing_history_refuses_new_session(object(), self.fixture, task, [source])
+ before = source.request_count()
+ def leaked_prompt(*args, **kwargs):
+ rejected_request()
+ return outcome
+ with patch.object(boundary, 'worker_cli', side_effect=leaked_prompt):
+ with self.assertRaisesRegex(AssertionError, 'missing history sent a model prompt'):
+ boundary.missing_history_refuses_new_session(object(), self.fixture, task, [source])
+ self.assertEqual(source.request_count(), before + 1)
+ self.assertEqual(boundary.source_events(source), [])
+ self.assertEqual(history.read_bytes(), original)
+ self.assertFalse(history.with_suffix('.native-context-held').exists())
+ finally:
+ source.close()
+
+ def test_unrelated_rejection_does_not_satisfy_missing_history(self):
+ history = self.history()
+ original = history.read_bytes()
+ with patch.object(boundary, 'worker_cli', return_value=(1, {
+ 'error': {'code': 'PERMISSION_DENIED'}})):
+ with self.assertRaises(AssertionError):
+ boundary.missing_history_refuses_new_session(
+ object(), self.fixture, {'task_id': 'task', 'run_id': 'run'}, [])
+ self.assertEqual(history.read_bytes(), original)
+
+ def test_missing_history_cannot_silently_create_a_replacement(self):
+ history = self.history()
+
+ def recreated(*args, **kwargs):
+ history.write_text('replacement native history')
+ return 6, {'error': {'code': 'CAPABILITY_UNAVAILABLE'}}
+
+ with patch.object(boundary, 'worker_cli', side_effect=recreated):
+ with self.assertRaisesRegex(AssertionError, 'unexpected replacement transcript'):
+ boundary.missing_history_refuses_new_session(
+ object(), self.fixture, {'task_id': 'task', 'run_id': 'run'}, [])
+ self.assertEqual(history.read_text(), 'replacement native history')
+ self.assertTrue(history.with_suffix('.native-context-held').exists())
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/scripts/test-native-context-product.py b/scripts/test-native-context-product.py
new file mode 100644
index 00000000..25b536b1
--- /dev/null
+++ b/scripts/test-native-context-product.py
@@ -0,0 +1,407 @@
+#!/usr/bin/env python3
+"""Test the native-context oracle and isolated fixture, without launching any Agent."""
+import http.client
+import io
+import json
+import os
+from pathlib import Path
+import subprocess
+import sys
+import tempfile
+import unittest
+from unittest.mock import Mock, patch
+
+sys.dont_write_bytecode = True
+REPO = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(REPO / 'crates/daemon/tests/support'))
+import native_context_fixture as fixture
+from native_context_product import assert_frozen_route, exact_history, publish_replacement_route, report_failure, save_context_source, wait_for_resumable_task
+from publication_product import Product
+
+
+class NativeContextOracleTests(unittest.TestCase):
+ def setUp(self):
+ self.temporary = tempfile.TemporaryDirectory()
+ self.addCleanup(self.temporary.cleanup)
+ self.root = Path(self.temporary.name)
+
+ def context(self, harness):
+ root = self.root / harness
+ home, project = root / 'home', root / 'project'
+ home.mkdir(parents=True)
+ project.mkdir()
+ config = home / ('.codex' if harness == 'codex' else '.claude')
+ return fixture.prepare(home, config, project, harness)
+
+ def body(self, value, results=None, prompt='Use the named native skills'):
+ text = prompt + ' ' + ' '.join(skill['discovery'] for skill in value['skills'])
+ results = results or {}
+ if value['harness'] == 'codex':
+ return {'model': 'gpt-5.4', 'tools': [{'name': 'exec_command'}], 'input': [
+ {'role': 'user', 'content': text},
+ *[{'type': 'function_call_output', 'call_id': key, 'output': output}
+ for key, output in results.items()]]}
+ return {'model': 'gpt-5.4', 'tools': [{'name': 'Skill'}, {'name': 'Bash'}], 'messages': [
+ {'role': 'user', 'content': text},
+ {'role': 'user', 'content': [{'type': 'tool_result', 'tool_use_id': key, 'content': output}
+ for key, output in results.items()]}]}
+
+ def receipt(self, value):
+ return ' '.join(skill[key] for skill in value['skills'] for key in ('contents', 'executed'))
+
+ def test_old_private_context_fails_without_native_discovery(self):
+ for harness in ('codex', 'claude'):
+ value = self.context(harness)
+ body = self.body(value)
+ if harness == 'codex':
+ body['input'][0]['content'] = 'Use native-context-user and native-context-project'
+ else:
+ body['messages'][0]['content'] = 'Use native-context-user and native-context-project'
+ with self.assertRaisesRegex(AssertionError, 'native skill discovery missing'):
+ fixture.decision(value, body)
+
+ def test_discovery_alone_is_not_skill_execution(self):
+ value = self.context('codex')
+ action = fixture.decision(value, self.body(value))
+ self.assertEqual(action['kind'], 'tool')
+ self.assertEqual(action['id'], 'native_context_execute')
+ self.assertNotIn(value['receipt'], json.dumps(action))
+
+ def test_actual_fixture_scripts_produce_the_independent_receipts(self):
+ value = self.context('codex')
+ action = fixture.decision(value, self.body(value))
+ # Only our two synthetic read-only scripts run; no Agent or product binary.
+ result = subprocess.run(['/bin/sh', '-c', action['arguments']['cmd']],
+ check=True, capture_output=True, text=True)
+ for skill in value['skills']:
+ self.assertIn(skill['contents'], result.stdout)
+ self.assertIn(skill['executed'], result.stdout)
+ answer = fixture.decision(value, self.body(value, {'native_context_execute': result.stdout}))
+ self.assertEqual(answer['text'], value['receipt'])
+ fixture.assert_preserved(value)
+
+ def test_wrong_tool_id_or_prompt_echo_cannot_prove_execution(self):
+ value = self.context('codex')
+ action = fixture.decision(value, self.body(value, {'wrong': self.receipt(value)}, self.receipt(value)))
+ self.assertEqual(action['kind'], 'tool')
+ with self.assertRaisesRegex(AssertionError, 'receipt mismatch'):
+ fixture.decision(value, self.body(value, {'native_context_execute': 'done'}))
+
+ def test_continue_requires_prior_correlated_tool_history(self):
+ for harness in ('codex', 'claude'):
+ value = self.context(harness)
+ for result in ({}, {'wrong-id': self.receipt(value)}):
+ with self.assertRaisesRegex(AssertionError, 'prior tool result'):
+ fixture.decision(value, self.body(value, result, fixture.CONTINUE_PROMPT + self.receipt(value)))
+ action = fixture.decision(value, self.body(
+ value, {'native_context_execute': self.receipt(value)}, fixture.CONTINUE_PROMPT))
+ self.assertTrue(action['continued'])
+
+ def test_claude_invokes_both_native_skills_before_shell(self):
+ value = self.context('claude')
+ results = {}
+ for skill in value['skills']:
+ action = fixture.decision(value, self.body(value, results))
+ self.assertEqual(action['name'], 'Skill')
+ self.assertEqual(action['arguments'], {'skill': skill['name']})
+ results[action['id']] = skill['contents']
+ action = fixture.decision(value, self.body(value, results))
+ self.assertEqual(action['name'], 'Bash')
+
+ def test_claude_missing_skill_tool_fails_closed(self):
+ value = self.context('claude')
+ body = self.body(value)
+ body['tools'] = [{'name': 'Bash'}]
+ with self.assertRaisesRegex(AssertionError, 'Skill tool unavailable'):
+ fixture.decision(value, body)
+
+ def test_failed_claude_tool_cannot_satisfy_continue(self):
+ value = self.context('claude')
+ body = self.body(value, {'native_context_execute': self.receipt(value)}, fixture.CONTINUE_PROMPT)
+ body['messages'][-1]['content'][0]['is_error'] = True
+ with self.assertRaisesRegex(AssertionError, 'prior tool result'):
+ fixture.decision(value, body)
+
+ def test_setup_refuses_existing_skill_and_preserves_neighbor(self):
+ value = self.context('codex')
+ with self.assertRaises(FileExistsError):
+ fixture.prepare(value['home'], value['config'], value['project'], 'codex')
+ fixture.assert_preserved(value)
+ Path(value['skills'][0]['skill']).write_text('changed')
+ with self.assertRaisesRegex(AssertionError, 'changed native user material'):
+ fixture.assert_preserved(value)
+
+ def test_native_session_identity_is_independent_of_task_identity(self):
+ value = self.context('codex')
+ root = Path(value['config']) / 'sessions'
+ root.mkdir()
+ history = root / 'rollout.jsonl'
+ history.write_text(json.dumps({'type': 'session_meta', 'payload': {'id': 'original-native-session'}})
+ + '\n' + json.dumps({'type': 'assistant', 'text': value['receipt']}) + '\n')
+ self.assertEqual(exact_history(value), (str(history), 'original-native-session'))
+ (root / 'new-session.jsonl').write_text(history.read_text())
+ with self.assertRaisesRegex(AssertionError, 'exactly the task native transcript'):
+ exact_history(value)
+
+ def test_protocol_events_contain_correlated_tool_and_terminal_frames(self):
+ for harness, protocol in (('codex', 'responses'), ('claude', 'messages')):
+ value = self.context(harness)
+ body = self.body(value)
+ action = fixture.decision(value, body)
+ frames = fixture.events(body, action, protocol)
+ self.assertIn(action['id'], json.dumps(frames))
+ self.assertEqual(frames[-1][0], 'response.completed' if protocol == 'responses' else 'message_stop')
+
+ def assert_native_wire(self, harness, protocol):
+ value = self.context(harness)
+ controls = self.root / harness
+ (controls / 'native-context.json').write_text(json.dumps(value))
+ server = fixture.NativeContextUpstream(controls)
+ self.addCleanup(server.close)
+ connection = http.client.HTTPConnection(*server.server.server_address, timeout=3)
+ self.addCleanup(connection.close)
+ for results in ({}, {'native_context_execute': self.receipt(value)}):
+ connection.request('POST', '/v1/' + protocol, json.dumps(self.body(value, results)),
+ {'Authorization': 'Bearer ' + server.token})
+ response = connection.getresponse()
+ wire = response.read().decode()
+ self.assertEqual(response.status, 200)
+ self.assertEqual(response.getheader('Content-Type'), 'text/event-stream')
+ frames = []
+ for frame in wire.strip().split('\n\n'):
+ fields = dict(line.split(': ', 1) for line in frame.splitlines())
+ event, payload = fields['event'], json.loads(fields['data'])
+ self.assertEqual(payload.get('type'), event, 'native SSE JSON lost its event discriminator')
+ if protocol == 'responses':
+ self.assertEqual(payload.get('sequence_number'), len(frames))
+ frames.append((event, payload))
+ self.assertGreater(len(frames), 2)
+ if protocol == 'responses':
+ self.assertEqual(frames[-1][0], 'response.completed')
+ self.assertEqual(frames[-1][1]['response']['status'], 'completed')
+ terminal = frames[-1][1]['response']['output'][0]
+ self.assertEqual(terminal['type'], 'message' if results else 'function_call')
+ if results:
+ self.assertEqual(terminal['content'][0]['text'], value['receipt'])
+ else:
+ self.assertEqual(frames[-1][0], 'message_stop')
+ self.assertEqual(frames[-2][1]['delta']['stop_reason'], 'end_turn' if results else 'tool_use')
+
+ def test_responses_native_wire_has_typed_ordered_terminal_frames(self):
+ self.assert_native_wire('codex', 'responses')
+
+ def test_messages_native_wire_has_typed_terminal_frames(self):
+ self.assert_native_wire('claude', 'messages')
+
+ def test_loopback_server_rejects_wrong_route_and_records_old_context_red(self):
+ value = self.context('codex')
+ (self.root / 'native-context.json').write_text(json.dumps(value))
+ server = fixture.NativeContextUpstream(self.root)
+ self.addCleanup(server.close)
+ connection = http.client.HTTPConnection(*server.server.server_address, timeout=3)
+ self.addCleanup(connection.close)
+ body = {'model': server.model, 'input': 'old private HOME', 'tools': []}
+ connection.request('POST', '/v1/responses', json.dumps(body), {'Authorization': 'Bearer wrong'})
+ response = connection.getresponse()
+ self.assertEqual(response.status, 401)
+ response.read()
+ connection.request('POST', '/v1/responses', json.dumps(body), {'Authorization': 'Bearer ' + server.token})
+ response = connection.getresponse()
+ self.assertEqual(response.status, 400)
+ response.read()
+ recorded = json.loads((self.root / 'native-context-events.jsonl').read_text())
+ self.assertEqual(recorded['state'], 'red')
+ self.assertIn('discovery missing', recorded['reason'])
+
+ def test_product_native_roots_do_not_escape_to_parent_configuration(self):
+ with patch.dict(os.environ, {'CODEX_HOME': '/daily/codex', 'CLAUDE_CONFIG_DIR': '/daily/claude',
+ 'CLAUDE_CODE_OAUTH_TOKEN': 'synthetic-parent-token',
+ 'CODEX_CONFIG': 'synthetic-parent-config', 'AWS_PROFILE': 'daily',
+ 'QODER_CONFIG_DIR': '/daily/qoder',
+ 'HIROUTE_WORKER_RECEIPT_DIR': '/daily/worker-receipts',
+ 'QODER_PERSONAL_ACCESS_TOKEN': 'synthetic-qoder-secret'}):
+ product = Product(REPO, root=self.root / 'product')
+ home = Path(product.env['HOME'])
+ self.assertEqual(product.env['CODEX_HOME'], str(home / '.codex'))
+ self.assertEqual(product.env['CLAUDE_CONFIG_DIR'], str(home / '.claude'))
+ self.assertEqual(product.env['QODER_CONFIG_DIR'], str(home / '.qoder'))
+ receipt_root = str(product.root / 'worker-receipts')
+ self.assertEqual(product.env['HIROUTE_WORKER_RECEIPT_DIR'], receipt_root)
+ # Borrowing a normally logged-in native HOME must not borrow HiRoute's
+ # client submission journal or collide with earlier acceptance runs.
+ product.env['HOME'] = '/explicitly-borrowed/native-home'
+ self.assertEqual(product.env['HIROUTE_WORKER_RECEIPT_DIR'], receipt_root)
+ neighbor = Product(REPO, root=self.root / 'neighbor-product')
+ neighbor.env['HOME'] = product.env['HOME']
+ self.assertNotEqual(neighbor.env['HIROUTE_WORKER_RECEIPT_DIR'], receipt_root)
+ for key in ('CLAUDE_CODE_OAUTH_TOKEN', 'CODEX_CONFIG', 'AWS_PROFILE', 'QODER_PERSONAL_ACCESS_TOKEN'):
+ self.assertNotIn(key, product.env)
+
+ def test_proxy_trap_records_any_method_without_request_content(self):
+ trap = fixture.NativeProxyTrap(self.root / 'proxy-attempts.log')
+ self.addCleanup(trap.close)
+ connection = http.client.HTTPConnection(*trap.server.server_address, timeout=3)
+ self.addCleanup(connection.close)
+ for method in ('CONNECT', 'POST', 'CUSTOM_METHOD'):
+ connection.request(method, '/synthetic-private-path', 'synthetic-private-body',
+ {'Proxy-Authorization': 'synthetic-private-token'})
+ response = connection.getresponse()
+ self.assertEqual(response.status, 502)
+ response.read()
+ self.assertEqual(trap.path.read_text(), 'proxy-request\n' * 3)
+
+ def test_claude_proxy_conflict_is_live_and_part_of_preservation_verdict(self):
+ value = self.context('claude')
+ upstream = fixture.NativeContextUpstream(self.root)
+ self.addCleanup(upstream.close)
+ environment = fixture.install_proxy_conflict(value, upstream)
+ self.assertEqual({environment[name] for name in ('HTTP_PROXY', 'HTTPS_PROXY', 'ALL_PROXY',
+ 'http_proxy', 'https_proxy', 'all_proxy')},
+ {upstream.proxy_trap.url})
+ self.assertEqual(environment['NO_PROXY'], environment['no_proxy'])
+ self.assertNotIn('127.0.0.1', environment['NO_PROXY'])
+ fixture.assert_preserved(value)
+ connection = http.client.HTTPConnection(*upstream.proxy_trap.server.server_address, timeout=3)
+ self.addCleanup(connection.close)
+ connection.request('CONNECT', 'synthetic.invalid:443')
+ response = connection.getresponse()
+ response.read()
+ with self.assertRaisesRegex(AssertionError, 'user-configured proxy'):
+ fixture.assert_preserved(value)
+
+ def test_native_sources_declare_a_budget_the_selected_client_can_admit(self):
+ upstream = Mock(token='synthetic-token', model='synthetic-model')
+ for harness, protocol, context_tokens in (('codex_cli', 'responses', 32768),
+ ('claude_code', 'messages', 200000), ('qoder_cli', 'responses', 100000)):
+ product = Mock(worker_work={'harness': harness, 'protocol': protocol})
+ with patch('native_context_product.save_native_source', return_value={'binding_id': 'saved'}) as save:
+ self.assertEqual(save_context_source(product, upstream, 'neighbor'), {'binding_id': 'saved'})
+ self.assertEqual(save.call_args.kwargs['context_tokens'], context_tokens)
+ self.assertEqual(save.call_args.kwargs['protocol'], protocol)
+ self.assertEqual(save.call_args.kwargs['variant'], 'neighbor')
+
+ def test_plan_replacement_changes_the_actual_route(self):
+ product = Mock(root=self.root, worker_work={'protocol': 'responses', 'harness': 'codex_cli'})
+ product.preview.return_value = {'preview_id': 'new-route'}
+ upstream = Mock(controls=self.root)
+ with patch('native_context_product.NativeContextUpstream', return_value=upstream), \
+ patch('native_context_product.save_native_source', return_value={'binding_id': 'new-binding'}) as save, \
+ patch('native_context_product.plan_change', return_value={'change': 'new-route'}) as change:
+ self.assertIs(publish_replacement_route(product, {'harness': 'codex'}), upstream)
+ self.assertEqual(upstream.model, 'gpt-5.5')
+ self.assertEqual(save.call_args.kwargs['upstream_model_id'], 'gpt-5.5')
+ self.assertEqual(change.call_args.kwargs['candidates'], [{'binding_id': 'new-binding'}])
+ product.apply.assert_called_once()
+
+ def test_frozen_route_requires_old_source_traffic_and_rejects_new_route_traffic(self):
+ replacement = Mock(controls=self.root)
+ replacement.request_count.return_value = 0
+ continued = {'state': 'green', 'continued': True}
+ with self.assertRaisesRegex(AssertionError, 'original source'):
+ assert_frozen_route([continued], 1, replacement)
+ assert_frozen_route([continued], 0, replacement)
+ (self.root / 'native-context-events.jsonl').write_text(json.dumps(continued) + '\n')
+ with self.assertRaisesRegex(AssertionError, 'newly published route'):
+ assert_frozen_route([continued], 0, replacement)
+
+ def test_frozen_route_rejects_attempts_even_when_the_new_source_rejects_them(self):
+ continued = {'state': 'green', 'continued': True}
+ for protocol in ('responses', 'messages'):
+ for rejection, status in (('credential', 401), ('endpoint', 404), ('model', 400)):
+ with self.subTest(protocol=protocol, rejection=rejection):
+ source = fixture.NativeContextUpstream(self.root)
+ connection = http.client.HTTPConnection(*source.server.server_address, timeout=3)
+ try:
+ assert_frozen_route([continued], 0, source)
+ connection.request('POST', '/v1/' + ('wrong' if rejection == 'endpoint' else protocol),
+ json.dumps({'model': 'wrong' if rejection == 'model' else source.model}),
+ {'Authorization': 'Bearer ' + ('wrong' if rejection == 'credential' else source.token)})
+ response = connection.getresponse()
+ response.read()
+ self.assertEqual(response.status, status)
+ self.assertEqual(source.request_count(), 1)
+ self.assertFalse((self.root / 'native-context-events.jsonl').exists())
+ with self.assertRaisesRegex(AssertionError, 'newly published route'):
+ assert_frozen_route([continued], 0, source)
+ finally:
+ connection.close()
+ source.close()
+
+ def test_failed_journey_preserves_diagnostics_even_if_stop_fails(self):
+ product = Mock(repo=self.root)
+ product.stop.side_effect = RuntimeError('stop failure')
+ product.preserve_diagnostics.return_value = {'state': 'complete', 'current_boot': 'this-boot'}
+ report = {'scenario': 'native-case', 'worker_harness': 'codex'}
+ with patch('sys.stdout', new_callable=io.StringIO) as output:
+ report_failure(product, report, 'actual-failure-stage')
+ emitted = json.loads(output.getvalue())
+ self.assertEqual(emitted['stage'], 'actual-failure-stage')
+ self.assertEqual(emitted['state'], 'red')
+ self.assertEqual(emitted['daemon_stop_state'], 'failed')
+ self.assertEqual(emitted['diagnostics']['current_boot'], 'this-boot')
+ product.preserve_diagnostics.assert_called_once()
+
+ def test_diagnostics_copy_error_preserves_red_stage_and_primary_exception(self):
+ product = Mock(repo=self.root)
+ product.preserve_diagnostics.side_effect = OSError('sensitive exception detail')
+ report = {'scenario': 'native-case', 'worker_harness': 'claude'}
+ with patch('sys.stdout', new_callable=io.StringIO) as output:
+ with self.assertRaisesRegex(ValueError, 'primary failure'):
+ try:
+ raise ValueError('primary failure')
+ except ValueError:
+ report_failure(product, report, 'native-history')
+ raise
+ emitted = json.loads(output.getvalue())
+ self.assertEqual(emitted['state'], 'red')
+ self.assertEqual(emitted['stage'], 'native-history')
+ self.assertEqual(emitted['diagnostics'], {'state': 'unavailable', 'reason': 'diagnostics_io'})
+ self.assertNotIn('sensitive', output.getvalue())
+
+ def test_native_history_waits_for_public_cleanup_and_resume_eligibility(self):
+ ready = {'task_id': 'task', 'latest_run_id': 'run',
+ 'run': {'state': 'succeeded', 'cleanup': 'complete'}, 'resumable_until_ms': 2000}
+ responses = [(0, {'data': {'tasks': [dict(ready, resumable_until_ms=None)]}}),
+ (0, {'data': {'tasks': [ready]}})]
+ with patch('native_context_product.worker_cli', side_effect=responses) as read, \
+ patch('native_context_product.time.sleep'), patch('native_context_product.time.time', return_value=1):
+ self.assertEqual(wait_for_resumable_task(object(), 'task', 'run'), ready)
+ self.assertEqual(read.call_count, 2)
+
+ def test_missing_resume_eligibility_cannot_pass_just_because_history_exists(self):
+ task = {'task_id': 'task', 'latest_run_id': 'run',
+ 'run': {'state': 'succeeded', 'cleanup': 'complete'}, 'resumable_until_ms': None}
+ with patch('native_context_product.worker_cli', return_value=(0, {'data': {'tasks': [task]}})):
+ with self.assertRaisesRegex(AssertionError, 'continuation did not become ready'):
+ wait_for_resumable_task(object(), 'task', 'run', timeout=0)
+
+ def test_fixture_new_skill_ancestors_are_private_under_group_writable_umask(self):
+ previous = os.umask(0o002)
+ try:
+ value = self.context('codex')
+ finally:
+ os.umask(previous)
+ for base in (Path(value['home']), Path(value['project'])):
+ for relative in ('.agents', '.agents/skills'):
+ self.assertEqual((base / relative).stat().st_mode & 0o777, 0o700)
+
+ def test_fixture_never_chmods_an_existing_native_parent(self):
+ parent = self.root / 'existing-native-root'
+ parent.mkdir(mode=0o755)
+ original_mode = parent.stat().st_mode
+ fixture.write_new(parent / 'owned/subdirectory/file', 'owned')
+ self.assertEqual(parent.stat().st_mode, original_mode)
+ self.assertEqual((parent / 'owned').stat().st_mode & 0o777, 0o700)
+
+ def test_user_skill_uses_the_selected_claude_root(self):
+ home, project = self.root / 'home', self.root / 'workspace'
+ home.mkdir()
+ project.mkdir()
+ selected = home / 'custom-native-configuration'
+ value = fixture.prepare(home, selected, project, 'claude')
+ self.assertEqual(Path(value['skills'][0]['skill']).parent.parent, selected / 'skills')
+ self.assertFalse((home / '.claude').exists())
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/scripts/test-plan.py b/scripts/test-plan.py
index bf3080ef..bee8ed78 100644
--- a/scripts/test-plan.py
+++ b/scripts/test-plan.py
@@ -35,6 +35,11 @@ DIAGNOSTIC_CONTRACTS = (
"crates/diagnostics/src/identity.rs", "crates/diagnostics/src/error.rs",
)
SELECTION_TOOLING = {"scripts/test-plan.py", "scripts/test-test-plan.py"}
+WORKER_FIXTURE_TOOLING = {"scripts/test-agent-product-support.py",
+ "scripts/test-native-context-product.py",
+ "scripts/test-native-context-boundaries.py",
+ "scripts/test-qoder-product.py"}
+WORKER_BOOTSTRAP_TEST = "crates/daemon/src/delegation/profile/claude_adapter_bootstrap.test.mjs"
INTEGRATION_SKILL = ".agents/skills/hiroute-integrate/SKILL.md"
WEBSITE_TOOLING = {".github/workflows/website.yml", ".github/workflows/release.yml"}
WEBSITE_PREFIXES = ("apps/website/", ".github/scripts/")
@@ -57,9 +62,127 @@ VALIDATION_TOOLING = {"scripts/validation.py", "scripts/validation-host.py", "sc
"scripts/validation-schedule.py", "scripts/test-validation-schedule.py"}
PRODUCT_GROUPS = set(GROUPS) - {"diagnostics"}
+# Known shared Worker contracts consumed by the feature-gated Tauri bridge and
+# protected Session. Keep this bounded: shared-library location is not sufficient
+# to require Desktop compilation. Review new consumers when a contract moves.
+DESKTOP_WORKER_CONTRACTS = {
+ "crates/application-api/src/worker.rs",
+ "crates/domain/src/delegation/mod.rs",
+ "crates/domain/src/delegation/installation.rs",
+}
+
+
+def desktop_compile_checks(paths):
+ triggers = sorted({path for path in paths if path in DESKTOP_WORKER_CONTRACTS
+ or path.startswith("apps/desktop/src-tauri/")})
+ if not triggers:
+ return []
+ return [{
+ "id": "desktop.compile", "platform": "macos", "trigger_paths": triggers,
+ "guide": "docs/validation-routing.md#native-consumer-compilation",
+ # --frontend-dist uses the existing Pilot TAURI_CONFIG, whose ACL requires
+ # desktop-pilot. That feature also enables desktop-runtime and its bridge.
+ "command_template": ["python3", "scripts/validation.py",
+ "--frontend-dist", "<candidate-frontend-dist>", "desktop", "run",
+ "--ref", "<pushed-branch-ref>", "--sha", "<candidate-sha>",
+ "--plan", "<feature-plan>", "--phase", "focused", "--cargo-only", "--",
+ "cargo", "check", "--locked", "-p", "hiroute-desktop",
+ "--features", "desktop-pilot", "--all-targets"],
+ "required_inputs": {"pushed-branch-ref": "Advertised refs/heads/... containing the candidate",
+ "candidate-sha": "Exact committed candidate being validated",
+ "candidate-frontend-dist": "Same-candidate built frontend directory on the Mac",
+ "feature-plan": "Current validation plan; include related runs when applicable"},
+ "evidence_limit": "Compile production and test consumers on the configured Mac; "
+ "does not execute tests or prove native product behavior.",
+ }]
+
+
+# One registration per explicit product entry. The ordinary commands only compile ignored
+# targets; these obligations require real installations and separate business verdicts.
+WORKER_PRODUCT_CHECKS = {
+ "worker_native_context": {
+ "id": "worker.native-context", "harnesses": ["codex", "claude"],
+ "guide": "tools/product-e2e/tests/WORKER_NATIVE_CONTEXT.md",
+ "business_cases": ["worker.context." + name for name in (
+ "native-skills", "concurrent-routing", "run-authority", "exact-continue",
+ "cancel-owned-work", "retention-ownership")],
+ "automated_cases": ["worker.context.native-skills", "worker.context.exact-continue",
+ "worker.context.concurrent-routing", "worker.context.cancel-owned-work"],
+ },
+ "worker_delegation": {
+ "id": "worker.lifecycle", "harnesses": ["codex", "claude"],
+ "guide": "docs/code-map/worker-context.md",
+ },
+ "worker_read": {
+ "id": "worker.read-continue", "harnesses": ["codex", "claude"],
+ "guide": "docs/code-map/worker-context.md",
+ },
+ "qoder_delegation": {
+ "id": "qoder.delegation", "harnesses": ["qoder"],
+ "guide": "tools/product-e2e/tests/QODER_DELEGATION.md",
+ "required_tests": [
+ "qoder_main_agent_uses_installed_user_skill_to_delegate_real_work",
+ "qoder_worker_uses_native_skills_and_continues_the_frozen_task",
+ "qoder_workers_route_independently_and_cancel_only_owned_work",
+ "qoder_worker_compaction_keeps_the_frozen_managed_route",
+ "qoder_main_agent_uses_persisted_additional_model_routes"],
+ "required_environment": ["HIROUTE_PRODUCT_CANDIDATE_SHA", "HIROUTE_WORKER_QODER_BINARY",
+ "HIROUTE_QODER_CONTEXT_HOME", "HIROUTE_QODER_CONFIG_DIR",
+ "HIROUTE_QODER_MODEL_CONTEXT_HOME", "HIROUTE_QODER_MODEL_CONFIG_DIR"],
+ "missing_environment": "fail",
+ },
+}
+OPT_IN_WORKER_TARGETS = set(WORKER_PRODUCT_CHECKS)
+PRODUCT_GUIDES = {entry["guide"] for entry in WORKER_PRODUCT_CHECKS.values()} | {
+ "crates/daemon/tests/support/NATIVE_CONTEXT_BOUNDARIES.md"}
+
+# Qoder-only leaves and the shared settings/Skill boundaries consumed by its main-Agent
+# journey. Model-specific Codex/Claude settings do not select unrelated native journeys.
+QODER_PRODUCT_PREFIXES = (
+ "crates/integrations/src/agents/qoder", "crates/daemon/src/delegation/profile/qoder",
+ "crates/daemon/src/control/runtime/settings_facts/qoder",
+ "crates/application/src/agent_connection/skill",
+ "crates/application/src/agent_connection/qoder",
+ "crates/daemon/src/control/runtime/qoder",
+ "crates/domain/src/agents/qoder",
+ "crates/application/src/agent_connection/settings/",
+)
+QODER_PRODUCT_PATHS = {
+ "crates/daemon/src/control/runtime.rs",
+ "crates/application-api/src/agent_settings.rs",
+ "crates/domain/src/agents/profile.rs",
+ "crates/integrations/src/agents/registry.rs",
+ "crates/daemon/src/control/runtime/agent_connection.rs",
+ "crates/daemon/src/control/runtime/settings_facts.rs",
+ "crates/daemon/src/control/runtime/settings_status.rs",
+ "crates/daemon/src/control/runtime/collaboration_installation.rs",
+ "crates/daemon/src/control/runtime/collaboration_status.rs",
+ "crates/daemon/src/control/runtime/settings_entry_qoder_tests.rs",
+ "crates/application/src/agent_connection/settings.rs",
+ "crates/application/src/agent_connection/settings_input.rs",
+ "crates/application/src/control_plane/agent_settings.rs",
+ "crates/integrations/src/agents/filesystem.rs",
+ "crates/integrations/src/agents/settings_discovery.rs",
+ "crates/integrations/src/agents/executable.rs",
+}
+# These helpers also serve publication/model journeys. Add the known real Worker gates
+# without pretending their complete ordinary-test dependency graph is bounded here.
+SHARED_WORKER_FIXTURES = {
+ "crates/daemon/tests/support/delegation_product.py",
+ "crates/daemon/tests/support/publication_product.py",
+}
+
def e2e_consumers(path):
"""Bounded test/fixture ownership, not a guessed production dependency graph."""
+ if path.startswith("tools/product-e2e/tests/worker_product_support/"):
+ return [("hiroute-product-e2e", name) for name in WORKER_PRODUCT_CHECKS]
+ if path.startswith("tools/product-e2e/tests/") and Path(path).stem in OPT_IN_WORKER_TARGETS:
+ return [("hiroute-product-e2e", Path(path).stem)]
+ if path.startswith("crates/daemon/tests/support/native_context_"):
+ return [("hiroute-product-e2e", name) for name in ("worker_native_context", "qoder_delegation")]
+ if path == "crates/daemon/tests/support/agent_product_support.py" or path.startswith("crates/daemon/tests/support/qoder_"):
+ return [("hiroute-product-e2e", "qoder_delegation")]
if path == "tools/e2e-harness/tests/p0_gateway_runtime.rs" or path.startswith("tools/e2e-harness/tests/p0_gateway_runtime/"):
return [("hiroute-e2e", "p0_gateway_runtime"), ("hiroute-e2e", "p0_gateway_protocol"),
("hiroute-e2e", "p0_gateway_matrix_coverage")]
@@ -82,16 +205,44 @@ def e2e_consumers(path):
PROCESS_TARGETS = {"p0_gateway_runtime", "p0_gateway_protocol", "smoke_cli"}
+def worker_product_checks(paths):
+ """Explicit opt-in obligations; ordinary Cargo success does not run ignored Agents."""
+ selected = set()
+ for path in paths:
+ if path.endswith(".md"):
+ continue
+ selected.update(target for package, target in e2e_consumers(path)
+ if package == "hiroute-product-e2e" and target in OPT_IN_WORKER_TARGETS)
+ if path in QODER_PRODUCT_PATHS or path.startswith(QODER_PRODUCT_PREFIXES):
+ selected.add("qoder_delegation")
+ elif path.startswith(("crates/daemon/src/delegation/", "crates/application/src/delegation/",
+ "crates/domain/src/delegation/")) or path in SHARED_WORKER_FIXTURES:
+ selected.update(OPT_IN_WORKER_TARGETS)
+ return [{**entry,
+ "command": ["cargo", "test", "--locked", "-p", "hiroute-product-e2e",
+ "--test", target, "--", "--ignored", "--nocapture", "--test-threads=1"],
+ "evidence_limit": "Real installed Harnesses with controlled upstream; native Desktop "
+ "and unexecuted component contracts need their own evidence."}
+ for target, entry in WORKER_PRODUCT_CHECKS.items() if target in selected]
+
+
def select(paths, full=False):
groups = set()
frontend = full
- native = False
+ native_checks = desktop_compile_checks(paths)
+ native = bool(native_checks)
reasons = []
selection_tooling = False
+ worker_fixture_tooling = False
validation_tooling = False
release_contract_tooling = False
targets = set()
for path in sorted(set(paths)):
+ if path in PRODUCT_GUIDES:
+ continue # Navigation-only guide; not embedded in a product binary.
+ if path in WORKER_FIXTURE_TOOLING:
+ worker_fixture_tooling = True
+ continue
if path in RELEASE_CONTRACT_TOOLING or path.startswith("contracts/releases/"):
release_contract_tooling = True
continue
@@ -163,8 +314,9 @@ def select(paths, full=False):
"--test", "transport_loopback", "loopback_plain_http_smoke_reuses_h1_connection_and_joins_server",
"--", "--exact"])
if full or "gateway" in groups:
- commands.append(["cargo", "run", "--locked", "-p", "hiroute-e2e", "--", "validate",
- "--scenario", "e2e/scenarios/core-routing.json", "--profile", "e2e/profiles/local-process.json"])
+ commands.append(["cargo", "test", "--locked", "-p", "hiroute-e2e", "--test", "case_shards",
+ "core_routing_validation_covers_the_complete_unsharded_scenario",
+ "--", "--exact", "--nocapture"])
if targets and not full:
if not groups:
commands.append(["cargo", "fmt", "--check"])
@@ -181,6 +333,10 @@ def select(paths, full=False):
commands.append(["cargo", "clippy", "--locked", "-p", package, "--all-targets", "--all-features"] +
(feature_flags if runtime_context and package == "hiroute-e2e" else []) + ["--", "-D", "warnings"])
for package, target in sorted(pending):
+ if package == "hiroute-product-e2e" and target in OPT_IN_WORKER_TARGETS:
+ # Clippy above compiles all consumers. Running an ignored-only target
+ # normally would produce zero executed tests, not product acceptance.
+ continue
flags = ["--lib"] if target == "lib" else ["--test", target]
commands.append(["cargo", "test", "--locked", "-p", package, "--all-features", *flags] +
(feature_flags if target == "p0_gateway_runtime" else []) +
@@ -195,6 +351,15 @@ def select(paths, full=False):
"--", "--exact"])
if selection_tooling:
commands.append(["python3", "scripts/test-test-plan.py"])
+ product_checks = worker_product_checks(paths)
+ if full or worker_fixture_tooling or product_checks:
+ commands.append(["python3", "scripts/test-agent-product-support.py"])
+ commands.append(["python3", "scripts/test-native-context-product.py"])
+ commands.append(["python3", "scripts/test-native-context-boundaries.py"])
+ if full or worker_fixture_tooling or any(check["id"] == "qoder.delegation" for check in product_checks):
+ commands.append(["python3", "scripts/test-qoder-product.py"])
+ if full or any(path.startswith("crates/daemon/src/delegation/profile/") for path in paths):
+ commands.append(["node", "--test", WORKER_BOOTSTRAP_TEST])
if full or release_contract_tooling:
commands.extend([["python3", "scripts/test-release-contracts.py"],
["python3", "scripts/test-release-contract-pr.py"],
@@ -209,6 +374,8 @@ def select(paths, full=False):
return {"mode": "full" if full else "affected", "paths": sorted(set(paths)),
"groups": sorted(groups), "reasons": reasons, "rust": rust,
"frontend": frontend, "native_required": native, "commands": commands,
+ "native_checks": native_checks,
+ "product_checks": product_checks,
"execution": {"remote_exclusive": full,
"feature_context": "Package selection may resolve different dependency features than workspace; preserve failing context when diagnosing."},
"note": "Native Desktop, real accounts and fixed-machine performance are separate evidence."}
@@ -235,7 +402,8 @@ def integration_preflight(plan, collect_failures=False, context_plan=None):
or path == "crates/local-storage/src/lib.rs"
for path in plan["paths"])
# These already-selected cheap tooling gates run before Rust preparation.
- commands = [c[:] for c in plan["commands"] if c[:1] == ["python3"]]
+ commands = [c[:] for c in plan["commands"]
+ if c[:1] == ["python3"] or c[:2] == ["node", "--test"]]
if targets:
# Keep the final package selection for broad plans: package selection can
# change dependency features, even when both commands say --all-features.
diff --git a/scripts/test-qoder-product.py b/scripts/test-qoder-product.py
new file mode 100644
index 00000000..d01cd378
--- /dev/null
+++ b/scripts/test-qoder-product.py
@@ -0,0 +1,631 @@
+#!/usr/bin/env python3
+"""Qoder fixture ownership and product oracles; no Agent or production verdict."""
+import http.client
+from contextlib import redirect_stdout
+import io
+import json
+import os
+import sqlite3
+from pathlib import Path
+import sys
+import tempfile
+from types import SimpleNamespace
+import unittest
+from unittest.mock import patch
+
+sys.dont_write_bytecode = True
+REPO = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(REPO / 'crates/daemon/tests/support'))
+import native_context_fixture as oracle
+import qoder_native_context as qoder
+import qoder_collaboration_product as collaboration
+from qoder_collaboration_fixture import MainAgentOracle, worker_decision, output_envelope
+from qoder_compaction_product import CompactionOracle, PRESSURE_TOKENS, assert_native_compaction
+import qoder_model_fixture as model_fixture
+import qoder_model_product as model_product
+
+
+class QoderFixtureContext:
+ def setUp(self):
+ self.temporary = tempfile.TemporaryDirectory()
+ self.addCleanup(self.temporary.cleanup)
+ self.root = Path(self.temporary.name)
+ self.home = self.root / 'borrowed-home'
+ self.config = self.home / '.qoder'
+ self.config.mkdir(parents=True)
+ self.settings = self.config / 'settings.json'
+ self.settings.write_text('{"model":"user-choice"}\n')
+ self.settings.chmod(0o640)
+ self.project = self.root / 'private-project'
+ self.project.mkdir()
+ self.product = SimpleNamespace(env={}, project=self.project, storage=self.root / 'storage')
+
+ def context(self):
+ with patch.dict(os.environ, {'HIROUTE_QODER_CONTEXT_HOME': str(self.home),
+ 'HIROUTE_QODER_CONFIG_DIR': str(self.config)}):
+ qoder.select_context(self.product)
+ return qoder.prepare_context(self.product)
+
+ def body(self, fixture, results=None, prompt='Use the requested native skills'):
+ return {'model': 'gpt-5.4', 'tools': [{'name': 'Skill'}, {'name': 'Bash'}], 'input': [
+ {'role': 'user', 'content': prompt + ' '.join(item['discovery'] for item in fixture['skills'])},
+ *[{'type': 'function_call_output', 'call_id': key, 'output': value}
+ for key, value in (results or {}).items()],
+ *[{'role': 'user', 'content': 'Base directory for this skill: ' +
+ str(Path(item['skill']).parent) + '\n\n' + item['contents']}
+ for item in fixture['skills']
+ if 'native_context_skill_' + item['scope'] in (results or {})]]}
+
+
+
+class QoderFixtureTests(QoderFixtureContext, unittest.TestCase):
+ def test_small_context_requires_the_exact_output_budget_on_real_requests(self):
+ fixture = self.context()
+ fixture['expected_max_output_tokens'] = 4096
+ body = self.body(fixture)
+ for maximum in (None, 32768):
+ if maximum is not None:
+ body['max_output_tokens'] = maximum
+ with self.assertRaisesRegex(AssertionError, 'frozen source output budget'):
+ oracle.decision(fixture, body)
+ body['max_output_tokens'] = 4096
+ self.assertEqual(oracle.decision(fixture, body)['name'], 'Skill')
+
+ def test_ordinary_skill_journey_rejects_native_compaction_instead_of_reissuing_tools(self):
+ fixture = self.context()
+ body = self.body(fixture, prompt='Create a detailed summary for summarization.')
+ with self.assertRaisesRegex(AssertionError, 'unexpected Qoder compaction'):
+ oracle.decision(fixture, body)
+
+ def test_cancelled_history_uses_exact_task_identity_without_a_continue_binding(self):
+ fixture = self.context()
+ fixture['task_id'] = 'task/cancelled'
+ owned = self.product.storage / 'delegation-workers/sessions/owned-task'
+ owned.mkdir(parents=True)
+ (owned / '.hiroute-native-root-v1.json').write_text(json.dumps({
+ 'task_id': fixture['task_id'], 'harness': 'qoder_cli'}))
+ (owned / 'borrowed-native-context.json').write_text(json.dumps({
+ 'version': 1, 'harness': 'qoder_cli', 'context': {
+ 'home': fixture['home'], 'config_root': fixture['config'], 'workspace': fixture['project']}}))
+ native_id, run_id = 'exact-cancelled-native-id', 'run/cancelled'
+ task = {'task_id': fixture['task_id'], 'latest_run_id': run_id, 'plan': {'harness': 'qoder_cli'},
+ 'session': {'native_session_id': native_id, 'acp_session_id': native_id}}
+ run = {'task_id': fixture['task_id'], 'run_id': run_id,
+ 'progress': {'state': 'cancelled', 'cleanup': 'complete'}}
+ database = self.product.storage / 'live/runtime.db'
+ database.parent.mkdir()
+ with sqlite3.connect(database) as connection:
+ connection.execute('CREATE TABLE delegation_tasks (workspace_id TEXT, task_id TEXT, record_json TEXT)')
+ connection.execute('CREATE TABLE delegation_runs (workspace_id TEXT, run_id TEXT, record_json TEXT)')
+ connection.execute('INSERT INTO delegation_tasks VALUES (?,?,?)', ('personal/default', fixture['task_id'], json.dumps(task)))
+ connection.execute('INSERT INTO delegation_runs VALUES (?,?,?)', ('personal/default', run_id, json.dumps(run)))
+ history = qoder.history_directory(fixture) / (native_id + '.jsonl')
+ history.parent.mkdir(parents=True)
+ history.write_text(fixture['receipt'])
+ self.assertEqual(qoder.cancelled_history(fixture, run_id), (str(history), native_id))
+ with self.assertRaises(FileNotFoundError):
+ qoder.task_binding(fixture)
+ with sqlite3.connect(database) as connection:
+ run['task_id'] = 'task/other'
+ connection.execute('UPDATE delegation_runs SET record_json=?', (json.dumps(run),))
+ with self.assertRaisesRegex(AssertionError, 'cancelled task identity'):
+ qoder.cancelled_history(fixture, run_id)
+
+ def test_missing_explicit_context_does_not_fall_back_to_daily_home(self):
+ with patch.dict(os.environ, {'HOME': str(self.home), 'QODER_CONFIG_DIR': str(self.config)}, clear=True):
+ with self.assertRaisesRegex(AssertionError, 'explicitly select'):
+ qoder.select_context(self.product)
+ self.assertEqual(self.product.env, {})
+
+ def test_borrowed_settings_and_neighbor_survive_owned_receipt_cleanup(self):
+ neighbor = self.config / 'user-file'
+ neighbor.write_text('keep user file')
+ before = qoder.settings_snapshot(self.config)
+ fixture = self.context()
+ self.assertEqual(self.product.env['QODER_CONFIG_DIR'], str(self.config))
+ qoder.cleanup_context(self.product)
+ self.assertEqual(qoder.settings_snapshot(self.config), before)
+ self.assertEqual(neighbor.read_text(), 'keep user file')
+ self.assertFalse(Path(fixture['skills'][0]['skill']).exists())
+
+ def test_partial_setup_failure_cleans_only_recorded_new_user_files(self):
+ original = oracle.write_new
+ def fail_project(path, text, executable=False):
+ if path.is_relative_to(self.project):
+ raise OSError('synthetic project write failure')
+ original(path, text, executable)
+ with patch.object(oracle, 'write_new', side_effect=fail_project):
+ with self.assertRaisesRegex(OSError, 'project write failure'):
+ self.context()
+ qoder.cleanup_context(self.product)
+ self.assertEqual(list((self.config / 'skills').iterdir()), [])
+ self.assertEqual(self.settings.read_text(), '{"model":"user-choice"}\n')
+
+ def test_new_collaboration_leaf_preserves_permissive_user_parent(self):
+ self.context()
+ parent = self.config / 'skills'
+ parent.chmod(0o775)
+ skill = qoder.prepare_collaboration_target(self.product)
+ self.assertEqual(skill.parent.stat().st_mode & 0o777, 0o700)
+ self.assertFalse(skill.exists(), 'fixture must not manufacture the collaboration Skill')
+ qoder.cleanup_context(self.product)
+ self.assertFalse(skill.parent.exists())
+ self.assertEqual(parent.stat().st_mode & 0o777, 0o775)
+
+ def test_existing_collaboration_leaf_and_skill_are_never_fixture_owned(self):
+ self.context()
+ directory = self.config / 'skills/hiroute-collaboration'
+ directory.mkdir(mode=0o775)
+ directory.chmod(0o775)
+ skill = directory / 'SKILL.md'
+ skill.write_text('existing user Skill')
+ before = qoder.directory_identity(directory)
+ self.assertEqual(qoder.prepare_collaboration_target(self.product), skill)
+ self.assertFalse(hasattr(self.product, 'qoder_owned_collaboration_directory'))
+ qoder.cleanup_context(self.product)
+ self.assertEqual(qoder.directory_identity(directory), before)
+ self.assertEqual(skill.read_text(), 'existing user Skill')
+
+ def test_owned_collaboration_leaf_cleanup_refuses_new_contents_or_permissions(self):
+ self.context()
+ skill = qoder.prepare_collaboration_target(self.product)
+ skill.write_text('material not restored by the product')
+ with self.assertRaisesRegex(AssertionError, 'changed or nonempty collaboration'):
+ qoder.cleanup_context(self.product)
+ self.assertEqual(skill.read_text(), 'material not restored by the product')
+ # Receipt cleanup has finished; this second attempt only checks the leaf.
+ self.product.qoder_owned_files = {}
+ skill.unlink()
+ skill.parent.chmod(0o775)
+ with self.assertRaisesRegex(AssertionError, 'changed or nonempty collaboration'):
+ qoder.cleanup_context(self.product)
+ self.assertEqual(skill.parent.stat().st_mode & 0o777, 0o775)
+
+ def test_foreign_project_route_observation_is_part_of_the_product_verdict(self):
+ fixture = self.context()
+ upstream = oracle.NativeContextUpstream(self.root)
+ self.addCleanup(upstream.close)
+ qoder.install_project_conflict(fixture, upstream)
+ oracle.assert_preserved(fixture)
+ connection = http.client.HTTPConnection(*upstream.proxy_trap.server.server_address, timeout=3)
+ self.addCleanup(connection.close)
+ connection.request('POST', '/v1/responses', '{}')
+ response = connection.getresponse()
+ response.read()
+ with self.assertRaisesRegex(AssertionError, 'foreign project model route'):
+ oracle.assert_preserved(fixture)
+
+ def test_cleanup_refuses_a_user_edit_to_owned_receipt(self):
+ fixture = self.context()
+ skill = Path(fixture['skills'][0]['skill'])
+ skill.write_text('user edit after acceptance')
+ with self.assertRaisesRegex(AssertionError, 'replaced Qoder fixture material'):
+ qoder.cleanup_context(self.product)
+ self.assertEqual(skill.read_text(), 'user edit after acceptance')
+
+ def test_responses_require_both_native_skill_calls_and_shell_receipts(self):
+ fixture = self.context()
+ results = {}
+ for item in fixture['skills']:
+ action = oracle.decision(fixture, self.body(fixture, results))
+ self.assertEqual((action['name'], action['arguments']), ('Skill', {'skill': item['name']}))
+ results[action['id']] = 'Launching skill: ' + item['name']
+ action = oracle.decision(fixture, self.body(fixture, results))
+ self.assertEqual(action['name'], 'Bash')
+ with self.assertRaisesRegex(AssertionError, 'receipt mismatch'):
+ oracle.decision(fixture, self.body(fixture, {'native_context_execute': 'done'}))
+ receipts = ' '.join(item[key] for item in fixture['skills'] for key in ('contents', 'executed'))
+ with self.assertRaisesRegex(AssertionError, 'prior tool result'):
+ oracle.decision(fixture, self.body(fixture, {'wrong': receipts}, oracle.CONTINUE_PROMPT + receipts))
+ answer = oracle.decision(fixture, self.body(fixture, {'native_context_execute': receipts}, oracle.CONTINUE_PROMPT))
+ self.assertEqual(answer['text'], 'continued-' + fixture['receipt'])
+
+ def test_same_named_shadow_skill_cannot_prove_user_discovery(self):
+ fixture = self.context()
+ body = self.body(fixture, {'native_context_skill_user': 'Launching skill'})
+ body['input'][-1]['content'] = ('Base directory for this skill: ' +
+ str(Path(fixture['skills'][0]['skill']).parent) + '-shadow\n\n' + fixture['skills'][0]['contents'])
+ with self.assertRaisesRegex(AssertionError, 'expected native Skill directory'):
+ oracle.decision(fixture, body)
+
+
+class QoderDelegationOracleTests(QoderFixtureContext, unittest.TestCase):
+ def main_oracle(self):
+ fixture = self.context()
+ fixture.update(main_marker='private-main-marker', plan_id='published-plan',
+ artifact={'path': str(self.project / 'artifact'), 'receipt': 'worker-only-nonce'})
+ skill = self.config / 'skills/hiroute-collaboration/SKILL.md'
+ oracle.write_new(skill, '---\nname: hiroute-collaboration\n---\nUse hiroute worker plans before work.\n')
+ events = [{'state': 'green', 'call_id': 'delegated_artifact'}]
+ main = MainAgentOracle(fixture, skill, Path('/bin/sh'), lambda: events)
+ return fixture, main
+
+ def main_body(self, fixture, main, results=None, actual_directory=True):
+ text = ('Base directory for this skill: ' + str(main.skill.parent) + '\n\n' + main.skill_body
+ if actual_directory else 'Base directory for this skill: ' + str(main.skill.parent) + '-shadow\n\n' + main.skill_body)
+ return {'tools': [{'name': 'Skill'}, {'name': 'Bash'}], 'input': [
+ {'role': 'user', 'content': [{'type': 'input_text', 'text': fixture['main_marker'] + ' hiroute-collaboration'}]},
+ *[{'type': 'function_call_output', 'call_id': key, 'output': value}
+ for key, value in (results or {}).items()],
+ {'role': 'user', 'content': [{'type': 'input_text', 'text': text}]}]}
+
+ @staticmethod
+ def envelope(data):
+ return json.dumps({'schema_version': {'major': 2, 'minor': 0}, 'status': 'succeeded', 'data': data})
+
+ def test_main_oracle_requires_actual_user_skill_before_listing_plans(self):
+ fixture, main = self.main_oracle()
+ action = main.reply({}, self.main_body(fixture, main))
+ self.assertEqual((action['name'], action['arguments']), ('Skill', {'skill': 'hiroute-collaboration'}))
+ results = {'main_skill': 'Launching skill: hiroute-collaboration'}
+ with self.assertRaisesRegex(AssertionError, 'actual installed user Skill'):
+ main.reply({}, self.main_body(fixture, main, results, actual_directory=False))
+ action = main.reply({}, self.main_body(fixture, main, results))
+ self.assertEqual(action['name'], 'Bash')
+ self.assertIn('worker plans --output json', action['arguments']['command'])
+
+ def test_public_result_and_prompt_echo_cannot_replace_worker_disk_artifact(self):
+ fixture, main = self.main_oracle()
+ results = {'main_skill': 'Launching skill', 'main_plans': self.envelope({'plans': [
+ {'agent_plan_id': fixture['plan_id'], 'harness': 'qoder_cli', 'availability': 'ready'}]}),
+ 'main_exec': self.envelope({'task_id': 'real-task', 'run_id': 'real-run', 'run_state': 'succeeded',
+ 'result': fixture['artifact']['receipt']})}
+ with self.assertRaises(FileNotFoundError):
+ main.reply({}, self.main_body(fixture, main, results))
+ self.assertFalse(main.completed)
+ Path(fixture['artifact']['path']).write_text('wrong artifact')
+ with self.assertRaisesRegex(AssertionError, 'disk artifact missing'):
+ main.reply({}, self.main_body(fixture, main, results))
+ Path(fixture['artifact']['path']).write_text(fixture['artifact']['receipt'])
+ reply = main.reply({}, self.main_body(fixture, main, results))
+ self.assertTrue(main.completed)
+ self.assertIn(fixture['artifact']['receipt'], reply['text'])
+
+ def test_wrong_role_endpoint_rejects_before_issuing_a_tool(self):
+ fixture, main = self.main_oracle()
+ body = self.main_body(fixture, main)
+ body['input'][0]['content'][0]['text'] = 'a delegated Worker prompt'
+ with self.assertRaisesRegex(AssertionError, 'Worker request reached the main'):
+ main.reply({}, body)
+
+ def test_accepted_worker_is_waited_publicly_then_result_requires_the_disk_artifact(self):
+ fixture, main = self.main_oracle()
+ accepted = {'task_id': 'real-task', 'run_id': 'real-run', 'run_state': 'accepted'}
+ pending = json.dumps({'schema_version': {'major': 2, 'minor': 0}, 'status': 'succeeded',
+ 'data': accepted, 'next_actions': [{'command_id': 'worker.wait',
+ 'input': {'run_id': 'real-run', 'after_revision': 7}}]})
+ results = {'main_skill': 'Launching skill', 'main_plans': self.envelope({'plans': [
+ {'agent_plan_id': fixture['plan_id'], 'harness': 'qoder_cli', 'availability': 'ready'}]}),
+ 'main_exec': pending}
+ waiting = main.reply({}, self.main_body(fixture, main, results))
+ self.assertEqual(waiting['id'], 'main_wait_1')
+ self.assertIn('worker wait --run real-run --after-revision 7', waiting['arguments']['command'])
+ self.assertFalse(main.completed)
+ results['main_wait_1'] = self.envelope(dict(accepted, run_state='succeeded'))
+ reading = main.reply({}, self.main_body(fixture, main, results))
+ self.assertEqual(reading['id'], 'main_result')
+ self.assertIn('worker result --run real-run', reading['arguments']['command'])
+ results['main_result'] = self.envelope(dict(accepted, run_state='succeeded', result=fixture['artifact']['receipt']))
+ with self.assertRaises(FileNotFoundError):
+ main.reply({}, self.main_body(fixture, main, results))
+ Path(fixture['artifact']['path']).write_text(fixture['artifact']['receipt'])
+ main.reply({}, self.main_body(fixture, main, results))
+ self.assertTrue(main.completed)
+ results['main_wait_1'] = self.envelope(dict(accepted, task_id='different-task', run_state='succeeded'))
+ with self.assertRaisesRegex(AssertionError, 'switched the accepted Worker identity'):
+ main.reply({}, self.main_body(fixture, main, results))
+
+ def test_worker_output_requires_correlated_tool_and_real_artifact(self):
+ fixture, _ = self.main_oracle()
+ body = self.body(fixture, {'delegated_artifact': fixture['artifact']['receipt']})
+ with self.assertRaisesRegex(AssertionError, 'independent disk artifact'):
+ worker_decision(fixture, body)
+ Path(fixture['artifact']['path']).write_text(fixture['artifact']['receipt'])
+ self.assertEqual(worker_decision(fixture, body)['text'], fixture['artifact']['receipt'])
+ body['input'][1]['call_id'] = 'wrong-call-id'
+ self.assertEqual(worker_decision(fixture, body)['kind'], 'tool')
+
+ def test_failed_or_ambiguous_public_envelopes_never_prove_completion(self):
+ good = self.envelope({'task_id': 'task'})
+ for output in (good + good, good.replace('succeeded', 'internal_error'), 'claimed success'):
+ with self.assertRaisesRegex(AssertionError, 'one successful public CLI envelope'):
+ output_envelope(output)
+
+
+class QoderCollaborationCleanupTests(unittest.TestCase):
+ def test_disable_rejects_drift_and_retained_selection_or_restore_reference(self):
+ with tempfile.TemporaryDirectory() as root:
+ skill = Path(root) / 'SKILL.md'
+ for status in ({'state': 'drift'},
+ {'state': 'restored', 'current_selection': {'trigger_mode': 'explicit'}},
+ {'state': 'restored', 'restore_point_ref': 'remaining-owned-reference'}):
+ with self.subTest(status=status), patch.object(collaboration, 'apply_collaboration', return_value=status):
+ with self.assertRaisesRegex(AssertionError, 'did not restore and release'):
+ collaboration.restore_skill(None, 'context', 'restore-ref', None, skill)
+ for status in ({'state': 'restored'},
+ {'state': 'restored', 'current_selection': None, 'restore_point_ref': None}):
+ with patch.object(collaboration, 'apply_collaboration', return_value=status):
+ collaboration.restore_skill(None, 'context', 'restore-ref', None, skill)
+
+ def setup_cleanup(self):
+ calls = []
+ product = SimpleNamespace(process=object(), close=lambda: calls.append('close_product'))
+ source = SimpleNamespace(close=lambda: calls.append('close_source'))
+ report = {'candidate': 'fixture-only', 'state': 'red'}
+ self.addCleanup(patch.stopall)
+ patch.object(collaboration, 'report_failure',
+ side_effect=lambda *_: calls.append('report_and_stop')).start()
+ patch.object(qoder, 'cleanup_context',
+ side_effect=lambda *_: calls.append('cleanup_receipts')).start()
+ return calls, product, source, report
+
+ def test_restore_precedes_failure_report_stop_and_owned_cleanup(self):
+ calls, product, source, report = self.setup_cleanup()
+ collaboration.finish_collaboration(product, [source], lambda: calls.append('restore'),
+ report, 'worker_failed', True)
+ self.assertEqual(calls, ['restore', 'report_and_stop', 'close_product', 'cleanup_receipts', 'close_source'])
+ self.assertEqual(report['restore_after_failure'], {'state': 'succeeded'})
+
+ def test_restore_error_is_reported_without_masking_original_worker_failure(self):
+ calls, product, source, report = self.setup_cleanup()
+ def restore():
+ calls.append('restore')
+ raise ValueError('secondary restore status failure')
+ output = io.StringIO()
+ with redirect_stdout(output), self.assertRaisesRegex(RuntimeError, 'original Worker failure'):
+ try:
+ raise RuntimeError('original Worker failure')
+ finally:
+ collaboration.finish_collaboration(product, [source], restore, report, 'worker_failed', True)
+ recorded = json.loads(output.getvalue())
+ self.assertTrue(recorded['primary_failure_preserved'])
+ self.assertEqual(recorded['failures'], [{'step': 'restore_collaboration', 'error_type': 'ValueError'}])
+ self.assertEqual(calls[-3:], ['close_product', 'cleanup_receipts', 'close_source'])
+
+ def test_owned_cleanup_failure_prevents_success_and_still_closes_sources(self):
+ calls, product, source, report = self.setup_cleanup()
+ with patch.object(qoder, 'cleanup_context', side_effect=AssertionError('changed user material')):
+ with redirect_stdout(io.StringIO()), self.assertRaisesRegex(AssertionError, 'cleanup failed'):
+ collaboration.finish_collaboration(product, [source], None, report, 'completed', False)
+ self.assertEqual(calls[-1], 'close_source')
+
+
+class QoderCompactionOracleTests(unittest.TestCase):
+ def setUp(self):
+ self.fixture = {'compaction_prompt': 'public-worker-marker', 'receipt': 'final-worker-receipt',
+ 'compaction_script': '/private/owned/read-only-receipt.sh'}
+ self.oracle = CompactionOracle(self.fixture, 'frozen-upstream-model')
+
+ def body(self, text, output=None, model='frozen-upstream-model'):
+ return {'model': model, 'input': [
+ *([{'type': 'function_call_output', 'call_id': 'native_compaction_tool', 'output': output}]
+ if output is not None else []),
+ {'role': 'user', 'content': [{'type': 'input_text', 'text': text}]}]}
+
+ def begin(self):
+ first = self.oracle.reply({}, self.body(self.fixture['compaction_prompt']))
+ self.assertEqual((first['request_kind'], first['input_tokens']), ('main', PRESSURE_TOKENS))
+ summary = self.oracle.reply({}, self.body('Please summarize this tool output: ' + self.oracle.tool_receipt))
+ self.assertEqual(summary['request_kind'], 'tool_summary')
+ return summary['text']
+
+ def test_auxiliary_requests_require_independent_summaries_and_correlated_tool_history(self):
+ summary = self.begin()
+ compact = self.oracle.reply({}, self.body('Create a detailed summary for summarization.', summary))
+ self.assertEqual(compact['request_kind'], 'compact')
+ final = self.oracle.reply({}, self.body(compact['text']))
+ self.assertEqual(final['request_kind'], 'main')
+ self.assertIn(self.fixture['receipt'], final['text'])
+ self.assertEqual((self.oracle.main_requests, self.oracle.tool_summary_requests, self.oracle.compact_requests), (2, 1, 1))
+
+ def test_ordinary_main_success_does_not_prove_missing_auxiliary_requests(self):
+ self.oracle.reply({}, self.body(self.fixture['compaction_prompt']))
+ with self.assertRaisesRegex(AssertionError, 'consume the actual native summary'):
+ self.oracle.reply({}, self.body('Continue successfully.'))
+ self.assertEqual((self.oracle.tool_summary_requests, self.oracle.compact_requests), (0, 0))
+
+ def test_wrong_auxiliary_model_and_uncorrelated_summary_fail_closed(self):
+ summary = self.begin()
+ for text in ('Create a detailed summary for summarization.', 'summarize tool output: ' + self.oracle.tool_receipt):
+ with self.assertRaisesRegex(AssertionError, 'frozen upstream model'):
+ self.oracle.reply({}, self.body(text, summary, model='wrong-auxiliary-alias'))
+ with self.assertRaisesRegex(AssertionError, 'correlated summarized tool receipt'):
+ self.oracle.reply({}, self.body('Create a detailed summary for summarization. ' + summary))
+ self.assertEqual(self.oracle.compact_requests, 0)
+
+ def test_native_boundary_and_persisted_summary_are_both_required(self):
+ with tempfile.TemporaryDirectory() as root:
+ path = Path(root) / 'exact-session.jsonl'
+ summary = {'isCompactSummary': True, 'message': self.oracle.summary_receipt}
+ path.write_text(json.dumps(summary) + '\n')
+ with self.assertRaisesRegex(AssertionError, 'automatic compaction boundary'):
+ assert_native_compaction(path, self.oracle.summary_receipt)
+ boundary = {'subtype': 'compact_boundary', 'compactMetadata': {
+ 'trigger': 'auto', 'preTokens': PRESSURE_TOKENS + 12, 'postTokens': 200}}
+ path.write_text(json.dumps(boundary) + '\n')
+ with self.assertRaisesRegex(AssertionError, 'persist the independently issued summary'):
+ assert_native_compaction(path, self.oracle.summary_receipt)
+ path.write_text(json.dumps(boundary) + '\n' + json.dumps(summary) + '\n')
+ self.assertEqual(assert_native_compaction(path, self.oracle.summary_receipt)[0]['trigger'], 'auto')
+
+ def test_pressure_usage_is_present_on_the_real_responses_wire(self):
+ with tempfile.TemporaryDirectory() as root:
+ controls = Path(root)
+ (controls / 'native-context.json').write_text(json.dumps(self.fixture))
+ server = oracle.NativeContextUpstream(controls)
+ server.model = 'frozen-upstream-model'
+ server.reply = self.oracle.reply
+ self.addCleanup(server.close)
+ connection = http.client.HTTPConnection(*server.server.server_address, timeout=3)
+ self.addCleanup(connection.close)
+ connection.request('POST', '/v1/responses', json.dumps(self.body(self.fixture['compaction_prompt'])),
+ {'Authorization': 'Bearer ' + server.token})
+ response = connection.getresponse()
+ frames = [json.loads(line.removeprefix('data: ')) for line in response.read().decode().splitlines()
+ if line.startswith('data: ')]
+ self.assertEqual(response.status, 200)
+ self.assertEqual(frames[-1]['type'], 'response.completed')
+ self.assertEqual(frames[-1]['response']['usage']['input_tokens'], PRESSURE_TOKENS)
+ self.assertEqual(frames[-1]['response']['output'][0]['type'], 'function_call')
+
+
+class PersistedModelFixtureTests(unittest.TestCase):
+ def test_model_settings_do_not_require_native_source_discovery_and_restore_uses_model_state(self):
+ calls = []
+ state = {'state': 'configured', 'restore_point_ref': 'model-restore',
+ 'current_selection': {'mode': 'qoder_additional', 'allowed_plan_ids': ['plan/current']}}
+
+ def preview(command, body):
+ calls.append(command)
+ self.assertIn(command, ('agents connect preview', 'agents restore preview', 'agents connect status'))
+ if command == 'agents connect status':
+ return state
+ return {'applicable': True, 'spec': body['spec'], 'accept_digest': 'accepted',
+ 'dependency_digest': 'bound', 'expected_revisions': {}}
+
+ def cli(command, body):
+ calls.append(command)
+ self.assertIn(command, ('agents connect apply', 'agents restore apply'))
+ return 0, {'data': {'state': 'succeeded'}}
+
+ product = SimpleNamespace(preview=preview, cli=cli)
+ model_product.apply_models(product, model_product.model_spec('context', ['plan/current']), 'configure')
+ self.assertEqual(calls, ['agents connect preview', 'agents connect apply', 'agents connect status'])
+ with self.assertRaisesRegex(AssertionError, 'release its selection/reference'):
+ model_product.restore_models(product, 'context')
+ state.update(state='not_configured', current_selection=None, restore_point_ref=None)
+ with patch.object(model_product, 'settings_status', return_value={'restore_point_ref': 'model-restore'}):
+ with patch.object(model_product, 'apply_models', return_value=({}, state)):
+ model_product.restore_models(product, 'context')
+ for remaining in (
+ {'state': 'restored'}, # Collaboration's terminal state is not a model contract.
+ {'state': 'drift'},
+ {'current_selection': {'mode': 'qoder_additional', 'allowed_plan_ids': ['plan/current']}},
+ {'restore_point_ref': 'remaining-owned-model-reference'},
+ ):
+ with self.subTest(remaining=remaining):
+ restored = dict(state, **remaining)
+ with patch.object(model_product, 'apply_models', return_value=({}, restored)):
+ with self.assertRaisesRegex(AssertionError, 'release its selection/reference'):
+ model_product.restore_models(product, 'context')
+
+ def test_source_attempt_counter_includes_rejected_credentials(self):
+ with tempfile.TemporaryDirectory() as directory:
+ source = oracle.NativeContextUpstream(Path(directory))
+ self.addCleanup(source.close)
+ host, port = source.server.server_address
+ connection = http.client.HTTPConnection(host, port, timeout=2)
+ try:
+ connection.request('POST', '/v1/responses', '{}', {'Authorization': 'Bearer wrong'})
+ response = connection.getresponse()
+ response.read()
+ self.assertEqual(response.status, 401)
+ finally:
+ connection.close()
+ self.assertEqual(source.request_count(), 1)
+ self.assertFalse((Path(directory) / 'native-context-events.jsonl').exists())
+
+ def test_collaboration_check_does_not_require_a_worker_plan(self):
+ revisions = {'fixture-current-revision': 7}
+ captured = []
+ product = SimpleNamespace(
+ control=lambda operation, payload: {'data': {'revisions': revisions}},
+ grant=lambda operation, consent, key: captured.append(consent) or 'bounded-capability',
+ cli=lambda command, capability: (0, {'data': {
+ 'skill_loading': 'proven', 'trusted_cli_execution': 'proven'}}))
+ collaboration.check_collaboration(product, 'no-worker-plan')
+ self.assertEqual(captured[0]['expected_revisions'], revisions)
+
+ def test_model_context_requires_its_own_explicit_roots(self):
+ with tempfile.TemporaryDirectory() as directory:
+ home = Path(directory)
+ config = home / '.qoder'
+ config.mkdir()
+ product = SimpleNamespace(env={})
+ borrowed = {'HIROUTE_QODER_CONTEXT_HOME': str(home), 'HIROUTE_QODER_CONFIG_DIR': str(config)}
+ with patch.dict(os.environ, borrowed, clear=True):
+ with self.assertRaisesRegex(AssertionError, 'MODEL_CONTEXT_HOME'):
+ model_fixture.select_model_context(product)
+ self.assertEqual(product.env, {})
+ dedicated = {'HIROUTE_QODER_MODEL_CONTEXT_HOME': str(home),
+ 'HIROUTE_QODER_MODEL_CONFIG_DIR': str(config)}
+ with patch.dict(os.environ, dedicated), patch.object(Path, 'home', return_value=home):
+ with self.assertRaisesRegex(AssertionError, 'daily HOME'):
+ model_fixture.select_model_context(product)
+ with patch.dict(os.environ, dedicated):
+ self.assertEqual(model_fixture.select_model_context(product), config)
+
+ def test_ordinary_native_command_does_not_hide_persisted_settings(self):
+ product = SimpleNamespace(project=Path('/fixture/project'), env={'QODER_CONFIG_DIR': '/fixture/.qoder'})
+ command = model_fixture.native_command(product, '/installed/qodercli', 'managed/raw-alias', 'input-nonce')
+ self.assertEqual(command[command.index('--model') + 1], 'managed/raw-alias')
+ self.assertNotIn('--settings', command)
+ self.assertNotIn('--setting-sources', command)
+ self.assertFalse(any('TOKEN' in argument or 'apiKey' in argument for argument in command))
+
+ def test_preservation_rejects_unknown_or_default_changes_and_owned_cleanup_refuses_drift(self):
+ with tempfile.TemporaryDirectory() as directory:
+ settings = model_fixture.OwnedModelSettings(Path(directory), 'http://127.0.0.1:1/v1')
+ baseline = settings.read()
+ managed = 'hiroute-main-test'
+ configured = json.loads(json.dumps(baseline))
+ configured['providers'][managed] = {'apiKey': 'synthetic-secret'}
+ settings.write(configured)
+ settings.assert_preserved(managed)
+ for mutate in (
+ lambda value: value['model'].update(name='changed-default'),
+ lambda value: value['providers']['fixture-native'].pop('fixtureUnknownProviderKey'),
+ ):
+ changed = json.loads(json.dumps(configured))
+ mutate(changed)
+ settings.write(changed)
+ with self.assertRaisesRegex(AssertionError, 'native/default/unknown'):
+ settings.assert_preserved(managed)
+ settings.write(configured)
+ with self.assertRaisesRegex(AssertionError, 'managed/drifted'):
+ settings.close()
+ self.assertTrue(settings.path.exists())
+ settings.write(baseline)
+ settings.close()
+ self.assertFalse(settings.path.exists())
+
+ def test_simulated_user_edits_do_not_reserialize_the_managed_provider(self):
+ with tempfile.TemporaryDirectory() as directory:
+ settings = model_fixture.OwnedModelSettings(Path(directory), 'http://127.0.0.1:1/v1')
+ configured = settings.read()
+ provider = {'apiKey': 'synthetic-secret', 'models': [{'model': 'selected'}]}
+ configured['providers']['managed'] = provider
+ settings.path.write_text(json.dumps(configured, separators=(',', ':')))
+ exact_provider = json.dumps(provider, separators=(',', ':'))
+ settings.add_user_edit('managed')
+ settings.select_default(settings.native_default, 'managed/selected')
+ self.assertIn(exact_provider, settings.path.read_text())
+ settings.select_default('managed/selected', settings.native_default)
+ settings.assert_preserved('managed')
+
+ def test_native_result_must_be_success_without_error_and_independent_receipt(self):
+ result = {'type': 'result', 'subtype': 'success', 'is_error': False,
+ 'result': 'independent-output', 'session_id': 'native-session'}
+ self.assertEqual(model_fixture.successful_native_result(json.dumps(result).encode(), 'independent-output'),
+ 'native-session')
+ for update in ({'is_error': True}, {'result': 'input-echo'}, {'session_id': ''}):
+ with self.assertRaises(AssertionError):
+ model_fixture.successful_native_result(json.dumps(dict(result, **update)).encode(), 'independent-output')
+ with self.assertRaisesRegex(AssertionError, 'one native'):
+ model_fixture.successful_native_result((json.dumps(result) + '\n' + json.dumps(result)).encode(), 'independent-output')
+
+ def test_source_oracle_rejects_another_route_and_uses_a_separate_output_nonce(self):
+ expected = model_fixture.PersistedRouteOracle('actual-source-model')
+ prompt = expected.arm('native-request')
+ body = {'model': 'actual-source-model', 'input': prompt}
+ reply = expected.reply({}, body)
+ self.assertNotEqual(reply['text'], prompt)
+ self.assertEqual(expected.calls, ['native-request'])
+ with self.assertRaisesRegex(AssertionError, 'wrong source'):
+ expected.reply({}, dict(body, model='other-source-model'))
+ with self.assertRaisesRegex(AssertionError, 'unplanned'):
+ expected.reply({}, dict(body, input='another task'))
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/scripts/test-test-plan.py b/scripts/test-test-plan.py
index a37c697a..b0cce262 100644
--- a/scripts/test-test-plan.py
+++ b/scripts/test-test-plan.py
@@ -2,6 +2,7 @@
import importlib.util
from pathlib import Path
import unittest
+from unittest import mock
import sys
import json
import subprocess
@@ -13,8 +14,215 @@ spec = importlib.util.spec_from_file_location("test_plan", Path(__file__).with_n
plan = importlib.util.module_from_spec(spec)
spec.loader.exec_module(plan)
+runner_spec = importlib.util.spec_from_file_location("remote_rust", Path(__file__).with_name("remote-rust.py"))
+runner = importlib.util.module_from_spec(runner_spec)
+runner_spec.loader.exec_module(runner)
+
class SelectionTests(unittest.TestCase):
+ def test_worker_contract_alone_requires_feature_enabled_mac_consumers(self):
+ for path in ('crates/application-api/src/worker.rs',
+ 'crates/domain/src/delegation/mod.rs',
+ 'crates/domain/src/delegation/installation.rs'):
+ with self.subTest(path=path):
+ result = plan.select([path])
+ self.assertTrue(result['native_required'])
+ self.assertEqual(len(result['native_checks']), 1)
+ check = result['native_checks'][0]
+ self.assertEqual(check['id'], 'desktop.compile')
+ self.assertEqual(check['platform'], 'macos')
+ self.assertEqual(check['command_template'], [
+ 'python3', 'scripts/validation.py',
+ '--frontend-dist', '<candidate-frontend-dist>', 'desktop', 'run',
+ '--ref', '<pushed-branch-ref>', '--sha', '<candidate-sha>',
+ '--plan', '<feature-plan>', '--phase', 'focused', '--cargo-only', '--',
+ 'cargo', 'check', '--locked', '-p', 'hiroute-desktop',
+ '--features', 'desktop-pilot', '--all-targets'])
+ self.assertEqual(set(check['required_inputs']),
+ {'pushed-branch-ref', 'candidate-sha', 'candidate-frontend-dist',
+ 'feature-plan'})
+ self.assertNotIn(check['command_template'], result['commands'])
+ # Existing backend coverage stays independent of the Mac obligation.
+ self.assertTrue(any('--exclude' in c and 'hiroute-desktop' in c
+ for c in result['commands']))
+
+ def test_native_and_shared_consumer_changes_deduplicate_compile_obligation(self):
+ paths = ['apps/desktop/src-tauri/src/bridge/worker_tasks.rs',
+ 'crates/application-api/src/worker.rs']
+ result = plan.select(paths + paths)
+ self.assertEqual(len(result['native_checks']), 1)
+ self.assertEqual(result['native_checks'][0]['trigger_paths'], sorted(paths))
+
+ def test_unrelated_shared_frontend_and_docs_do_not_require_native_compile(self):
+ for paths in (['crates/domain/src/routing.rs'], ['apps/desktop/src/App.tsx'],
+ ['docs/test-selection.md'], ['crates/diagnostics/src/level.rs'], []):
+ with self.subTest(paths=paths):
+ result = plan.select(paths)
+ self.assertFalse(result['native_required'])
+ self.assertEqual(result['native_checks'], [])
+
+ def test_qoder_product_gate_requires_delegation_and_persisted_models_without_environment(self):
+ # Selection must retain a required gate even on a machine unable to run it.
+ with mock.patch.dict(plan.os.environ, {}, clear=True):
+ result = plan.select(['tools/product-e2e/tests/qoder_delegation.rs'])
+ self.assertEqual(len(result['product_checks']), 1)
+ check = result['product_checks'][0]
+ self.assertEqual(check['harnesses'], ['qoder'])
+ self.assertEqual(check['required_tests'], [
+ 'qoder_main_agent_uses_installed_user_skill_to_delegate_real_work',
+ 'qoder_worker_uses_native_skills_and_continues_the_frozen_task',
+ 'qoder_workers_route_independently_and_cancel_only_owned_work',
+ 'qoder_worker_compaction_keeps_the_frozen_managed_route',
+ 'qoder_main_agent_uses_persisted_additional_model_routes'])
+ self.assertEqual(check['required_environment'], [
+ 'HIROUTE_PRODUCT_CANDIDATE_SHA', 'HIROUTE_WORKER_QODER_BINARY',
+ 'HIROUTE_QODER_CONTEXT_HOME', 'HIROUTE_QODER_CONFIG_DIR',
+ 'HIROUTE_QODER_MODEL_CONTEXT_HOME', 'HIROUTE_QODER_MODEL_CONFIG_DIR'])
+ self.assertEqual(check['missing_environment'], 'fail')
+ self.assertEqual(check['command'], [
+ 'cargo', 'test', '--locked', '-p', 'hiroute-product-e2e', '--test',
+ 'qoder_delegation', '--', '--ignored', '--nocapture', '--test-threads=1'])
+ self.assertFalse(result['native_required'])
+ self.assertFalse(any('--ignored' in command for command in result['commands']))
+
+ def test_qoder_leaf_and_shared_collaboration_changes_select_only_qoder_gate(self):
+ for path in (
+ 'crates/daemon/tests/support/qoder_native_context.py',
+ 'crates/daemon/tests/support/qoder_collaboration_product.py',
+ 'crates/daemon/tests/support/qoder_collaboration_fixture.py',
+ 'crates/daemon/tests/support/qoder_compaction_product.py',
+ 'crates/integrations/src/agents/qoder/probe.rs',
+ 'crates/application/src/agent_connection/qoder_model_journal.rs',
+ 'crates/domain/src/agents/qoder_model.rs',
+ 'crates/daemon/src/control/runtime/qoder_model.rs',
+ 'crates/daemon/src/delegation/profile/qoder.rs',
+ 'crates/daemon/src/control/runtime/settings_facts/qoder.rs',
+ 'crates/daemon/src/control/runtime/settings_facts.rs',
+ 'crates/daemon/src/control/runtime/settings_status.rs',
+ 'crates/daemon/src/control/runtime.rs',
+ 'crates/application/src/control_plane/agent_settings.rs',
+ 'crates/daemon/src/control/runtime/collaboration_installation.rs',
+ 'crates/application/src/agent_connection/settings_input.rs',
+ 'crates/application/src/agent_connection/skill_reference.rs',
+ ):
+ with self.subTest(path=path):
+ result = plan.select([path])
+ self.assertEqual([check['command'][6] for check in result['product_checks']],
+ ['qoder_delegation'])
+ self.assertIn(['python3', 'scripts/test-qoder-product.py'], result['commands'])
+ # Model-specific settings are not consumers of the independent Qoder Skill path.
+ self.assertEqual(plan.select([
+ 'crates/daemon/src/control/runtime/settings_codex_profile.rs',
+ 'crates/daemon/src/control/runtime/native_claude_model.rs',
+ ])['product_checks'], [])
+
+ def test_shared_agent_journey_helper_selects_current_consumers_and_its_ownership_checks(self):
+ result = plan.select(['crates/daemon/tests/support/agent_product_support.py'])
+ self.assertEqual(result['mode'], 'affected')
+ self.assertEqual([check['command'][6] for check in result['product_checks']], ['qoder_delegation'])
+ self.assertIn(['python3', 'scripts/test-agent-product-support.py'], result['commands'])
+ tooling = plan.select(['scripts/test-agent-product-support.py'])
+ self.assertEqual(tooling['product_checks'], [])
+ self.assertIn(['python3', 'scripts/test-agent-product-support.py'], tooling['commands'])
+
+ def test_shared_native_context_fixture_selects_both_real_consumer_targets(self):
+ for path in ('crates/daemon/tests/support/native_context_product.py',
+ 'crates/daemon/tests/support/native_context_fixture.py',
+ 'crates/daemon/tests/support/native_context_boundaries.py'):
+ with self.subTest(path=path):
+ result = plan.select([path])
+ self.assertEqual(result['mode'], 'affected')
+ self.assertEqual({check['command'][6] for check in result['product_checks']},
+ {'worker_native_context', 'qoder_delegation'})
+
+ def test_qoder_production_gates_preserve_ordinary_owner_checks_and_deduplicate(self):
+ result = plan.select(['crates/integrations/src/agents/qoder.rs',
+ 'crates/daemon/src/control/runtime/settings_facts/qoder.rs',
+ 'crates/daemon/tests/support/qoder_native_context.py'])
+ self.assertEqual(result['groups'], ['daemon', 'integrations'])
+ self.assertEqual([check['command'][6] for check in result['product_checks']],
+ ['qoder_delegation'])
+ self.assertTrue(any('smoke_cli' in command for command in result['commands']))
+ shared = plan.select(['crates/daemon/tests/support/publication_product.py'])
+ self.assertEqual(shared['mode'], 'affected')
+ self.assertEqual({check['command'][6] for check in shared['product_checks']},
+ plan.OPT_IN_WORKER_TARGETS)
+ self.assertEqual(plan.select(['scripts/test-qoder-product.py'])['product_checks'], [])
+
+ def test_qoder_guide_and_settings_docs_do_not_expand_product_scope(self):
+ result = plan.select(['tools/product-e2e/tests/QODER_DELEGATION.md',
+ 'docs/test-selection.md'])
+ self.assertFalse(result['rust'])
+ self.assertFalse(result['frontend'])
+ self.assertEqual(result['product_checks'], [])
+
+ def test_worker_context_changes_require_explicit_real_harness_cases(self):
+ for path in ('crates/daemon/src/delegation/profile/mod.rs',
+ 'crates/daemon/src/delegation/executor/resume.rs',
+ 'tools/product-e2e/tests/worker_native_context.rs'):
+ with self.subTest(path=path):
+ result = plan.select([path])
+ required = result['product_checks']
+ self.assertEqual(len(required), 1 if path.endswith('worker_native_context.rs') else 4)
+ self.assertEqual(required[0]['id'], 'worker.native-context')
+ self.assertEqual(required[0]['harnesses'], ['codex', 'claude'])
+ self.assertIn('--ignored', required[0]['command'])
+ self.assertEqual(len(required[0]['business_cases']), 6)
+ self.assertEqual(required[0]['automated_cases'], [
+ 'worker.context.native-skills', 'worker.context.exact-continue',
+ 'worker.context.concurrent-routing', 'worker.context.cancel-owned-work'])
+ self.assertIn('native Desktop', required[0]['evidence_limit'])
+
+ def test_changed_worker_journey_is_explicitly_selected(self):
+ for target in plan.OPT_IN_WORKER_TARGETS:
+ checks = plan.select(['tools/product-e2e/tests/' + target + '.rs'])['product_checks']
+ self.assertEqual(len(checks), 1)
+ self.assertEqual(checks[0]['command'][6], target)
+ self.assertIn('--ignored', checks[0]['command'])
+ shared = plan.select(['tools/product-e2e/tests/worker_product_support/mod.rs'])
+ self.assertEqual({check['command'][6] for check in shared['product_checks']},
+ plan.OPT_IN_WORKER_TARGETS)
+
+ def test_native_bootstrap_has_its_own_executable_check(self):
+ command = ['node', '--test', plan.WORKER_BOOTSTRAP_TEST]
+ for path in ('crates/daemon/src/delegation/profile/mod.rs',
+ 'crates/daemon/src/delegation/profile/claude_adapter_bootstrap.mjs',
+ plan.WORKER_BOOTSTRAP_TEST):
+ self.assertIn(command, plan.select([path])['commands'])
+ self.assertIn(command, plan.select([], full=True)['commands'])
+ selected = plan.select(['crates/daemon/src/delegation/profile/mod.rs'])
+ self.assertIn(command, plan.integration_preflight(selected)['commands'])
+
+ def test_worker_fixture_oracle_has_a_tooling_only_entry(self):
+ result = plan.select(sorted(plan.WORKER_FIXTURE_TOOLING))
+ self.assertFalse(result['rust'])
+ self.assertFalse(result['frontend'])
+ self.assertIn(['python3', 'scripts/test-native-context-product.py'], result['commands'])
+ self.assertIn(['python3', 'scripts/test-native-context-boundaries.py'], result['commands'])
+
+ def test_worker_support_selects_all_registered_consumers_without_full_workspace(self):
+ result = plan.select(['tools/product-e2e/tests/worker_product_support/mod.rs'])
+ self.assertEqual(result['mode'], 'affected')
+ self.assertFalse(result['frontend'])
+ targets = plan.e2e_consumers('tools/product-e2e/tests/worker_product_support/mod.rs')
+ self.assertEqual({target for _, target in targets},
+ {'worker_delegation', 'worker_read', 'worker_native_context', 'qoder_delegation'})
+ self.assertIn(['cargo', 'clippy', '--locked', '-p', 'hiroute-product-e2e',
+ '--all-targets', '--all-features', '--', '-D', 'warnings'], result['commands'])
+ self.assertFalse(any(command[:2] == ['cargo', 'test'] for command in result['commands']))
+ # Ignored-only targets must not become misleading zero-selected test commands.
+ self.assertFalse(any('--ignored' in command for command in result['commands']))
+
+ def test_native_context_guide_is_navigation_only(self):
+ result = plan.select(['tools/product-e2e/tests/WORKER_NATIVE_CONTEXT.md'])
+ self.assertFalse(result['rust'])
+ self.assertFalse(result['frontend'])
+
+ def test_unrelated_and_docs_changes_do_not_request_real_agents(self):
+ for path in ('docs/code-map/worker-context.md', 'crates/diagnostics/src/level.rs',
+ 'apps/desktop/src/product/Models.tsx'):
+ self.assertEqual(plan.select([path])['product_checks'], [])
+
def test_validation_tooling_selects_runner_consumers_without_product_builds(self):
result = plan.select(['scripts/validation.py', 'scripts/local-rust.py', 'scripts/pilot-builds.py',
'scripts/desktop-pilot.py', 'docs/validation-routing.md'])
@@ -104,6 +312,23 @@ class SelectionTests(unittest.TestCase):
self.assertTrue(any("--no-default-features" in command for command in result["commands"]))
self.assertIn("hiroute-e2e", result["commands"][2])
+ def test_full_and_gateway_contract_checks_are_admitted_by_the_managed_runner(self):
+ for paths, full in [([], True), (["crates/gateway/src/lib.rs"], False)]:
+ with self.subTest(paths=paths, full=full):
+ commands = plan.select(paths, full=full)["commands"]
+ for command in commands:
+ if command[0] == "cargo":
+ # local-rust delegates to this same validator before starting Cargo.
+ runner.validate("refs/heads/codex/selected-contract-check", "a" * 40, command)
+ self.assertIn([
+ "cargo", "test", "--locked", "-p", "hiroute-e2e", "--test", "case_shards",
+ "core_routing_validation_covers_the_complete_unsharded_scenario",
+ "--", "--exact", "--nocapture",
+ ], commands)
+ with self.assertRaisesRegex(ValueError, "Expected cargo"):
+ runner.validate("refs/heads/codex/selected-contract-check", "a" * 40,
+ ["cargo", "run", "--locked", "-p", "hiroute-e2e", "--", "validate"])
+
def test_full_does_not_repeat_product_smoke(self):
result = plan.select([], full=True)
self.assertTrue(result["frontend"])
@@ -420,6 +645,19 @@ class RevisionPlans(unittest.TestCase):
self.assertTrue(value['iteration']['diagnostic_only'])
self.assertEqual(value['iteration']['since'], self.shared)
+ def test_native_consumer_obligation_survives_docs_only_iteration(self):
+ self.write('crates/application-api/src/worker.rs', 'changed public contract')
+ checkpoint = self.commit('worker contract')
+ self.write('docs/testing.md', 'navigation repair')
+ self.commit('docs')
+ result = self.invoke('--base', self.base, '--since', checkpoint, '--integration')
+ self.assertEqual(result.returncode, 0, result.stderr)
+ value = json.loads(result.stdout)
+ self.assertTrue(value['native_required'])
+ self.assertEqual([check['id'] for check in value['native_checks']], ['desktop.compile'])
+ self.assertEqual(value['iteration']['native_checks'], [])
+ self.assertEqual(value['integration']['scope'], 'iteration')
+
def test_rename_staged_unstaged_and_untracked_are_included(self):
old = 'tools/product-e2e/tests/routing_plans.rs'
self.write(old, 'old')
diff --git a/scripts/test-validation.py b/scripts/test-validation.py
index b9feab5a..ca028813 100644
--- a/scripts/test-validation.py
+++ b/scripts/test-validation.py
@@ -105,6 +105,91 @@ class Routing(unittest.TestCase):
self.assertEqual(payload['name'], 'desktop')
self.assertEqual(set(payload['bundle']), {'pilot-builds.py', 'local-rust.py', 'remote-rust.py', 'desktop-pilot.py', 'validation-report.py'})
+ def test_ssh_pilot_and_build_execute_same_caller_driver_instead_of_host_checkout(self):
+ caller = self.root / 'caller'
+ remote = self.root / 'remote-checkout'
+ account = self.root / 'remote-home'
+ for directory in (caller / 'scripts', remote / 'scripts', account):
+ directory.mkdir(parents=True)
+ events = self.root / 'driver-events.jsonl'
+ driver = f'''import json, sys
+from pathlib import Path
+def record(action):
+ with Path({str(events)!r}).open('a') as output:
+ output.write(json.dumps(dict(origin='caller', driver=__file__, action=action, arguments=sys.argv[1:])) + '\\n')
+if __name__ == '__main__':
+ record(sys.argv[1])
+'''
+ build_driver = '''import importlib.util, sys
+from pathlib import Path
+spec = importlib.util.spec_from_file_location('pilot', Path(__file__).with_name('desktop-pilot.py'))
+pilot = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(pilot)
+pilot.record('build:' + sys.argv[1])
+'''
+ (caller / 'scripts/desktop-pilot.py').write_text(driver)
+ (caller / 'scripts/pilot-builds.py').write_text(build_driver)
+ for name in ('local-rust.py', 'remote-rust.py', 'validation-report.py'):
+ (caller / 'scripts' / name).write_text('# unused fixture dependency\n')
+ (caller / 'scripts/validation-host.py').write_text(Path(host.__file__).read_text())
+ stale_driver = "raise SystemExit('stale host checkout driver was executed')\n"
+ for name in ('desktop-pilot.py', 'pilot-builds.py'):
+ (remote / 'scripts' / name).write_text(stale_driver)
+ target = {'transport': 'ssh', 'host': 'fixture-mac', 'repo': str(remote)}
+ real_run = subprocess.run
+ transport_calls = []
+
+ def ssh_or_child(argv, **kwargs):
+ if argv[0] != 'ssh':
+ return real_run(argv, **kwargs)
+ payload = json.loads(kwargs['input'])
+ transport_calls.append(payload)
+ with patch.object(host.sys, 'platform', 'darwin'), \
+ patch.object(host.Path, 'home', return_value=account), \
+ patch.object(host, 'gui_session', return_value={'available': True}):
+ return subprocess.CompletedProcess(argv, host.execute(payload))
+
+ actions = [('pilot-build', ['status', '--lease', 'a' * 32])]
+ actions += [('pilot', ['start', '--app', '/private/tmp/hiroute-desktop', '--build-run', 'b' * 32])]
+ actions += [('pilot', [action, '--session', '/private/tmp/owned-session'])
+ for action in ('status', 'stop')]
+ actions += [('pilot', ['config', '--frontend-dist', '/private/tmp/frontend'])]
+ with patch.object(m, 'REPO', caller), patch.object(m.subprocess, 'run', side_effect=ssh_or_child):
+ for action, arguments in actions:
+ self.assertEqual(m.dispatch({'desktop': target}, action, arguments), 0)
+ records = [json.loads(line) for line in events.read_text().splitlines()]
+ self.assertEqual([record['action'] for record in records], ['build:status', 'start', 'status', 'stop', 'config'])
+ self.assertEqual({record['origin'] for record in records}, {'caller'})
+ self.assertEqual(len({record['driver'] for record in records}), 1)
+ bundled_driver = Path(records[0]['driver'])
+ self.assertTrue(bundled_driver.is_relative_to(account / '.cache/hiroute/validation-tools'))
+ self.assertEqual(bundled_driver.read_text(), driver)
+ self.assertEqual(records[-1]['arguments'][1:3], ['--repo', str(remote.resolve())])
+ self.assertTrue(all(payload['bundle'] == transport_calls[0]['bundle'] for payload in transport_calls))
+ self.assertEqual((remote / 'scripts/desktop-pilot.py').read_text(), stale_driver)
+
+ def test_pilot_actions_without_complete_bundle_fail_without_host_driver_fallback(self):
+ for action in ('pilot', 'pilot-build'):
+ for bundle in (None, {'desktop-pilot.py': '# incomplete\n'}):
+ p = self.payload(action, ['status'])
+ p.update(name='desktop', bundle=bundle)
+ with self.subTest(action=action, bundle=bundle), \
+ patch.object(host.sys, 'platform', 'darwin'), \
+ patch.object(host.subprocess, 'run') as run:
+ with self.assertRaisesRegex(ValueError, 'Incomplete Pilot tooling bundle'):
+ host.execute(p)
+ run.assert_not_called()
+
+ def test_pilot_config_repository_comes_only_from_execution_target(self):
+ for override in (['--repo', '/different/repo'], ['--repo=/different/repo']):
+ p = self.payload('pilot', ['config', *override, '--frontend-dist', '/frontend'])
+ p['name'] = 'desktop'
+ with patch.object(host.sys, 'platform', 'darwin'), \
+ patch.object(host.subprocess, 'run') as run:
+ with self.assertRaisesRegex(ValueError, 'Configure repo in validation.json'):
+ host.execute(p)
+ run.assert_not_called()
+
def test_bundle_is_content_addressed_immutable_and_private(self):
sources = {name: '# fixture\n' for name in ('pilot-builds.py', 'local-rust.py', 'remote-rust.py', 'desktop-pilot.py', 'validation-report.py')}
with patch.object(host.Path, 'home', return_value=self.root):
diff --git a/scripts/validation-host.py b/scripts/validation-host.py
index bf3cdce4..3842f8f8 100644
--- a/scripts/validation-host.py
+++ b/scripts/validation-host.py
@@ -157,7 +157,12 @@ def execute(payload):
raise ValueError("pilot requires config/start/status/stop")
if arguments[0] == "start" and not gui_session()["available"]:
raise ValueError("Desktop GUI login session unavailable for the execution user")
- argv = [sys.executable, str(repo / "scripts/desktop-pilot.py"), *arguments]
+ if arguments[0] == "config":
+ if any(a == "--repo" or a.startswith("--repo=") for a in arguments):
+ raise ValueError("Configure repo in validation.json")
+ arguments[1:1] = ["--repo", str(repo)]
+ bundle = tooling_bundle(payload.get("bundle"))
+ argv = [sys.executable, str(bundle / "desktop-pilot.py"), *arguments]
elif action == "pilot-cli":
if "--socket" not in arguments and not any(a.startswith("--socket=") for a in arguments):
raise ValueError("pilot-cli requires an explicit execution-host --socket")
diff --git a/scripts/validation.py b/scripts/validation.py
index 98f80576..e188c9f3 100644
--- a/scripts/validation.py
+++ b/scripts/validation.py
@@ -106,7 +106,7 @@ def dispatch(targets, action, arguments, frontend_dist=None, dry_run=False):
if dry_run:
print(json.dumps(payload, indent=2))
return 0
- if action == "pilot-build":
+ if action in ("pilot", "pilot-build"):
payload["bundle"] = {name: (REPO / "scripts" / name).read_text() for name in
("pilot-builds.py", "local-rust.py", "remote-rust.py", "desktop-pilot.py", "validation-report.py")}
if target["transport"] == "local":
diff --git a/tools/e2e-harness/SHARDING.md b/tools/e2e-harness/SHARDING.md
index 3b38f6a7..714880a1 100644
--- a/tools/e2e-harness/SHARDING.md
+++ b/tools/e2e-harness/SHARDING.md
@@ -15,6 +15,11 @@ cargo run --locked -p hiroute-e2e -- validate \
--profile e2e/profiles/local-process.json
```
+Managed validation uses the complete CLI definition test through `cargo test`, as
+shown in [test selection](../../docs/test-selection.md#keep-these-quality-boundaries).
+It checks all 17 steps and 10 declared shards without choosing a case or starting the
+business processes. Passing definition validation is not production smoke evidence.
+
Give each isolated black-box process a unique result file:
```sh
diff --git a/tools/e2e-harness/SHARDING.zh-CN.md b/tools/e2e-harness/SHARDING.zh-CN.md
index f071b3a9..961fce93 100644
--- a/tools/e2e-harness/SHARDING.zh-CN.md
+++ b/tools/e2e-harness/SHARDING.zh-CN.md
@@ -14,6 +14,10 @@ cargo run --locked -p hiroute-e2e -- validate \
--profile e2e/profiles/local-process.json
```
+受管验证通过 `cargo test` 执行完整的 CLI 定义测试,命令见
+[测试选择](../../docs/test-selection.md#keep-these-quality-boundaries)。它不选择分片,
+检查全部 17 个步骤、10 个声明分片,但不启动业务进程。定义校验通过不代表生产 smoke 通过。
+
为一个分片运行独立的黑盒进程时,给每次运行唯一结果文件:
```sh
diff --git a/tools/e2e-harness/tests/case_shards.rs b/tools/e2e-harness/tests/case_shards.rs
index 6eaa50e5..bcfd824d 100644
--- a/tools/e2e-harness/tests/case_shards.rs
+++ b/tools/e2e-harness/tests/case_shards.rs
@@ -8,10 +8,71 @@ fn root() -> PathBuf {
fn validate(arguments: &[&str]) -> std::process::Output {
Command::new(env!("CARGO_BIN_EXE_hiroute-e2e"))
.args(arguments)
+ .env_remove("HIROUTE_E2E_CPA_BIN")
+ .env_remove("HIROUTE_E2E_SUT_BIN")
.output()
.unwrap()
}
+#[test]
+fn core_routing_validation_covers_the_complete_unsharded_scenario() {
+ let root = root();
+ let scenario = root.join("e2e/scenarios/core-routing.json");
+ let profile = root.join("e2e/profiles/local-process.json");
+ let declared: Value = serde_json::from_slice(&std::fs::read(&scenario).unwrap()).unwrap();
+ let output = validate(&[
+ "validate",
+ "--scenario",
+ scenario.to_str().unwrap(),
+ "--profile",
+ profile.to_str().unwrap(),
+ ]);
+ assert!(
+ output.status.success(),
+ "{}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ let report: Value = serde_json::from_slice(&output.stdout).unwrap();
+ assert_eq!(report["schema_version"], 1);
+ assert_eq!(report["scenario"], "dual-protocol-rule-routing");
+ assert_eq!(report["profile"], "local-process");
+ assert!(report.get("selected_case").is_none());
+ assert_eq!(report["steps"], 17);
+ assert_eq!(report["case_shards"].as_array().unwrap().len(), 10);
+ assert_eq!(report["case_shards"], declared["case_shards"]);
+ assert_eq!(
+ report["protocols"],
+ serde_json::json!(["messages", "responses"])
+ );
+ assert_eq!(
+ report["sources"],
+ serde_json::json!(["claude-compatible", "codex-chatgpt"])
+ );
+ assert_eq!(
+ report["executable_environment_required"],
+ serde_json::json!(["HIROUTE_E2E_CPA_BIN", "HIROUTE_E2E_SUT_BIN"])
+ );
+
+ // A semantic error in the final step must not disappear behind a default shard
+ // or successful JSON parsing. Validation never starts CPA or SUT processes.
+ let mut invalid = declared;
+ invalid["steps"].as_array_mut().unwrap().last_mut().unwrap()["request"]["stream"] =
+ Value::Bool(false);
+ let temporary = tempfile::tempdir().unwrap();
+ let invalid_path = temporary.path().join("invalid-core-routing.json");
+ std::fs::write(&invalid_path, serde_json::to_vec(&invalid).unwrap()).unwrap();
+ let rejected = validate(&[
+ "validate",
+ "--scenario",
+ invalid_path.to_str().unwrap(),
+ "--profile",
+ profile.to_str().unwrap(),
+ ]);
+ assert!(!rejected.status.success());
+ assert!(String::from_utf8_lossy(&rejected.stderr).contains("streaming response"));
+ println!("{}", String::from_utf8_lossy(&output.stdout));
+}
+
#[test]
fn generic_case_validation_selects_one_declared_partition() {
let root = root();
diff --git a/tools/e2e-harness/tests/p0_gateway_request_authority.rs b/tools/e2e-harness/tests/p0_gateway_request_authority.rs
index 6f73e9e9..9ad47a57 100644
--- a/tools/e2e-harness/tests/p0_gateway_request_authority.rs
+++ b/tools/e2e-harness/tests/p0_gateway_request_authority.rs
@@ -223,6 +223,24 @@ fn production_hirouted_wire_authority_catalog_deadline_and_actual_restart() {
);
}
+ // Native Qoder cannot send a custom token header. Its dedicated local entry
+ // still authenticates publication grants, never account or run credentials.
+ let qoder_responses = format!("{}/responses", hiroute_domain::QODER_MODEL_BASE_PATH);
+ for headers in [
+ "Authorization: Bearer native-account-token\r\n",
+ "Authorization: Bearer hr_run_model_fixture\r\n",
+ "Authorization: Bearer wire-token\r\nAuthorization: Bearer wire-token\r\n",
+ "Authorization: Bearer wire-token\r\nX-HiRoute-Token: wire-token\r\n",
+ ] {
+ let rejected =
+ header_only_request(address, &qoder_responses, headers, Duration::from_secs(1));
+ assert_json_response(&rejected, 401);
+ assert_eq!(
+ serde_json::from_slice::<Value>(&rejected.body).unwrap()["code"],
+ "GATEWAY_GRANT_UNAUTHORIZED"
+ );
+ }
+
let models = request(
address,
"GET",
@@ -248,6 +266,17 @@ fn production_hirouted_wire_authority_catalog_deadline_and_actual_restart() {
assert_eq!(unchanged.headers["etag"], etag);
assert!(unchanged.body.is_empty());
+ let qoder_models = request(
+ address,
+ "GET",
+ &format!("{}/models", hiroute_domain::QODER_MODEL_BASE_PATH),
+ &[("Authorization", "Bearer wire-token")],
+ b"",
+ );
+ assert_json_response(&qoder_models, 200);
+ assert_eq!(qoder_models.body, models.body);
+ assert_eq!(qoder_models.headers["etag"], etag);
+
for (path, model, header, status, code) in [
(
"/v1/responses",
@@ -277,6 +306,20 @@ fn production_hirouted_wire_authority_catalog_deadline_and_actual_restart() {
422,
"AGENT_PROTOCOL_UNSUPPORTED",
),
+ (
+ qoder_responses.as_str(),
+ "wire-private",
+ ("Authorization", "Bearer wire-token"),
+ 404,
+ "AGENT_MODEL_NOT_GRANTED",
+ ),
+ (
+ qoder_responses.as_str(),
+ "wire-deep",
+ ("Authorization", "Bearer wire-messages-token"),
+ 422,
+ "AGENT_PROTOCOL_UNSUPPORTED",
+ ),
] {
let body = serde_json::to_vec(&json!({"model": model})).unwrap();
let response = request(address, "POST", path, &[header], &body);
@@ -311,6 +354,27 @@ fn production_hirouted_wire_authority_catalog_deadline_and_actual_restart() {
assert_json_response(&accepted, 200);
assert_response_text(&accepted, "wire-fast", "wire-provider", "ok");
+ let qoder_provider = serve_one_tls_json_response(
+ provider.try_clone().unwrap(),
+ "Bearer wire-provider-secret-1",
+ provider_response("qoder-provider", "native-qoder-ok"),
+ );
+ let qoder_accepted = request(
+ address,
+ "POST",
+ &qoder_responses,
+ &[("Authorization", "Bearer wire-token")],
+ br#"{"model":"wire-fast","input":"ordinary Qoder request"}"#,
+ );
+ qoder_provider.join().unwrap();
+ assert_json_response(&qoder_accepted, 200);
+ assert_response_text(
+ &qoder_accepted,
+ "wire-fast",
+ "qoder-provider",
+ "native-qoder-ok",
+ );
+
let selector_started = Instant::now();
let timed_out = trickle_request(address, Duration::from_secs(3));
assert!(
diff --git a/tools/product-e2e/src/smoke/control.rs b/tools/product-e2e/src/smoke/control.rs
index dc76747f..f5b38fe6 100644
--- a/tools/product-e2e/src/smoke/control.rs
+++ b/tools/product-e2e/src/smoke/control.rs
@@ -350,14 +350,34 @@ pub(super) fn discover(ctx: &mut Context<'_>) -> Result<()> {
let agents = result["data"]["agents"]
.as_array()
.ok_or(super::SmokeError("agent_discovery_missing"))?;
+ let agent_ids = agents
+ .iter()
+ .map(|agent| {
+ agent["agent_id"]
+ .as_str()
+ .ok_or(super::SmokeError("agent_discovery_mismatch"))
+ })
+ .collect::<Result<std::collections::BTreeSet<_>>>()?;
require(
result["status"] == "succeeded"
- && agents.len() == 2
+ && agent_ids.len() == agents.len()
+ && [
+ "agent_codex_default",
+ "agent_claude_default",
+ "agent_qoder_default",
+ ]
+ .iter()
+ .all(|id| agent_ids.contains(id))
&& agents.iter().any(|a| {
a["agent_id"] == "agent_claude_default"
&& a["supported"] == true
&& a["registered_configuration"]["connection_option_id"]
== "zhipu.coding-plan.cn.v1"
+ })
+ && agents.iter().any(|a| {
+ a["agent_id"] == "agent_qoder_default"
+ && a["registered_configuration"].is_null()
+ && a["discovered_credential"].is_null()
}),
"agent_discovery_mismatch",
)?;
diff --git a/tools/product-e2e/tests/QODER_DELEGATION.md b/tools/product-e2e/tests/QODER_DELEGATION.md
new file mode 100644
index 00000000..6e3fea83
--- /dev/null
+++ b/tools/product-e2e/tests/QODER_DELEGATION.md
@@ -0,0 +1,275 @@
+# Qoder model and task routing acceptance
+
+The [Qoder target](qoder_delegation.rs) exercises five distinct product journeys.
+It is explicitly opt-in; the existing Codex/Claude target keeps its original
+installation requirements. A missing CLI, login, case or result is a failed or
+not-executed prerequisite, never a passing skipped case.
+
+## Run contract
+
+Read this table before selecting the native context or starting a fixture. The
+sections below give the precise inputs, ownership guards and required outcomes.
+
+| Journey scope | Inputs and write scope | Restore/cleanup owner and evidence limit |
+| --- | --- | --- |
+| Main-Agent, Worker core, auxiliary routes and cancellation | [Explicit CLI, candidate and normally logged-in context](#select-the-native-context-explicitly). HiRoute storage, workspaces and submission receipts are private; only recorded test receipt Skills and the product-installed collaboration Skill enter the chosen native config. Existing user settings are preserved. | The [Qoder context leaf](../../../crates/daemon/tests/support/qoder_native_context.py) removes only its unchanged receipt files and owned empty Skill directory; the [collaboration journey](../../../crates/daemon/tests/support/qoder_collaboration_product.py) requests production Skill Restore before service stop. Login and native history remain native-client-owned. These are headless paths, not Desktop UI proof. |
+| Persisted additional model routes | A [dedicated, normally logged-in MODEL context](#persisted-additional-model-routes), separate from daily HOME. The [model settings leaf](../../../crates/daemon/tests/support/qoder_model_fixture.py) writes a synthetic settings baseline; production Apply writes its managed provider and Skill. | The [model journey](../../../crates/daemon/tests/support/qoder_model_product.py) requests production Restore while daemon/sources remain alive; the leaf restores original settings only after its baseline/ownership guard passes. Neither owner deletes login or history. Ordinary saved-settings startup and bounded Live checks are separate evidence. |
+
+For settings preparation, follow the existing [internal bootstrap boundary](../../../docs/code-map/testing.md#what-each-layer-proves).
+Mac UI acceptance uses its separately owned managed Desktop/Pilot session;
+that session's owner restores through the UI, retains evidence and stops only its
+owned processes. Do not run a headless fixture against that live session's settings.
+Required missing outcomes fail; [cheap oracle checks](#cheap-oracle-checks) do not
+start the product or establish native support.
+
+## Product journeys
+
+| Product journey | Executable entry and decisive observations |
+| --- | --- |
+| Enable task routing and delegate from the real main Agent | [Main-Agent journey](../../../crates/daemon/tests/support/qoder_collaboration_product.py): discover the installation, perform the native capability check, apply collaboration-only settings, check the actual installed user Skill, then run native Qoder. Its `Skill` tool must load the exact user directory and body; its `Bash` tool executes the trusted public `hiroute worker plans` and `worker exec`. The separate Worker source requires real user/project Skill receipts and a disk artifact before returning success. Disable uses the current public restore reference and removes only the product-owned Skill. |
+| Continue a Worker in its original context | [Shared core](../../../crates/daemon/tests/support/native_context_product.py): real user/project Skill calls and shell receipts; immediate Continue; daemon restart after replacing the Plan route and current native context; same exact native session, original route and prior correlated tool history; replay sends no request. Unsupported restricted policies fail before model/tool side effects. |
+| Keep native tool summaries and automatic compaction on the managed route | [Auxiliary-route journey](../../../crates/daemon/tests/support/qoder_compaction_product.py): a real public Worker runs an owned read-only Bash receipt. A synthetic high-usage response triggers Qoder’s actual tool-summary and compaction requests. Each is classified by its native request content and independently issued receipt, then the main request must consume both receipts. Exact native history must contain an automatic compaction boundary and persisted summary; Continue loads that same compacted session. |
+| Run neighboring tasks and cancel only one | [Shared boundary](../../../crates/daemon/tests/support/native_context_boundaries.py): simultaneous tasks have distinct sources, models and native IDs; cancellation stops the target's real child and heartbeat while its neighbor remains live and succeeds. Temporarily withholding only the exact test session's transcript must not produce a replacement session or prompt. |
+| Select additional models from persisted user settings | [Persisted-model journey](../../../crates/daemon/tests/support/qoder_model_product.py): save two Plan routes, start ordinary Qoder with each saved selector, restart the daemon and invoke again, then perform the production Live check. Rotate the connection token, preserve independent Skill/model Restore, and refuse removing a route referenced by the native default. Uses a separate writable test context. |
+
+Settings setup/preview/apply/check use the existing `Product.cli` notation for
+production internal Local Control. They are not proof of the standalone public
+settings CLI. The actual public CLI acceptance here is the native main Agent
+executing `worker plans`, `worker exec`, and any necessary `worker wait`/`worker result`.
+An exec response may report accepted or running after a bounded wait. The native
+main Agent follows the response's exact wait cursor until a terminal state, then
+reads the result for that same task/run. Acceptance alone cannot prove completion;
+the independently checked Worker artifact remains required.
+
+The main-Agent fixture has independent Responses endpoints and credentials for the
+main Agent and the Worker. The main Agent's model is a temporary test input, not a
+HiRoute-managed Qoder model connection. No Qoder model scan, import, subscription
+or catalog call is needed. Native `Skill` launch receipts alone do not prove which
+file loaded: the oracle also requires Qoder's actual directory/body expansion.
+The private project has a conflicting default/core model route to a separate
+foreign loopback trap. Worker success requires zero requests there and unchanged
+project settings. The raw-native negative preflight must first show that this
+conflict actually reaches the trap without the HiRoute overlay; schema inspection
+alone is not that evidence.
+
+Model self-report, prompt echo, an uncorrelated tool result, or a successful public
+result without the independent Worker artifact cannot satisfy the journey.
+
+## Select the native context explicitly
+
+Set these values before the managed exact-candidate run:
+
+- `HIROUTE_PRODUCT_CANDIDATE_SHA`: the full committed candidate SHA.
+- `HIROUTE_WORKER_QODER_BINARY`: an absolute path to the selected native CLI.
+- `HIROUTE_QODER_CONTEXT_HOME`: an existing, explicitly chosen native HOME.
+- `HIROUTE_QODER_CONFIG_DIR`: its explicitly chosen existing Qoder config root.
+
+The context must have completed Qoder's normal login. An empty root with a BYOK
+fixture can still fail native session creation; do not copy authentication or
+silently fall back to the daily HOME. The Product storage/runtime/workspace remain
+separate and private. The fixture never deletes the selected native root, reads
+an auth file, or rewrites user provider/model settings. It adds unique receipt
+Skills and removes only its recorded unchanged files. Native authentication may
+refresh its own state; unchanged user settings and ownership are the assertions,
+not zero writes across all HOME.
+
+Keep login, native Provider access, collaboration checks and completed delegation
+as separate observations. On the tested macOS Qoder CLI 1.1.65 installation, a
+normally logged-in context reported `allow_byok=0` yet reached the controlled
+Provider with its selected model and credential, and passed the real Desktop
+collaboration check. Neither an account label nor this status flag alone proves
+support or refusal. Use actual native/product behavior and record the selected
+context and CLI version; do not generalize this observation to other accounts or
+versions. A no-login result from a dedicated acceptance HOME says nothing about
+the user's separately logged-in daily HOME.
+
+HiRoute's CLI submission receipts always use the Product's explicit private
+`HIROUTE_WORKER_RECEIPT_DIR`, even when native HOME is borrowed. Repeated submissions
+within one journey keep that directory so replay/conflict behavior remains real;
+separate acceptance runs must not reuse the daily client's journal.
+
+The real collaboration Skill must be installed by the production settings
+operation at `<QODER_CONFIG_DIR>/skills/hiroute-collaboration/SKILL.md`. There is no
+same-named project/plugin replacement. A pre-existing unmanaged different file is
+a real conflict; do not overwrite it to obtain green. Borrowed identical Skills
+must survive disabling collaboration. Retain the selected native context for
+later normal login reuse; it is not owned by `Product.close()`.
+
+If the collaboration leaf directory is absent, the fixture explicitly creates
+only that empty directory with mode `0700` before Apply. It records the directory's
+identity and permissions; the product still creates the actual `SKILL.md`. After
+product Restore, cleanup removes only the same unchanged, empty fixture-owned
+directory. Existing user directories are neither claimed nor chmodded. A permissive
+`skills` parent remains unchanged; an existing unsuitable leaf remains subject to
+the product's normal access guard.
+
+When delegation fails after installation, the fixture first requests product
+Restore through `agents restore preview/apply` while the service is still running,
+then retains diagnostics and stops it. Configure continues to use
+`agents connect preview/apply`; both paths require the authoritative status after Apply.
+Cleanup errors are reported separately and cannot replace the first business
+failure. A failed Restore never authorizes direct deletion of an installed Skill;
+the unchanged-empty-directory guard still applies. Partial observations such as a
+proved user Skill or an accepted failed Worker run do not complete the journey.
+
+Use [test planner](../../../scripts/test-plan.py) and the configured
+[validation runner](../../../scripts/validation.py):
+
+```sh
+cargo test --locked -p hiroute-product-e2e --test qoder_delegation -- --ignored --nocapture --test-threads=1
+```
+
+For an already attested exact-candidate build, the existing Python entries accept
+`REPO FULL_SHA`, with `HIROUTE_VALIDATION_PRODUCT_BIN_DIR` selecting that build.
+The core selects `HIROUTE_PRODUCT_WORKER_HARNESS=qoder`; the boundary takes
+`--harness qoder`. Preserve build proof and binary digests. A random local binary
+path is not an exact-candidate attestation.
+
+## Persisted additional model routes
+
+The fifth journey additionally requires `HIROUTE_QODER_MODEL_CONTEXT_HOME` and
+`HIROUTE_QODER_MODEL_CONFIG_DIR`. Both must explicitly select a dedicated,
+normally logged-in test context; the config must be inside that HOME. Missing
+values fail even when the four Worker journeys have a usable borrowed context.
+The fifth journey rejects the caller's daily HOME. Never copy or symlink login
+credentials into it. Keep this persistent login root outside the temporary Product
+root; Product cleanup has no ownership of authentication or native history.
+
+The fixture seeds a synthetic user default, a separate native provider, unknown
+fields and a later unrelated edit in that controlled settings file. Production
+Preview/Apply adds only its owned provider. Ordinary native `--model provider/alias`
+calls read the persisted user settings with the normal settings precedence; the
+launcher supplies no `--settings`, `--setting-sources`, provider or credential
+override. It requires a real source request, an independently generated output
+nonce and one native terminal result with `subtype=success` and `is_error=false`.
+The original collaboration journey's temporary direct model source cannot prove
+this behavior.
+
+Four required outcomes keep the evidence distinct:
+
+- `agent.models.persisted-routes`: both saved aliases reach their own production
+ Gateway routes, one works after daemon restart, and the explicit current-revision
+ Live check actually calls both routes. Live uses its separately bounded native
+ verifier; it cannot substitute for the ordinary startup calls.
+- `agent.models.credential-rotation`: the old local connection token is rejected
+ at the same `/_hiroute/qoder/v1/responses` entry used by ordinary native Qoder,
+ without any source request, while a new ordinary Qoder
+ process reads the updated persisted credential successfully. Tokens stay in
+ memory/protected native settings and never enter the report.
+- `agent.models.independent-restore`: Skill Restore leaves a usable model route;
+ model Restore leaves the actual user Skill intact and verifiable. A route-list
+ adjustment removes the old native choice, revokes its alias and keeps the retained
+ route callable by ordinary Qoder. Native/default/unknown user fields and
+ unrelated later edits survive these operations.
+- `agent.models.default-reference-guard`: a synthetic user selection of a managed
+ default blocks both its removal and full model Restore, without changing the
+ settings, Skill, current authority or token. Keeping that alias is still legal.
+ The fixture changes its own simulated default back before actual Restore.
+
+Production Restore runs while the daemon and sources are alive. The fixture then
+undoes its synthetic baseline only if no managed or drifted fields remain; a
+failed Restore cannot authorize direct deletion of a provider or Skill. Existing
+settings bytes/permissions are restored only after that ownership check. This
+JSON baseline does not claim exhaustive JSONC, hook, MCP or external-project
+precedence coverage; their focused integration tests and dedicated native cases
+remain separate. Budget-reduction publication rejection belongs to the real-store
+contract tests, rather than another repeated native journey.
+
+The complete Qoder target now requires five Rust tests, five scenario reports and
+14 required green outcomes. Reports from the original four-journey revision retain
+their original SHA and do not establish support for persisted model routing.
+
+## Native auxiliary-route proof
+
+The core Skill/Continue journey deliberately keeps a 32,768-token context and a
+4,096-token output budget. Every Qoder source request must carry that exact output
+limit, and an unexpected automatic compaction fails immediately instead of being
+mistaken for another main-model tool request. Main-Agent and cancellation journeys
+use 100,000-token contexts to keep their assertions focused. These reports record
+the selected context budget; success at 100,000 does not establish small-window
+support. The separate core gate must also pass.
+
+The source observes requests after Gateway processing, which can cap output
+tokens. Its 4,096 assertion therefore proves the upstream limit, not the raw
+native request limit by itself. The native metadata projection is separately
+covered by renderer/profile contracts and the pinned raw-ACP metadata-only versus
+CLI-only controls; the small-window journey catches the original zero-threshold
+compaction failure through actual behavior. Keep these evidence levels distinct.
+
+`worker.context.tool-summary-route` and `worker.context.compaction-route` share
+one fourth journey. Only its owned project settings enable context management and
+Bash output summarization. The source declares a 100,000-token context; the first
+real Responses tool reply reports 90,000 input tokens. The native client performs
+the summarization and compaction itself; the fixture does not write a native
+summary or invoke an internal HiRoute execution port. This leaves the original
+immediate-Continue journey unchanged.
+
+The source sees the Gateway's upstream model and source credential. Successful
+auxiliary requests therefore prove traversal of the production Worker/Gateway
+path; this report does not claim to capture the private run token on that leg.
+The Gateway's existing per-run authorization contracts protect the frozen Plan
+alias and credential. An auxiliary request using a wrong source model is rejected,
+and a foreign project endpoint request makes preservation fail. Ordinary main
+request success without both auxiliary requests, their receipt chain and the
+actual native compaction boundary cannot make this journey green.
+
+The Qoder 1.1.65 native signatures and exact-history witness are narrow fixture
+facts. Keep the raw-native positive and isolated wrong-summary/wrong-compact
+mutation evidence alongside the product report: it demonstrates that both native
+purpose settings affect real requests, but does not replace this production-entry run. Other native auxiliary uses remain separately
+bounded or unverified; this case does not claim universal model routing coverage.
+
+## What remains separate
+
+The six Worker outcome definitions and retention/read/credential consumer gates
+remain in [Worker native acceptance](WORKER_NATIVE_CONTEXT.md). These journeys do
+not prove every native hook, plugin, auxiliary model or permission mode. The
+Worker's supported tool set excludes unproven native nested-Agent tools. Strong
+conflicting *user* provider/purpose/hook cases require a normally logged-in test
+context whose synthetic settings are owned by the test; never change daily
+settings to manufacture that negative case.
+
+The [Qoder leaf](../../../crates/daemon/tests/support/qoder_native_context.py)
+reads the task's binding only in the current Product's owned metadata. Its
+`history_directory` function isolates the Qoder 1.1.65 short-workspace filename
+assumption used to locate one exact test session. Production retains opaque
+native history and confirms exact `session/load`; it does not consume that
+filename algorithm. The missing-history case restores the original test file,
+refuses to overwrite an unexpected replacement, and never searches daily history
+by message contents. Borrowed native history is not fixture cleanup material.
+
+A newly cancelled task need not have a continuation binding. For its history
+preservation assertion only, `cancelled_history` reads the exact task/run from this
+Product's own runtime database in read-only mode, verifies cancellation and complete
+cleanup, and uses that recorded native ID with the same bounded history formula.
+This registered current-storage fixture reader neither searches another task nor
+grants Continue. The successful neighbor and all Continue cases still require the
+real `native-session-binding.json` witness.
+
+macOS acceptance must additionally use the real managed Desktop/Pilot entry with
+the explicitly logged-in test HOME: install/select the single CLI, bind Qoder to a
+Plan, enable collaboration, observe a completed task and cancel real native work.
+A Python `prepared` response or API setup is not Desktop acceptance. Record
+platform, product/fixture revisions and every selected case's outcome separately.
+
+The main-Agent and persisted-model journeys share
+[Agent product support](../../../crates/daemon/tests/support/agent_product_support.py)
+for process deadlines/private output and authoritative settings transactions. Qoder
+leaves retain launch arguments, native settings ownership and result/receipt checks.
+The same upstream counter rejects false credential-revocation proofs without
+per-journey handler replacement. A new ecosystem should reuse these mechanics;
+it still needs independent assertions for its native contract.
+
+## Cheap oracle checks
+
+```sh
+python3 scripts/test-agent-product-support.py
+python3 scripts/test-qoder-product.py
+python3 scripts/test-native-context-product.py
+python3 scripts/test-native-context-boundaries.py
+```
+
+These checks reject missing explicit context, shadow user Skills, wrong role
+endpoints, fabricated/uncorrelated completion, changed borrowed files and missing
+disk artifacts. They also retain the existing SSE/ownership/boundary assertions.
+They start neither a native Agent nor HiRoute and cannot establish product support.
diff --git a/tools/product-e2e/tests/WORKER_NATIVE_CONTEXT.md b/tools/product-e2e/tests/WORKER_NATIVE_CONTEXT.md
new file mode 100644
index 00000000..58e8ff82
--- /dev/null
+++ b/tools/product-e2e/tests/WORKER_NATIVE_CONTEXT.md
@@ -0,0 +1,127 @@
+# Worker native context acceptance
+
+The core and boundary journeys use the real CLI, daemon, Gateway, installed native CLI and ACP
+adapter. Only the model upstream is synthetic. It creates a private product HOME
+with ordinary user/project skills, conflicting provider configuration and a
+neighboring user file. It neither reads a daily account nor replaces ACP.
+Qoder has a separate explicitly logged-in [acceptance entry](QODER_DELEGATION.md);
+it reuses these journeys without adding Qoder installation requirements to this target.
+Headless Codex/Claude cases select a non-default native configuration directory explicitly;
+Pilot cases use its documented native roots beneath the selected process HOME.
+
+## Business cases and proof levels
+
+The [Rust target](worker_native_context.rs) invokes the
+[core journey](../../../crates/daemon/tests/support/native_context_product.py) and
+[boundary journey](../../../crates/daemon/tests/support/native_context_boundaries.py)
+for both Codex and Claude. This is an assertion map, not a record of executed checks.
+
+| Stable case ID | Core journey | Boundary journey or separate contract |
+| --- | --- | --- |
+| `worker.context.native-skills` | Native discovery, real tool execution and independent receipts from user and project skills; Claude invokes its native `Skill` tool. Conflicting settings and the user proxy trap must not divert the model route. | Boundary tools also require the native skill receipts before their heartbeat scripts start. |
+| `worker.context.concurrent-routing` | Not a core outcome. | Boundary: simultaneous native tools in one HOME/config/workspace, distinct Plans, endpoints, source credentials, models and native sessions; each source rejects the other task's marker. |
+| `worker.context.run-authority` | Conflicting provider settings must not override the selected route. | Fresh run token, expiry, revocation and restricted permissions are not completed by either report. Keep [profile tests](../../../crates/daemon/src/delegation/profile/tests.rs), [journal contracts](../../../crates/daemon/src/delegation/persistent_journal_tests.rs) and the separate [lifecycle journey](worker_delegation.rs). |
+| `worker.context.exact-continue` | Immediate and restarted Continue retain the native session and correlated tool history after publishing a different source/model; task Plan stays frozen and replay sends no upstream request. | Boundary: temporarily remove only the exact fixture transcript; Continue must reject or fail native load without a result, model request, replacement session or changed neighboring history. |
+| `worker.context.cancel-owned-work` | Not a core outcome. | Boundary: formal cancellation removes the target native tool PID and stops its heartbeat while the neighbor remains live and completes. [Local process tests](../../../crates/daemon/tests/local_worker_platform.rs) retain child-chain/root-first-exit/failure assertions; the separate lifecycle journey remains required. |
+| `worker.context.retention-ownership` | User configuration, skills and neighboring files remain unchanged through cleanup. | Neither report establishes hidden/expired body refusal or physical history deletion. [Read/Continue](worker_read.rs) and [store/maintenance consumers](../../../crates/daemon/src/control/runtime/delegation_maintenance_tests.rs) own visibility and task-metadata cleanup assertions; borrowed history stays native-client owned. |
+
+The runner independently requires two core outcomes and three boundary outcomes
+(concurrency, cancellation and missing-history Continue). See the
+[boundary guide](../../../crates/daemon/tests/support/NATIVE_CONTEXT_BOUNDARIES.md)
+for its observations and cleanup ownership. The core report still marks its four
+`related_contracts` as `not_executed`; boundary results do not rewrite that report.
+The lifecycle/read targets, component contracts and native Desktop each need their
+own selected evidence. Keep missing, duplicate, non-green and zero-selected cases
+failing. Default Cargo runs ignore both installed-Agent tests, even when the rest
+of the workspace is green.
+
+## Exact-candidate execution
+
+Use `scripts/test-plan.py --base BASE` and the configured `scripts/validation.py`
+backend entry. The plan exposes `product_checks` separately because ordinary
+package tests do not execute ignored real-Agent tests. Set an exact full
+`HIROUTE_PRODUCT_CANDIDATE_SHA` and explicitly selected absolute file paths:
+
+- `HIROUTE_WORKER_CODEX_BINARY`
+- `HIROUTE_WORKER_CODEX_ACP_ADAPTER`
+- `HIROUTE_WORKER_CLAUDE_BINARY`
+- `HIROUTE_WORKER_CLAUDE_ACP_ADAPTER`
+- `HIROUTE_WORKER_NODE`
+
+The selected command is:
+
+```sh
+cargo test --locked -p hiroute-product-e2e --test worker_native_context -- --ignored --nocapture --test-threads=1
+```
+
+The runner builds the current checkout's CLI/daemon and executes both Harnesses.
+For a previously attested exact-candidate build, the Python entry can be called
+with `REPO FULL_SHA`; `HIROUTE_VALIDATION_PRODUCT_BIN_DIR` selects that build's
+directory. The core entry selects one Harness with `HIROUTE_PRODUCT_WORKER_HARNESS`;
+the boundary entry requires `--harness codex` or `--harness claude`. Record the
+original build proof and binary digests; pointing at arbitrary binaries is not
+an acceptable shortcut. Do not run Agent work during a tooling-only review.
+
+## Cheap preflight contracts
+
+These checks prepare trustworthy inputs and verdicts before starting an Agent.
+They do not satisfy the real-client or Desktop business cases.
+
+| Contract | Smallest entry and useful assertions |
+| --- | --- |
+| Native SSE wire | [Fixture tests](../../../scripts/test-native-context-product.py): `test_responses_native_wire_has_typed_ordered_terminal_frames` and `test_messages_native_wire_has_typed_terminal_frames` make real loopback HTTP requests, checking JSON event `type`, Responses sequence numbers, tool and text terminal frames. |
+| Owned directory permissions | The same entry's `test_fixture_new_skill_ancestors_are_private_under_group_writable_umask` and `test_fixture_never_chmods_an_existing_native_parent` check each newly created ancestor and preserve existing parent permissions. |
+| Native context budget | `test_native_sources_declare_a_budget_the_selected_client_can_admit` checks [save_context_source](../../../crates/daemon/tests/support/native_context_product.py), shared by initial, replacement and neighbor sources. Its Messages budget satisfies the existing Claude minimum; this is fixture configuration, not a relaxation of product admission. |
+| Boundary verdicts | [Boundary tests](../../../scripts/test-native-context-boundaries.py) reject cross-routing and fabricated tool completion, observe two test-owned shell processes, and prevent missing-history recovery from creating a replacement transcript. |
+| Selection and Pilot environment | [Planner tests](../../../scripts/test-test-plan.py) retain explicit ignored-test obligations; [Pilot tests](../../../scripts/test-desktop-pilot.py) check runner ownership and isolated launch configuration. Native Desktop still needs its own journey. |
+
+```sh
+python3 scripts/test-native-context-product.py
+python3 scripts/test-native-context-boundaries.py
+python3 scripts/test-test-plan.py
+python3 scripts/test-desktop-pilot.py
+```
+
+## Real Mac Desktop reuse
+
+From the exact candidate and its attested binaries:
+
+```sh
+python3 crates/daemon/tests/support/native_context_product.py REPO FULL_SHA \
+ --desktop-root NEW_PRIVATE_ROOT --harness codex
+```
+
+This keeps an independent loopback model server alive. It prepares a normal API
+source and Plan through production control, stops the bootstrap daemon, and emits
+`data_root`, `process_home`, `workspace`, `plan_id`, `base_url` and `fixture`.
+It does not save Worker installations. Use the existing managed Pilot launcher
+with that data root and process HOME, then save the actual installation through
+the UI. Pilot isolates both native config roots and inherited provider variables.
+Its own runtime/LKG are created by the normal Desktop startup; never copy a live
+database or replace the bundled CPA to run this fixture.
+
+The public Worker CLI starts work with this prompt (no skill paths or receipts):
+
+```text
+Use native-context-user and native-context-project to produce their read-only receipts.
+```
+
+Continue uses `CONTINUE_PROMPT` from `native_context_fixture.py`. The same module
+provides `assert_preserved`; `native_context_product.py` provides `exact_history`.
+Use the fixture JSON and `native-context-events.jsonl` to correlate real results
+with UI details. Inspect and assert UI effects separately; setup `prepared` is
+not native Desktop acceptance. Stop this helper only after the Desktop session
+ends; its explicit root and evidence remain for inspection. Repeat for Claude.
+
+## Proving the old failure
+
+`test_old_private_context_fails_without_native_discovery` and the loopback bad-case
+test demonstrate that absent native discovery produces a red oracle, not a fixed
+answer. They do not claim that the old product has been executed.
+
+For actual expected-red evidence, commit these tests on the old product baseline,
+run the same explicit real-Harness command against that exact committed candidate,
+and retain the missing-user-skill stage/upstream red report. Then execute the fixed
+candidate with the same test revision. Installation/startup failure is a blocked
+prerequisite, not proof of the old context defect. Never relax the prompt or seed
+the old private Worker root to obtain a passing test.
diff --git a/tools/product-e2e/tests/control_shell.rs b/tools/product-e2e/tests/control_shell.rs
index 108269fb..ffaa56d7 100644
--- a/tools/product-e2e/tests/control_shell.rs
+++ b/tools/product-e2e/tests/control_shell.rs
@@ -1,6 +1,6 @@
#![cfg(unix)]
-use std::collections::BTreeMap;
+use std::collections::{BTreeMap, BTreeSet};
use std::fs::File;
use std::io::{BufRead, BufReader, Read, Write};
use std::os::unix::fs::FileTypeExt;
@@ -99,6 +99,7 @@ fn control_shell_uses_real_hiroute_and_hirouted_processes() {
.env("HOME", &agent_home)
.env_remove("CODEX_HOME")
.env_remove("CLAUDE_CONFIG_DIR")
+ .env_remove("QODER_CONFIG_DIR")
.env("PATH", agent_path)
.env_remove("ANTHROPIC_BASE_URL")
.env_remove("ANTHROPIC_MODEL")
@@ -154,13 +155,7 @@ fn control_shell_uses_real_hiroute_and_hirouted_processes() {
let observed = run_cli(&binaries.hiroute, &runtime_root, &command);
let command_id = format!("{}.{}", command[0], command[1]);
assert_cli(&observed, expected[command_id.as_str()]);
- assert_eq!(
- observed.envelope["data"]["agents"]
- .as_array()
- .unwrap()
- .len(),
- 2
- );
+ assert_discovery_agent_ids(observed.envelope["data"]["agents"].as_array().unwrap());
let internal = desktop_call(
&endpoint,
ClientHelloV1 {
@@ -179,7 +174,7 @@ fn control_shell_uses_real_hiroute_and_hirouted_processes() {
);
assert_eq!(internal["status"], "succeeded");
let agents = internal["data"]["agents"].as_array().unwrap();
- assert_eq!(agents.len(), 2);
+ assert_discovery_agent_ids(agents);
let claude = agents
.iter()
.find(|agent| agent["agent_id"] == "agent_claude_default")
@@ -193,6 +188,12 @@ fn control_shell_uses_real_hiroute_and_hirouted_processes() {
claude["discovered_credential"]["field_selector"],
"env.ANTHROPIC_AUTH_TOKEN"
);
+ let qoder = agents
+ .iter()
+ .find(|agent| agent["agent_id"] == "agent_qoder_default")
+ .unwrap();
+ assert!(qoder["registered_configuration"].is_null());
+ assert!(qoder["discovered_credential"].is_null());
assert!(!internal.to_string().contains(secret_sentinel));
// Owner-only connection controls intentionally expose the exact directory
// used by copied commands. No other discovery field may expose paths.
@@ -340,6 +341,21 @@ struct CliObservation {
stderr: Vec<u8>,
}
+fn assert_discovery_agent_ids(agents: &[Value]) {
+ let ids = agents
+ .iter()
+ .map(|agent| agent["agent_id"].as_str().unwrap())
+ .collect::<BTreeSet<_>>();
+ assert_eq!(ids.len(), agents.len(), "duplicate Agent IDs");
+ for required in [
+ "agent_codex_default",
+ "agent_claude_default",
+ "agent_qoder_default",
+ ] {
+ assert!(ids.contains(required), "missing required Agent: {required}");
+ }
+}
+
fn run_cli(binary: &Path, runtime_root: &Path, arguments: &[&str]) -> CliObservation {
observe(
Command::new(binary)
diff --git a/tools/product-e2e/tests/qoder_delegation.rs b/tools/product-e2e/tests/qoder_delegation.rs
new file mode 100644
index 00000000..df16f361
--- /dev/null
+++ b/tools/product-e2e/tests/qoder_delegation.rs
@@ -0,0 +1,48 @@
+#![cfg(unix)]
+
+mod worker_product_support;
+
+#[test]
+#[ignore = "requires an explicitly selected, normally logged-in Qoder context and native CLI"]
+fn qoder_main_agent_uses_installed_user_skill_to_delegate_real_work() {
+ worker_product_support::run_real_worker_scenario(
+ "HIROUTE_PRODUCT_QODER_MAIN",
+ "qoder-main-agent-delegation",
+ );
+}
+
+#[test]
+#[ignore = "requires an explicitly selected, normally logged-in Qoder context and native CLI"]
+fn qoder_worker_uses_native_skills_and_continues_the_frozen_task() {
+ worker_product_support::run_real_worker_scenario(
+ "HIROUTE_PRODUCT_QODER_CORE",
+ "worker-native-context-core",
+ );
+}
+
+#[test]
+#[ignore = "requires an explicitly selected, normally logged-in Qoder context and native CLI"]
+fn qoder_workers_route_independently_and_cancel_only_owned_work() {
+ worker_product_support::run_real_worker_scenario(
+ "HIROUTE_PRODUCT_QODER_BOUNDARIES",
+ "worker-native-context-boundaries",
+ );
+}
+
+#[test]
+#[ignore = "requires an explicitly selected, normally logged-in Qoder context and native CLI"]
+fn qoder_worker_compaction_keeps_the_frozen_managed_route() {
+ worker_product_support::run_real_worker_scenario(
+ "HIROUTE_PRODUCT_QODER_COMPACTION",
+ "qoder-worker-compaction-route",
+ );
+}
+
+#[test]
+#[ignore = "requires a dedicated normally logged-in Qoder MODEL context; writes only its owned test settings"]
+fn qoder_main_agent_uses_persisted_additional_model_routes() {
+ worker_product_support::run_real_worker_scenario(
+ "HIROUTE_PRODUCT_QODER_MODELS",
+ "qoder-persisted-model-routes",
+ );
+}
diff --git a/tools/product-e2e/tests/worker_native_context.rs b/tools/product-e2e/tests/worker_native_context.rs
new file mode 100644
index 00000000..4c0eebfa
--- /dev/null
+++ b/tools/product-e2e/tests/worker_native_context.rs
@@ -0,0 +1,21 @@
+#![cfg(unix)]
+
+mod worker_product_support;
+
+#[test]
+#[ignore = "requires explicitly selected real Codex and Claude ACP installations"]
+fn native_worker_context_loads_skills_and_continues_exact_history() {
+ worker_product_support::run_real_worker_scenario(
+ "HIROUTE_PRODUCT_NATIVE_CONTEXT",
+ "worker-native-context-core",
+ );
+}
+
+#[test]
+#[ignore = "requires explicitly selected real Codex and Claude ACP installations"]
+fn concurrent_native_workers_keep_routes_and_cancel_only_owned_work() {
+ worker_product_support::run_real_worker_scenario(
+ "HIROUTE_PRODUCT_NATIVE_CONTEXT_BOUNDARIES",
+ "worker-native-context-boundaries",
+ );
+}
diff --git a/tools/product-e2e/tests/worker_product_support/mod.rs b/tools/product-e2e/tests/worker_product_support/mod.rs
index 7eff4a9f..8e2fe393 100644
--- a/tools/product-e2e/tests/worker_product_support/mod.rs
+++ b/tools/product-e2e/tests/worker_product_support/mod.rs
@@ -15,6 +15,64 @@ const REQUIRED_INSTALLATIONS: [&str; 5] = [
];
pub fn run_real_worker_scenario(mode: &str, expected_scenario: &str) {
+ let qoder_script = match mode {
+ "HIROUTE_PRODUCT_QODER_MAIN" => Some("qoder_collaboration_product.py"),
+ "HIROUTE_PRODUCT_QODER_CORE" => Some("native_context_product.py"),
+ "HIROUTE_PRODUCT_QODER_BOUNDARIES" => Some("native_context_boundaries.py"),
+ "HIROUTE_PRODUCT_QODER_COMPACTION" => Some("qoder_compaction_product.py"),
+ "HIROUTE_PRODUCT_QODER_MODELS" => Some("qoder_model_product.py"),
+ _ => None,
+ };
+ if let Some(script) = qoder_script {
+ run_qoder_scenario(script, expected_scenario);
+ return;
+ }
+ let script = match mode {
+ "HIROUTE_PRODUCT_NATIVE_CONTEXT" => "native_context_product.py",
+ "HIROUTE_PRODUCT_NATIVE_CONTEXT_BOUNDARIES" => "native_context_boundaries.py",
+ _ => "delegation_product.py",
+ };
+ run_scenario(
+ script,
+ mode,
+ expected_scenario,
+ &["codex", "claude"],
+ &REQUIRED_INSTALLATIONS,
+ );
+}
+
+fn run_qoder_scenario(script: &str, expected_scenario: &str) {
+ let context_variables = if script == "qoder_model_product.py" {
+ [
+ "HIROUTE_QODER_MODEL_CONTEXT_HOME",
+ "HIROUTE_QODER_MODEL_CONFIG_DIR",
+ ]
+ } else {
+ ["HIROUTE_QODER_CONTEXT_HOME", "HIROUTE_QODER_CONFIG_DIR"]
+ };
+ for name in context_variables {
+ let path = PathBuf::from(required(name));
+ assert!(
+ path.is_absolute() && path.is_dir(),
+ "{name} must explicitly name an existing logged-in context"
+ );
+ }
+ run_scenario(
+ script,
+ "HIROUTE_PRODUCT_QODER",
+ expected_scenario,
+ &["qoder"],
+ &["HIROUTE_WORKER_QODER_BINARY"],
+ );
+}
+
+fn run_scenario(
+ script: &str,
+ mode: &str,
+ expected_scenario: &str,
+ harnesses: &[&str],
+ installations: &[&str],
+) {
let workspace = workspace_root();
let candidate = required("HIROUTE_PRODUCT_CANDIDATE_SHA");
assert_eq!(candidate.len(), 40, "candidate must be a full Git SHA");
@@ -23,7 +81,7 @@ pub fn run_real_worker_scenario(mode: &str, expected_scenario: &str) {
candidate,
"candidate checkout mismatch"
);
- for variable in REQUIRED_INSTALLATIONS {
+ for &variable in installations {
let path = PathBuf::from(required(variable));
assert!(
path.is_absolute() && path.is_file(),
@@ -32,14 +90,23 @@ pub fn run_real_worker_scenario(mode: &str, expected_scenario: &str) {
}
build_product_binaries(&workspace);
- for harness in ["codex", "claude"] {
- let output = Command::new(python())
- .arg(workspace.join("crates/daemon/tests/support/delegation_product.py"))
+ for &harness in harnesses {
+ let mut command = Command::new(python());
+ command
+ .arg(workspace.join("crates/daemon/tests/support").join(script))
.arg(&workspace)
.arg(&candidate)
- .env(mode, "1")
.env("HIROUTE_PRODUCT_WORKER_HARNESS", harness)
- .current_dir(&workspace)
+ .env(
+ "HIROUTE_VALIDATION_PRODUCT_BIN_DIR",
+ workspace.join("target/debug"),
+ )
+ .current_dir(&workspace);
+ if script == "native_context_boundaries.py" {
+ command.args(["--harness", harness]);
+ }
+ command.env(mode, "1");
+ let output = command
.output()
.expect("run the real Worker product scenario");
assert_scenario(output, expected_scenario, harness, &candidate);
@@ -81,6 +148,47 @@ fn assert_scenario(output: Output, scenario: &str, harness: &str, candidate: &st
.find(|value| value.get("scenario").and_then(Value::as_str) == Some(scenario))
.unwrap_or_else(|| panic!("missing {scenario} report for {harness}: {report}"));
assert_eq!(report["state"], "green", "scenario report: {report}");
+ let expected: &[&str] = match scenario {
+ "worker-native-context-core" => &[
+ "worker.context.native-skills",
+ "worker.context.exact-continue",
+ ],
+ "worker-native-context-boundaries" => &[
+ "worker.context.concurrent-routing",
+ "worker.context.cancel-owned-work",
+ "worker.context.exact-continue",
+ ],
+ "qoder-worker-compaction-route" => &[
+ "worker.context.tool-summary-route",
+ "worker.context.compaction-route",
+ ],
+ "qoder-main-agent-delegation" => &[
+ "agent.collaboration.user-skill",
+ "agent.collaboration.public-worker-delegation",
+ "agent.collaboration.disable-owned-skill",
+ ],
+ "qoder-persisted-model-routes" => &[
+ "agent.models.persisted-routes",
+ "agent.models.credential-rotation",
+ "agent.models.independent-restore",
+ "agent.models.default-reference-guard",
+ ],
+ _ => &[],
+ };
+ if !expected.is_empty() {
+ let cases = report["cases"].as_array().expect("required case results");
+ assert_eq!(cases.len(), expected.len(), "scenario report: {report}");
+ for &id in expected {
+ assert_eq!(
+ cases
+ .iter()
+ .filter(|case| case["id"] == id && case["state"] == "green")
+ .count(),
+ 1,
+ "missing, duplicate or non-green case {id}: {report}"
+ );
+ }
+ }
assert_eq!(report["candidate"], candidate, "scenario report: {report}");
assert_eq!(
report["worker_harness"], harness,