The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
chore(core): remove unused test files and consolidate observability tests
Steven Enamakelf9cfad99bde6
diff --git a/crates/openhuman-core/src/core/core_mod_tests.rs b/crates/openhuman-core/src/core/core_mod_tests.rsindex 6e11bedf97..a0429ef702 100644--- a/crates/openhuman-core/src/core/core_mod_tests.rs+++ b/crates/openhuman-core/src/core/core_mod_tests.rs@@ -1,115 +1,115 @@- use super::*;+use super::*;- fn mk(namespace: &'static str, function: &'static str) -> ControllerSchema {- ControllerSchema {- namespace,- function,- description: "",- inputs: vec![],- outputs: vec![],- }+fn mk(namespace: &'static str, function: &'static str) -> ControllerSchema {+ ControllerSchema {+ namespace,+ function,+ description: "",+ inputs: vec![],+ outputs: vec![],}+}- #[test]- fn method_name_joins_namespace_and_function_with_dot() {- let s = mk("memory", "doc_put");- assert_eq!(s.method_name(), "memory.doc_put");- }+#[test]+fn method_name_joins_namespace_and_function_with_dot() {+ let s = mk("memory", "doc_put");+ assert_eq!(s.method_name(), "memory.doc_put");+}- #[test]- fn method_name_is_not_an_rpc_method_name() {- // The dotted controller key and the `openhuman.<ns>_<fn>` RPC method- // name are intentionally different — guard against drift.- let s = mk("memory", "doc_put");- assert_eq!(s.method_name(), "memory.doc_put");- assert_eq!(- crate::core::all::rpc_method_name(&s),- "openhuman.memory_doc_put"- );- }+#[test]+fn method_name_is_not_an_rpc_method_name() {+ // The dotted controller key and the `openhuman.<ns>_<fn>` RPC method+ // name are intentionally different — guard against drift.+ let s = mk("memory", "doc_put");+ assert_eq!(s.method_name(), "memory.doc_put");+ assert_eq!(+ crate::core::all::rpc_method_name(&s),+ "openhuman.memory_doc_put"+ );+}- #[test]- fn method_name_preserves_underscores_in_function() {- let s = mk("team", "change_member_role");- assert_eq!(s.method_name(), "team.change_member_role");- }+#[test]+fn method_name_preserves_underscores_in_function() {+ let s = mk("team", "change_member_role");+ assert_eq!(s.method_name(), "team.change_member_role");+}- #[test]- fn controller_schema_equality_considers_all_fields() {- let a = ControllerSchema {- namespace: "a",- function: "b",- description: "x",- inputs: vec![],- outputs: vec![],- };- let b = ControllerSchema {- namespace: "a",- function: "b",- description: "x",- inputs: vec![],- outputs: vec![],- };- let c = ControllerSchema {- namespace: "a",- function: "b",- description: "different",- inputs: vec![],- outputs: vec![],- };- assert_eq!(a, b);- assert_ne!(a, c);- }+#[test]+fn controller_schema_equality_considers_all_fields() {+ let a = ControllerSchema {+ namespace: "a",+ function: "b",+ description: "x",+ inputs: vec![],+ outputs: vec![],+ };+ let b = ControllerSchema {+ namespace: "a",+ function: "b",+ description: "x",+ inputs: vec![],+ outputs: vec![],+ };+ let c = ControllerSchema {+ namespace: "a",+ function: "b",+ description: "different",+ inputs: vec![],+ outputs: vec![],+ };+ assert_eq!(a, b);+ assert_ne!(a, c);+}- #[test]- fn type_schema_nesting_is_equality_comparable() {- let a = TypeSchema::Array(Box::new(TypeSchema::Option(Box::new(TypeSchema::String))));- let b = TypeSchema::Array(Box::new(TypeSchema::Option(Box::new(TypeSchema::String))));- let c = TypeSchema::Array(Box::new(TypeSchema::Option(Box::new(TypeSchema::I64))));- assert_eq!(a, b);- assert_ne!(a, c);- }+#[test]+fn type_schema_nesting_is_equality_comparable() {+ let a = TypeSchema::Array(Box::new(TypeSchema::Option(Box::new(TypeSchema::String))));+ let b = TypeSchema::Array(Box::new(TypeSchema::Option(Box::new(TypeSchema::String))));+ let c = TypeSchema::Array(Box::new(TypeSchema::Option(Box::new(TypeSchema::I64))));+ assert_eq!(a, b);+ assert_ne!(a, c);+}++#[test]+fn field_schema_required_flag_changes_equality() {+ let a = FieldSchema {+ name: "x",+ ty: TypeSchema::Bool,+ comment: "",+ required: true,+ };+ let b = FieldSchema {+ name: "x",+ ty: TypeSchema::Bool,+ comment: "",+ required: false,+ };+ assert_ne!(a, b);+}- #[test]- fn field_schema_required_flag_changes_equality() {- let a = FieldSchema {- name: "x",+#[test]+fn controller_schema_serializes_to_json() {+ // Schema must be JSON-serializable: the /schema endpoint depends on it.+ let s = ControllerSchema {+ namespace: "health",+ function: "snapshot",+ description: "d",+ inputs: vec![FieldSchema {+ name: "limit",+ ty: TypeSchema::U64,+ comment: "cap",+ required: false,+ }],+ outputs: vec![FieldSchema {+ name: "ok",ty: TypeSchema::Bool,comment: "",required: true,- };- let b = FieldSchema {- name: "x",- ty: TypeSchema::Bool,- comment: "",- required: false,- };- assert_ne!(a, b);- }-- #[test]- fn controller_schema_serializes_to_json() {- // Schema must be JSON-serializable: the /schema endpoint depends on it.- let s = ControllerSchema {- namespace: "health",- function: "snapshot",- description: "d",- inputs: vec![FieldSchema {- name: "limit",- ty: TypeSchema::U64,- comment: "cap",- required: false,- }],- outputs: vec![FieldSchema {- name: "ok",- ty: TypeSchema::Bool,- comment: "",- required: true,- }],- };- let json = serde_json::to_value(&s).unwrap();- assert_eq!(json["namespace"], "health");- assert_eq!(json["function"], "snapshot");- assert_eq!(json["inputs"][0]["name"], "limit");- assert_eq!(json["outputs"][0]["required"], true);- }+ }],+ };+ let json = serde_json::to_value(&s).unwrap();+ assert_eq!(json["namespace"], "health");+ assert_eq!(json["function"], "snapshot");+ assert_eq!(json["inputs"][0]["name"], "limit");+ assert_eq!(json["outputs"][0]["required"], true);+}diff --git a/crates/openhuman-core/src/core/http_server_status.rs b/crates/openhuman-core/src/core/http_server_status.rsindex 10f042958c..a5fc46276b 100644--- a/crates/openhuman-core/src/core/http_server_status.rs+++ b/crates/openhuman-core/src/core/http_server_status.rs@@ -27,4 +27,3 @@ pub const HTTP_SERVER_COMPILED_IN: bool = cfg!(feature = "http-server");#[cfg(test)]#[path = "http_server_status_tests.rs"]mod tests;-diff --git a/crates/openhuman-core/src/core/http_server_status_tests.rs b/crates/openhuman-core/src/core/http_server_status_tests.rsindex 6fbe680623..fbd1c12cac 100644--- a/crates/openhuman-core/src/core/http_server_status_tests.rs+++ b/crates/openhuman-core/src/core/http_server_status_tests.rs@@ -1,25 +1,25 @@- use super::HTTP_SERVER_COMPILED_IN;+use super::HTTP_SERVER_COMPILED_IN;- /// Pins the constant to the gate rather than to a hardcoded value: the- /// assertion inverts with the feature, so it holds for both the default- /// build and the slim (`--no-default-features`) build.- #[test]- fn reports_the_compiled_gate_state() {- assert_eq!(HTTP_SERVER_COMPILED_IN, cfg!(feature = "http-server"));- }+/// Pins the constant to the gate rather than to a hardcoded value: the+/// assertion inverts with the feature, so it holds for both the default+/// build and the slim (`--no-default-features`) build.+#[test]+fn reports_the_compiled_gate_state() {+ assert_eq!(HTTP_SERVER_COMPILED_IN, cfg!(feature = "http-server"));+}- /// The default build ships the HTTP transport; this is the state the- /// desktop app requires. Skipped when the slim build is under test.- #[test]- #[cfg(feature = "http-server")]- fn is_true_when_the_http_server_feature_is_on() {- assert!(HTTP_SERVER_COMPILED_IN);- }+/// The default build ships the HTTP transport; this is the state the+/// desktop app requires. Skipped when the slim build is under test.+#[test]+#[cfg(feature = "http-server")]+fn is_true_when_the_http_server_feature_is_on() {+ assert!(HTTP_SERVER_COMPILED_IN);+}- /// The slim build must report honestly, otherwise the shell's const assert- /// would pass against a listener-less core.- #[test]- #[cfg(not(feature = "http-server"))]- fn is_false_when_the_http_server_feature_is_off() {- assert!(!HTTP_SERVER_COMPILED_IN);- }+/// The slim build must report honestly, otherwise the shell's const assert+/// would pass against a listener-less core.+#[test]+#[cfg(not(feature = "http-server"))]+fn is_false_when_the_http_server_feature_is_off() {+ assert!(!HTTP_SERVER_COMPILED_IN);+}diff --git a/crates/openhuman-core/src/core/legacy_aliases.rs b/crates/openhuman-core/src/core/legacy_aliases.rsindex 25f26bfb8b..21ccd9fc49 100644--- a/crates/openhuman-core/src/core/legacy_aliases.rs+++ b/crates/openhuman-core/src/core/legacy_aliases.rs@@ -228,4 +228,3 @@ pub fn resolve_legacy(method: &str) -> &str {#[cfg(test)]#[path = "legacy_aliases_tests.rs"]mod tests;-diff --git a/crates/openhuman-core/src/core/legacy_aliases_tests.rs b/crates/openhuman-core/src/core/legacy_aliases_tests.rsindex 3c9e278f24..c6dc5603f5 100644--- a/crates/openhuman-core/src/core/legacy_aliases_tests.rs+++ b/crates/openhuman-core/src/core/legacy_aliases_tests.rs@@ -1,457 +1,455 @@- use super::*;- use std::collections::{BTreeMap, BTreeSet};- use std::fs;- use std::path::PathBuf;-- fn frontend_rpc_catalog_path() -> PathBuf {- PathBuf::from(env!("OPENHUMAN_REPOSITORY_ROOT")).join("app/src/services/rpcMethods.ts")- }-- fn read_frontend_rpc_catalog() -> String {- let path = frontend_rpc_catalog_path();- fs::read_to_string(&path)- .unwrap_or_else(|err| panic!("failed to read {}: {err}", path.display()))- }-- fn object_body_after_marker<'a>(source: &'a str, marker: &str, terminator: &str) -> &'a str {- let marker_start = source- .find(marker)- .unwrap_or_else(|| panic!("missing marker `{marker}` in frontend RPC catalog"));- let object_start = marker_start- + source[marker_start..]- .find('{')- .unwrap_or_else(|| panic!("missing object start after `{marker}`"))- + 1;- let rest = &source[object_start..];- let object_end = rest- .find(terminator)- .unwrap_or_else(|| panic!("missing terminator `{terminator}` after `{marker}`"));- &rest[..object_end]- }-- fn quoted_value(text: &str) -> String {- let (quote_index, quote) = text- .char_indices()- .find(|(_, ch)| *ch == '\'' || *ch == '"')- .unwrap_or_else(|| panic!("expected quoted value in `{text}`"));- let value_start = quote_index + quote.len_utf8();- let rest = &text[value_start..];- let value_end = rest- .find(quote)- .unwrap_or_else(|| panic!("unterminated quoted value in `{text}`"));- rest[..value_end].to_string()- }-- fn parse_core_rpc_methods(source: &str) -> BTreeMap<String, String> {- let body = object_body_after_marker(source, "export const CORE_RPC_METHODS", "} as const;");- let mut methods = BTreeMap::new();- for line in body.lines().map(str::trim).filter(|line| !line.is_empty()) {- if line.starts_with("//") {- continue;- }- let (key, value) = line- .split_once(':')- .unwrap_or_else(|| panic!("malformed CORE_RPC_METHODS entry: `{line}`"));- methods.insert(key.trim().to_string(), quoted_value(value));- }- methods- }-- fn parse_frontend_legacy_aliases(- source: &str,- core_methods: &BTreeMap<String, String>,- ) -> BTreeMap<String, String> {- let body = object_body_after_marker(source, "export const LEGACY_METHOD_ALIASES", "};");- let compact = body- .lines()- .map(str::trim)- .filter(|line| !line.is_empty() && !line.starts_with("//"))- .collect::<Vec<_>>()- .join(" ");- let mut aliases = BTreeMap::new();- for entry in compact- .split(',')- .map(str::trim)- .filter(|entry| !entry.is_empty())- {- let (legacy, target_expr) = entry- .split_once(':')- .unwrap_or_else(|| panic!("expected legacy alias entry, got `{entry}`"));- // Prettier strips quotes from keys that are valid JS identifiers- // (e.g. `health_snapshot`), so accept both `'foo':` and bare `foo:`.- let legacy_trimmed = legacy.trim();- let legacy = if legacy_trimmed.starts_with('\'') || legacy_trimmed.starts_with('"') {- quoted_value(legacy)- } else {- legacy_trimmed.to_string()- };- let target_expr = target_expr.trim();- let canonical = if let Some(key) = target_expr.strip_prefix("CORE_RPC_METHODS.") {- core_methods- .get(key)- .unwrap_or_else(|| {- panic!("legacy alias references unknown CORE_RPC_METHODS.{key}")- })- .clone()- } else {- quoted_value(target_expr)- };- aliases.insert(legacy, canonical);- }- aliases- }-- fn registered_http_methods() -> BTreeSet<String> {- crate::core::all::all_http_method_schemas()- .into_iter()- .map(|method| method.method)- .collect()- }-- /// Whether `method`'s controller is compiled out of THIS build by a- /// default-ON Cargo feature gate.- ///- /// The frontend RPC catalog and the alias table below are both **data**:- /// they are authored against the full (shipped desktop) surface and cannot- /// be `#[cfg]`'d per Rust feature — the frontend is built independently of- /// the core's feature set, and the shipped app always enables `mcp`. So in- /// a slim build they legitimately still name methods whose controllers no- /// longer exist. The drift checks below must therefore ignore exactly those- /// namespaces, and keep asserting on everything else — otherwise the whole- /// drift signal is lost in slim builds (or, worse, someone "fixes" the- /// failure by deleting live frontend methods from the catalog).- ///- /// Mirrors how the agent loader tolerates the orchestrator TOML's dangling- /// `mcp_agent` subagent id (#4799). Composed from one predicate per gate so- /// each new gate adds a self-contained pair (keeps the attribute-`#[cfg]`- /// form the feature-gate smoke lane's coverage guard tracks).- fn is_compiled_out_method(method: &str) -> bool {- mcp_method_compiled_out(method) || channels_method_compiled_out(method)- }-- #[cfg(feature = "mcp")]- fn mcp_method_compiled_out(_method: &str) -> bool {- false- }-- #[cfg(not(feature = "mcp"))]- fn mcp_method_compiled_out(method: &str) -> bool {- // `mcp` feature OFF ⇒ the `mcp_clients` (dynamic registry) and- // `mcp_audit` (write log) controllers are unregistered.- method.starts_with("openhuman.mcp_clients_") || method.starts_with("openhuman.mcp_audit_")- }-- #[cfg(feature = "channels")]- fn channels_method_compiled_out(_method: &str) -> bool {- false- }-- #[cfg(not(feature = "channels"))]- fn channels_method_compiled_out(method: &str) -> bool {- // `channels` feature OFF ⇒ the channels + webview_notifications- // controllers are unregistered (#4801). NOTE: the in-app web chat- // (`openhuman.channel_*`) is NOT gated (core product surface, #5002) —- // do not add that prefix here.- method.starts_with("openhuman.channels_")- || method.starts_with("openhuman.webview_notifications_")- }-- #[test]- fn quoted_value_extracts_single_quoted_string() {- assert_eq!(quoted_value(": 'hello'"), "hello");- }-- #[test]- fn quoted_value_extracts_double_quoted_string() {- assert_eq!(quoted_value(": \"hello\""), "hello");- }-- #[test]- #[should_panic(expected = "expected quoted value")]- fn quoted_value_panics_on_unquoted_text() {- let _ = quoted_value(": bare-token");- }-- #[test]- #[should_panic(expected = "unterminated quoted value")]- fn quoted_value_panics_on_unterminated_quote() {- let _ = quoted_value(": 'open-but-never-closed");- }-- #[test]- fn object_body_after_marker_returns_inner_body() {- let source = "noise\nexport const FOO = {\n alpha: 'a',\n beta: 'b',\n} as const;\nrest";- let body = object_body_after_marker(source, "export const FOO", "} as const;");- assert!(body.contains("alpha: 'a'"));- assert!(body.contains("beta: 'b'"));- assert!(!body.contains("rest"));- assert!(!body.contains("noise"));- }-- #[test]- #[should_panic(expected = "missing marker")]- fn object_body_after_marker_panics_when_marker_absent() {- let _ = object_body_after_marker("nothing here", "export const MISSING", "};");- }-- #[test]- #[should_panic(expected = "missing terminator")]- fn object_body_after_marker_panics_when_terminator_absent() {- let _ = object_body_after_marker(- "export const FOO = { alpha: 'a',",- "export const FOO",- "} as const;",- );- }-- #[test]- fn parse_core_rpc_methods_extracts_entries_and_skips_comments() {- let source = "export const CORE_RPC_METHODS = {\n // a comment that should be skipped\n alphaMethod: 'openhuman.alpha',\n betaMethod: 'openhuman.beta',\n} as const;\n";- let methods = parse_core_rpc_methods(source);- assert_eq!(- methods.get("alphaMethod").map(String::as_str),- Some("openhuman.alpha")- );- assert_eq!(- methods.get("betaMethod").map(String::as_str),- Some("openhuman.beta")- );- assert_eq!(methods.len(), 2);- }-- #[test]- #[should_panic(expected = "malformed CORE_RPC_METHODS entry")]- fn parse_core_rpc_methods_panics_on_non_colon_line() {- let source =- "export const CORE_RPC_METHODS = {\n alphaMethod 'openhuman.alpha',\n} as const;\n";- let _ = parse_core_rpc_methods(source);- }-- #[test]- fn parse_frontend_legacy_aliases_resolves_core_method_refs_and_literals() {- let source = "export const CORE_RPC_METHODS = {\n alphaMethod: 'openhuman.alpha',\n} as const;\n\nexport const LEGACY_METHOD_ALIASES: Record<string, CoreRpcMethod> = {\n 'openhuman.legacy_alpha': CORE_RPC_METHODS.alphaMethod,\n 'openhuman.legacy_literal': 'openhuman.literal_target',\n};\n";- let core_methods = parse_core_rpc_methods(source);- let aliases = parse_frontend_legacy_aliases(source, &core_methods);- assert_eq!(- aliases.get("openhuman.legacy_alpha").map(String::as_str),- Some("openhuman.alpha")- );- assert_eq!(- aliases.get("openhuman.legacy_literal").map(String::as_str),- Some("openhuman.literal_target")- );- }-- #[test]- fn parse_frontend_legacy_aliases_accepts_bare_identifier_keys_and_skips_comments() {- // Prettier strips redundant quotes from keys that are valid JS- // identifiers, so the canonical form for a simple key like- // `health_snapshot` is unquoted. The parser must accept both- // `'foo':` and bare `foo:`, and must ignore `//` comment lines- // in the LEGACY_METHOD_ALIASES body.- let source = "export const CORE_RPC_METHODS = {\n alphaMethod: 'openhuman.alpha',\n betaMethod: 'openhuman.beta',\n} as const;\n\nexport const LEGACY_METHOD_ALIASES: Record<string, CoreRpcMethod> = {\n // legacy aliases for the alpha method\n 'openhuman.legacy_alpha': CORE_RPC_METHODS.alphaMethod,\n beta_legacy: CORE_RPC_METHODS.betaMethod,\n};\n";- let core_methods = parse_core_rpc_methods(source);- let aliases = parse_frontend_legacy_aliases(source, &core_methods);- assert_eq!(- aliases.get("openhuman.legacy_alpha").map(String::as_str),- Some("openhuman.alpha"),- "quoted-key entry should still resolve"- );- assert_eq!(- aliases.get("beta_legacy").map(String::as_str),- Some("openhuman.beta"),- "bare-identifier key should resolve (Prettier-normalized form)"- );- assert!(- !aliases- .keys()- .any(|k| k.contains("//") || k.contains("legacy aliases")),- "comment text must not be captured as a key"- );- }-- #[test]- #[should_panic(expected = "legacy alias references unknown CORE_RPC_METHODS")]- fn parse_frontend_legacy_aliases_panics_on_unknown_core_method_ref() {- let source = "export const CORE_RPC_METHODS = {\n alphaMethod: 'openhuman.alpha',\n} as const;\n\nexport const LEGACY_METHOD_ALIASES: Record<string, CoreRpcMethod> = {\n 'openhuman.legacy_alpha': CORE_RPC_METHODS.doesNotExist,\n};\n";- let core_methods = parse_core_rpc_methods(source);- let _ = parse_frontend_legacy_aliases(source, &core_methods);- }-- #[test]- fn resolve_legacy_rewrites_every_table_entry() {- for (legacy, canonical) in LEGACY_ALIASES {- assert_eq!(- resolve_legacy(legacy),- *canonical,- "expected legacy alias {legacy} to resolve to {canonical}",- );+use super::*;+use std::collections::{BTreeMap, BTreeSet};+use std::fs;+use std::path::PathBuf;++fn frontend_rpc_catalog_path() -> PathBuf {+ PathBuf::from(env!("OPENHUMAN_REPOSITORY_ROOT")).join("app/src/services/rpcMethods.ts")+}++fn read_frontend_rpc_catalog() -> String {+ let path = frontend_rpc_catalog_path();+ fs::read_to_string(&path)+ .unwrap_or_else(|err| panic!("failed to read {}: {err}", path.display()))+}++fn object_body_after_marker<'a>(source: &'a str, marker: &str, terminator: &str) -> &'a str {+ let marker_start = source+ .find(marker)+ .unwrap_or_else(|| panic!("missing marker `{marker}` in frontend RPC catalog"));+ let object_start = marker_start+ + source[marker_start..]+ .find('{')+ .unwrap_or_else(|| panic!("missing object start after `{marker}`"))+ + 1;+ let rest = &source[object_start..];+ let object_end = rest+ .find(terminator)+ .unwrap_or_else(|| panic!("missing terminator `{terminator}` after `{marker}`"));+ &rest[..object_end]+}++fn quoted_value(text: &str) -> String {+ let (quote_index, quote) = text+ .char_indices()+ .find(|(_, ch)| *ch == '\'' || *ch == '"')+ .unwrap_or_else(|| panic!("expected quoted value in `{text}`"));+ let value_start = quote_index + quote.len_utf8();+ let rest = &text[value_start..];+ let value_end = rest+ .find(quote)+ .unwrap_or_else(|| panic!("unterminated quoted value in `{text}`"));+ rest[..value_end].to_string()+}++fn parse_core_rpc_methods(source: &str) -> BTreeMap<String, String> {+ let body = object_body_after_marker(source, "export const CORE_RPC_METHODS", "} as const;");+ let mut methods = BTreeMap::new();+ for line in body.lines().map(str::trim).filter(|line| !line.is_empty()) {+ if line.starts_with("//") {+ continue;}- }-- #[test]- fn resolve_legacy_rewrites_composio_trigger_settings() {- // The specific case observed in Sentry: older bundles called the- // bare `openhuman.update_composio_trigger_settings` against a core- // that only registers the namespaced form.+ let (key, value) = line+ .split_once(':')+ .unwrap_or_else(|| panic!("malformed CORE_RPC_METHODS entry: `{line}`"));+ methods.insert(key.trim().to_string(), quoted_value(value));+ }+ methods+}++fn parse_frontend_legacy_aliases(+ source: &str,+ core_methods: &BTreeMap<String, String>,+) -> BTreeMap<String, String> {+ let body = object_body_after_marker(source, "export const LEGACY_METHOD_ALIASES", "};");+ let compact = body+ .lines()+ .map(str::trim)+ .filter(|line| !line.is_empty() && !line.starts_with("//"))+ .collect::<Vec<_>>()+ .join(" ");+ let mut aliases = BTreeMap::new();+ for entry in compact+ .split(',')+ .map(str::trim)+ .filter(|entry| !entry.is_empty())+ {+ let (legacy, target_expr) = entry+ .split_once(':')+ .unwrap_or_else(|| panic!("expected legacy alias entry, got `{entry}`"));+ // Prettier strips quotes from keys that are valid JS identifiers+ // (e.g. `health_snapshot`), so accept both `'foo':` and bare `foo:`.+ let legacy_trimmed = legacy.trim();+ let legacy = if legacy_trimmed.starts_with('\'') || legacy_trimmed.starts_with('"') {+ quoted_value(legacy)+ } else {+ legacy_trimmed.to_string()+ };+ let target_expr = target_expr.trim();+ let canonical = if let Some(key) = target_expr.strip_prefix("CORE_RPC_METHODS.") {+ core_methods+ .get(key)+ .unwrap_or_else(|| panic!("legacy alias references unknown CORE_RPC_METHODS.{key}"))+ .clone()+ } else {+ quoted_value(target_expr)+ };+ aliases.insert(legacy, canonical);+ }+ aliases+}++fn registered_http_methods() -> BTreeSet<String> {+ crate::core::all::all_http_method_schemas()+ .into_iter()+ .map(|method| method.method)+ .collect()+}++/// Whether `method`'s controller is compiled out of THIS build by a+/// default-ON Cargo feature gate.+///+/// The frontend RPC catalog and the alias table below are both **data**:+/// they are authored against the full (shipped desktop) surface and cannot+/// be `#[cfg]`'d per Rust feature — the frontend is built independently of+/// the core's feature set, and the shipped app always enables `mcp`. So in+/// a slim build they legitimately still name methods whose controllers no+/// longer exist. The drift checks below must therefore ignore exactly those+/// namespaces, and keep asserting on everything else — otherwise the whole+/// drift signal is lost in slim builds (or, worse, someone "fixes" the+/// failure by deleting live frontend methods from the catalog).+///+/// Mirrors how the agent loader tolerates the orchestrator TOML's dangling+/// `mcp_agent` subagent id (#4799). Composed from one predicate per gate so+/// each new gate adds a self-contained pair (keeps the attribute-`#[cfg]`+/// form the feature-gate smoke lane's coverage guard tracks).+fn is_compiled_out_method(method: &str) -> bool {+ mcp_method_compiled_out(method) || channels_method_compiled_out(method)+}++#[cfg(feature = "mcp")]+fn mcp_method_compiled_out(_method: &str) -> bool {+ false+}++#[cfg(not(feature = "mcp"))]+fn mcp_method_compiled_out(method: &str) -> bool {+ // `mcp` feature OFF ⇒ the `mcp_clients` (dynamic registry) and+ // `mcp_audit` (write log) controllers are unregistered.+ method.starts_with("openhuman.mcp_clients_") || method.starts_with("openhuman.mcp_audit_")+}++#[cfg(feature = "channels")]+fn channels_method_compiled_out(_method: &str) -> bool {+ false+}++#[cfg(not(feature = "channels"))]+fn channels_method_compiled_out(method: &str) -> bool {+ // `channels` feature OFF ⇒ the channels + webview_notifications+ // controllers are unregistered (#4801). NOTE: the in-app web chat+ // (`openhuman.channel_*`) is NOT gated (core product surface, #5002) —+ // do not add that prefix here.+ method.starts_with("openhuman.channels_")+ || method.starts_with("openhuman.webview_notifications_")+}++#[test]+fn quoted_value_extracts_single_quoted_string() {+ assert_eq!(quoted_value(": 'hello'"), "hello");+}++#[test]+fn quoted_value_extracts_double_quoted_string() {+ assert_eq!(quoted_value(": \"hello\""), "hello");+}++#[test]+#[should_panic(expected = "expected quoted value")]+fn quoted_value_panics_on_unquoted_text() {+ let _ = quoted_value(": bare-token");+}++#[test]+#[should_panic(expected = "unterminated quoted value")]+fn quoted_value_panics_on_unterminated_quote() {+ let _ = quoted_value(": 'open-but-never-closed");+}++#[test]+fn object_body_after_marker_returns_inner_body() {+ let source = "noise\nexport const FOO = {\n alpha: 'a',\n beta: 'b',\n} as const;\nrest";+ let body = object_body_after_marker(source, "export const FOO", "} as const;");+ assert!(body.contains("alpha: 'a'"));+ assert!(body.contains("beta: 'b'"));+ assert!(!body.contains("rest"));+ assert!(!body.contains("noise"));+}++#[test]+#[should_panic(expected = "missing marker")]+fn object_body_after_marker_panics_when_marker_absent() {+ let _ = object_body_after_marker("nothing here", "export const MISSING", "};");+}++#[test]+#[should_panic(expected = "missing terminator")]+fn object_body_after_marker_panics_when_terminator_absent() {+ let _ = object_body_after_marker(+ "export const FOO = { alpha: 'a',",+ "export const FOO",+ "} as const;",+ );+}++#[test]+fn parse_core_rpc_methods_extracts_entries_and_skips_comments() {+ let source = "export const CORE_RPC_METHODS = {\n // a comment that should be skipped\n alphaMethod: 'openhuman.alpha',\n betaMethod: 'openhuman.beta',\n} as const;\n";+ let methods = parse_core_rpc_methods(source);+ assert_eq!(+ methods.get("alphaMethod").map(String::as_str),+ Some("openhuman.alpha")+ );+ assert_eq!(+ methods.get("betaMethod").map(String::as_str),+ Some("openhuman.beta")+ );+ assert_eq!(methods.len(), 2);+}++#[test]+#[should_panic(expected = "malformed CORE_RPC_METHODS entry")]+fn parse_core_rpc_methods_panics_on_non_colon_line() {+ let source =+ "export const CORE_RPC_METHODS = {\n alphaMethod 'openhuman.alpha',\n} as const;\n";+ let _ = parse_core_rpc_methods(source);+}++#[test]+fn parse_frontend_legacy_aliases_resolves_core_method_refs_and_literals() {+ let source = "export const CORE_RPC_METHODS = {\n alphaMethod: 'openhuman.alpha',\n} as const;\n\nexport const LEGACY_METHOD_ALIASES: Record<string, CoreRpcMethod> = {\n 'openhuman.legacy_alpha': CORE_RPC_METHODS.alphaMethod,\n 'openhuman.legacy_literal': 'openhuman.literal_target',\n};\n";+ let core_methods = parse_core_rpc_methods(source);+ let aliases = parse_frontend_legacy_aliases(source, &core_methods);+ assert_eq!(+ aliases.get("openhuman.legacy_alpha").map(String::as_str),+ Some("openhuman.alpha")+ );+ assert_eq!(+ aliases.get("openhuman.legacy_literal").map(String::as_str),+ Some("openhuman.literal_target")+ );+}++#[test]+fn parse_frontend_legacy_aliases_accepts_bare_identifier_keys_and_skips_comments() {+ // Prettier strips redundant quotes from keys that are valid JS+ // identifiers, so the canonical form for a simple key like+ // `health_snapshot` is unquoted. The parser must accept both+ // `'foo':` and bare `foo:`, and must ignore `//` comment lines+ // in the LEGACY_METHOD_ALIASES body.+ let source = "export const CORE_RPC_METHODS = {\n alphaMethod: 'openhuman.alpha',\n betaMethod: 'openhuman.beta',\n} as const;\n\nexport const LEGACY_METHOD_ALIASES: Record<string, CoreRpcMethod> = {\n // legacy aliases for the alpha method\n 'openhuman.legacy_alpha': CORE_RPC_METHODS.alphaMethod,\n beta_legacy: CORE_RPC_METHODS.betaMethod,\n};\n";+ let core_methods = parse_core_rpc_methods(source);+ let aliases = parse_frontend_legacy_aliases(source, &core_methods);+ assert_eq!(+ aliases.get("openhuman.legacy_alpha").map(String::as_str),+ Some("openhuman.alpha"),+ "quoted-key entry should still resolve"+ );+ assert_eq!(+ aliases.get("beta_legacy").map(String::as_str),+ Some("openhuman.beta"),+ "bare-identifier key should resolve (Prettier-normalized form)"+ );+ assert!(+ !aliases+ .keys()+ .any(|k| k.contains("//") || k.contains("legacy aliases")),+ "comment text must not be captured as a key"+ );+}++#[test]+#[should_panic(expected = "legacy alias references unknown CORE_RPC_METHODS")]+fn parse_frontend_legacy_aliases_panics_on_unknown_core_method_ref() {+ let source = "export const CORE_RPC_METHODS = {\n alphaMethod: 'openhuman.alpha',\n} as const;\n\nexport const LEGACY_METHOD_ALIASES: Record<string, CoreRpcMethod> = {\n 'openhuman.legacy_alpha': CORE_RPC_METHODS.doesNotExist,\n};\n";+ let core_methods = parse_core_rpc_methods(source);+ let _ = parse_frontend_legacy_aliases(source, &core_methods);+}++#[test]+fn resolve_legacy_rewrites_every_table_entry() {+ for (legacy, canonical) in LEGACY_ALIASES {assert_eq!(- resolve_legacy("openhuman.update_composio_trigger_settings"),- "openhuman.config_update_composio_trigger_settings",+ resolve_legacy(legacy),+ *canonical,+ "expected legacy alias {legacy} to resolve to {canonical}",);}-- #[test]- fn resolve_legacy_rewrites_bare_health_snapshot() {- // Sentry CORE-RUST-FG: older clients (and some SDK callers) issued- // `health_snapshot` without the `openhuman.` namespace prefix. The- // alias table must rewrite it to the canonical form so the call- // resolves against the registered controller.+}++#[test]+fn resolve_legacy_rewrites_composio_trigger_settings() {+ // The specific case observed in Sentry: older bundles called the+ // bare `openhuman.update_composio_trigger_settings` against a core+ // that only registers the namespaced form.+ assert_eq!(+ resolve_legacy("openhuman.update_composio_trigger_settings"),+ "openhuman.config_update_composio_trigger_settings",+ );+}++#[test]+fn resolve_legacy_rewrites_bare_health_snapshot() {+ // Sentry CORE-RUST-FG: older clients (and some SDK callers) issued+ // `health_snapshot` without the `openhuman.` namespace prefix. The+ // alias table must rewrite it to the canonical form so the call+ // resolves against the registered controller.+ assert_eq!(+ resolve_legacy("health_snapshot"),+ "openhuman.health_snapshot",+ );+}++#[test]+fn resolve_legacy_rewrites_health_probe_variants() {+ // #3566 / Sentry CORE-2C: older clients and SDK callers issued the+ // health snapshot under several legacy spellings (bare `health`, and+ // the dotted `health.snapshot` / `health.status` / `health.get`).+ // There is no distinct status/get handler, so every variant must+ // resolve to the canonical `openhuman.health_snapshot`.+ for legacy in ["health", "health.get", "health.snapshot", "health.status"] {assert_eq!(- resolve_legacy("health_snapshot"),+ resolve_legacy(legacy),"openhuman.health_snapshot",+ "expected health probe variant {legacy} to resolve to the snapshot method",);}-- #[test]- fn resolve_legacy_rewrites_health_probe_variants() {- // #3566 / Sentry CORE-2C: older clients and SDK callers issued the- // health snapshot under several legacy spellings (bare `health`, and- // the dotted `health.snapshot` / `health.status` / `health.get`).- // There is no distinct status/get handler, so every variant must- // resolve to the canonical `openhuman.health_snapshot`.- for legacy in ["health", "health.get", "health.snapshot", "health.status"] {- assert_eq!(- resolve_legacy(legacy),- "openhuman.health_snapshot",- "expected health probe variant {legacy} to resolve to the snapshot method",- );- }- }-- #[test]- fn resolve_legacy_bare_health_snapshot_regression() {- // Sentry CORE-2C regression guard: bare `health_snapshot` (no- // namespace prefix) must keep resolving to the canonical method. The- // CORE-2C events were stale (release 0.53.43 predated the alias added- // in #2853), but this lock-in proves the alias still fires on the- // exact-match resolver so the bare form can never regress.- assert_eq!(- resolve_legacy("health_snapshot"),- "openhuman.health_snapshot",- );- }-- #[test]- fn resolve_legacy_rewrites_system_info() {- // Sentry CORE-RUST-G0: older clients called `openhuman.system_info`- // before the method was namespaced under `health` as- // `openhuman.health_system_info`. The alias table must rewrite it so- // the call resolves against the registered controller.- assert_eq!(- resolve_legacy("openhuman.system_info"),- "openhuman.health_system_info",- );- }-- #[test]- fn resolve_legacy_passes_through_unknown_methods() {- assert_eq!(- resolve_legacy("openhuman.memory_list_namespaces"),- "openhuman.memory_list_namespaces"- );- assert_eq!(resolve_legacy("does.not.exist"), "does.not.exist");- assert_eq!(resolve_legacy(""), "");- }-- #[test]- fn resolve_legacy_is_idempotent_for_canonical_names() {- // Canonical names already match what the registry expects;- // running them through the resolver must be a no-op so callers- // can wrap the lookup unconditionally.- for (_, canonical) in LEGACY_ALIASES {- assert_eq!(- resolve_legacy(canonical),- *canonical,- "canonical {canonical} must pass through unchanged",- );- }- }-- #[test]- fn resolve_legacy_returned_str_equals_table_value() {- // Sanity check: the function returns the canonical str slice from- // the table when it matches, not a copy of the input.- let out = resolve_legacy("openhuman.ping");- assert_eq!(out, "core.ping");- }-- #[test]- fn resolve_legacy_rewrites_dotted_channel_list_aliases() {- assert_eq!(resolve_legacy("channels.list"), "openhuman.channels_list");- assert_eq!(- resolve_legacy("openhuman.channels.list"),- "openhuman.channels_list"- );- }-- #[test]- fn resolve_legacy_rewrites_tool_registry_diagnostics() {- // #3294: the dotted `tool_registry.diagnostics` spelling sent by older- // desktop bundles must resolve to the canonical controller name so the- // Tool Policy diagnostics panel works instead of failing with- // "unknown method".+}++#[test]+fn resolve_legacy_bare_health_snapshot_regression() {+ // Sentry CORE-2C regression guard: bare `health_snapshot` (no+ // namespace prefix) must keep resolving to the canonical method. The+ // CORE-2C events were stale (release 0.53.43 predated the alias added+ // in #2853), but this lock-in proves the alias still fires on the+ // exact-match resolver so the bare form can never regress.+ assert_eq!(+ resolve_legacy("health_snapshot"),+ "openhuman.health_snapshot",+ );+}++#[test]+fn resolve_legacy_rewrites_system_info() {+ // Sentry CORE-RUST-G0: older clients called `openhuman.system_info`+ // before the method was namespaced under `health` as+ // `openhuman.health_system_info`. The alias table must rewrite it so+ // the call resolves against the registered controller.+ assert_eq!(+ resolve_legacy("openhuman.system_info"),+ "openhuman.health_system_info",+ );+}++#[test]+fn resolve_legacy_passes_through_unknown_methods() {+ assert_eq!(+ resolve_legacy("openhuman.memory_list_namespaces"),+ "openhuman.memory_list_namespaces"+ );+ assert_eq!(resolve_legacy("does.not.exist"), "does.not.exist");+ assert_eq!(resolve_legacy(""), "");+}++#[test]+fn resolve_legacy_is_idempotent_for_canonical_names() {+ // Canonical names already match what the registry expects;+ // running them through the resolver must be a no-op so callers+ // can wrap the lookup unconditionally.+ for (_, canonical) in LEGACY_ALIASES {assert_eq!(- resolve_legacy("tool_registry.diagnostics"),- "openhuman.tool_registry_diagnostics"+ resolve_legacy(canonical),+ *canonical,+ "canonical {canonical} must pass through unchanged",);}-- #[test]- fn frontend_core_rpc_methods_exist_in_core_schema_registry() {- let source = read_frontend_rpc_catalog();- let core_methods = parse_core_rpc_methods(&source);- let registered = registered_http_methods();- let missing: Vec<_> = core_methods- .values()- .filter(|method| !registered.contains(*method))- .filter(|method| !is_compiled_out_method(method))- .cloned()- .collect();-- assert!(+}++#[test]+fn resolve_legacy_returned_str_equals_table_value() {+ // Sanity check: the function returns the canonical str slice from+ // the table when it matches, not a copy of the input.+ let out = resolve_legacy("openhuman.ping");+ assert_eq!(out, "core.ping");+}++#[test]+fn resolve_legacy_rewrites_dotted_channel_list_aliases() {+ assert_eq!(resolve_legacy("channels.list"), "openhuman.channels_list");+ assert_eq!(+ resolve_legacy("openhuman.channels.list"),+ "openhuman.channels_list"+ );+}++#[test]+fn resolve_legacy_rewrites_tool_registry_diagnostics() {+ // #3294: the dotted `tool_registry.diagnostics` spelling sent by older+ // desktop bundles must resolve to the canonical controller name so the+ // Tool Policy diagnostics panel works instead of failing with+ // "unknown method".+ assert_eq!(+ resolve_legacy("tool_registry.diagnostics"),+ "openhuman.tool_registry_diagnostics"+ );+}++#[test]+fn frontend_core_rpc_methods_exist_in_core_schema_registry() {+ let source = read_frontend_rpc_catalog();+ let core_methods = parse_core_rpc_methods(&source);+ let registered = registered_http_methods();+ let missing: Vec<_> = core_methods+ .values()+ .filter(|method| !registered.contains(*method))+ .filter(|method| !is_compiled_out_method(method))+ .cloned()+ .collect();++ assert!(missing.is_empty(),"frontend CORE_RPC_METHODS contains methods absent from all_http_method_schemas(): {missing:?}");- }-- #[test]- fn frontend_legacy_aliases_match_server_alias_table() {- let source = read_frontend_rpc_catalog();- let core_methods = parse_core_rpc_methods(&source);- let frontend_aliases = parse_frontend_legacy_aliases(&source, &core_methods);- let server_aliases: BTreeMap<String, String> = legacy_aliases()- .iter()- .map(|(legacy, canonical)| ((*legacy).to_string(), (*canonical).to_string()))- .collect();-- assert_eq!(+}++#[test]+fn frontend_legacy_aliases_match_server_alias_table() {+ let source = read_frontend_rpc_catalog();+ let core_methods = parse_core_rpc_methods(&source);+ let frontend_aliases = parse_frontend_legacy_aliases(&source, &core_methods);+ let server_aliases: BTreeMap<String, String> = legacy_aliases()+ .iter()+ .map(|(legacy, canonical)| ((*legacy).to_string(), (*canonical).to_string()))+ .collect();++ assert_eq!(frontend_aliases, server_aliases,"frontend LEGACY_METHOD_ALIASES must stay in sync with crates/openhuman-core/src/core/legacy_aliases.rs");- }-- #[test]- fn legacy_alias_targets_exist_in_core_schema_registry() {- let registered = registered_http_methods();- let missing: Vec<_> = legacy_aliases()- .iter()- .filter(|(_, canonical)| !registered.contains(*canonical))- .filter(|(_, canonical)| !is_compiled_out_method(canonical))- .map(|(legacy, canonical)| format!("{legacy} -> {canonical}"))- .collect();-- assert!(- missing.is_empty(),- "legacy aliases point at methods absent from all_http_method_schemas(): {missing:?}"- );- }+}++#[test]+fn legacy_alias_targets_exist_in_core_schema_registry() {+ let registered = registered_http_methods();+ let missing: Vec<_> = legacy_aliases()+ .iter()+ .filter(|(_, canonical)| !registered.contains(*canonical))+ .filter(|(_, canonical)| !is_compiled_out_method(canonical))+ .map(|(legacy, canonical)| format!("{legacy} -> {canonical}"))+ .collect();++ assert!(+ missing.is_empty(),+ "legacy aliases point at methods absent from all_http_method_schemas(): {missing:?}"+ );+}diff --git a/crates/openhuman-core/src/core/log_redaction.rs b/crates/openhuman-core/src/core/log_redaction.rsindex 5ad0a001f1..a8af0a1c0d 100644--- a/crates/openhuman-core/src/core/log_redaction.rs+++ b/crates/openhuman-core/src/core/log_redaction.rs@@ -65,4 +65,3 @@ pub fn scrub_secrets(input: &str) -> String {#[cfg(test)]#[path = "log_redaction_tests.rs"]mod tests;-diff --git a/crates/openhuman-core/src/core/log_redaction_tests.rs b/crates/openhuman-core/src/core/log_redaction_tests.rsindex ba0f2b05ee..4055fe29f4 100644--- a/crates/openhuman-core/src/core/log_redaction_tests.rs+++ b/crates/openhuman-core/src/core/log_redaction_tests.rs@@ -1,40 +1,40 @@- use super::scrub_secrets;+use super::scrub_secrets;- #[test]- fn scrubs_bearer_token() {- assert_eq!(- scrub_secrets("Authorization: Bearer abc123xyz"),- "Authorization: Bearer [REDACTED]"- );- }+#[test]+fn scrubs_bearer_token() {+ assert_eq!(+ scrub_secrets("Authorization: Bearer abc123xyz"),+ "Authorization: Bearer [REDACTED]"+ );+}- #[test]- fn scrubs_api_key_assignment() {- assert_eq!(scrub_secrets("api_key=sk-abc123"), "api_key=[REDACTED]");- }+#[test]+fn scrubs_api_key_assignment() {+ assert_eq!(scrub_secrets("api_key=sk-abc123"), "api_key=[REDACTED]");+}- #[test]- fn scrubs_anthropic_key() {- assert_eq!(- scrub_secrets("key: sk-ant-api03-abcdefghijklmnop"),- "key: [REDACTED]"- );- }+#[test]+fn scrubs_anthropic_key() {+ assert_eq!(+ scrub_secrets("key: sk-ant-api03-abcdefghijklmnop"),+ "key: [REDACTED]"+ );+}- #[test]- fn scrubs_bare_generic_sk_key() {- assert_eq!(scrub_secrets("sk-abcdefghijklmnopqrstuvwx"), "[REDACTED]");- }+#[test]+fn scrubs_bare_generic_sk_key() {+ assert_eq!(scrub_secrets("sk-abcdefghijklmnopqrstuvwx"), "[REDACTED]");+}- #[test]- fn scrubs_generic_sk_key_with_separators() {- // A `_` or `-` mid-suffix must not leave a trailing fragment unredacted.- assert_eq!(scrub_secrets("sk-abcdefghijklmnopqrst_uv"), "[REDACTED]");- assert_eq!(scrub_secrets("sk-abcdefghij-klmnopqrst_uv"), "[REDACTED]");- }+#[test]+fn scrubs_generic_sk_key_with_separators() {+ // A `_` or `-` mid-suffix must not leave a trailing fragment unredacted.+ assert_eq!(scrub_secrets("sk-abcdefghijklmnopqrst_uv"), "[REDACTED]");+ assert_eq!(scrub_secrets("sk-abcdefghij-klmnopqrst_uv"), "[REDACTED]");+}- #[test]- fn leaves_plain_diagnostics_intact() {- let msg = "profile 42: derived rate clamp exceeded (max_iterations=8)";- assert_eq!(scrub_secrets(msg), msg);- }+#[test]+fn leaves_plain_diagnostics_intact() {+ let msg = "profile 42: derived rate clamp exceeded (max_iterations=8)";+ assert_eq!(scrub_secrets(msg), msg);+}diff --git a/crates/openhuman-core/src/core/logging.rs b/crates/openhuman-core/src/core/logging.rsindex 64a260c3c6..36fd95c159 100644--- a/crates/openhuman-core/src/core/logging.rs+++ b/crates/openhuman-core/src/core/logging.rs@@ -652,4 +652,3 @@ where#[cfg(test)]#[path = "logging_tests.rs"]mod tests;-diff --git a/crates/openhuman-core/src/core/logging_tests.rs b/crates/openhuman-core/src/core/logging_tests.rsindex d14edae157..31d465f955 100644--- a/crates/openhuman-core/src/core/logging_tests.rs+++ b/crates/openhuman-core/src/core/logging_tests.rs@@ -1,187 +1,187 @@- use super::*;-- /// Serialize tests that mutate `RUST_LOG` / `OPENHUMAN_LOG_FILE_CONSTRAINTS` —- /// Cargo runs unit tests in parallel threads in the same process, so- /// concurrent env-var writes would race.- static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());-- /// Serialize tests that mutate the process-global `FILE_GUARD` static.- /// Without this, `shutdown_file_guard_takes_installed_guard` can race- /// any concurrent test that calls `init_for_embedded` (or that itself- /// stashes / takes the guard), making one of them observe a guard it- /// did not install. Mirror of the `SCHEDULE_LOCK` pattern in- /// `crates/openhuman-app/src/reset_reboot_schedule.rs::tests`.- #[cfg(feature = "file-logging")]- static FILE_GUARD_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());-- fn with_clean_rust_log<R>(f: impl FnOnce() -> R) -> R {- let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());- let prior = std::env::var("RUST_LOG").ok();- std::env::remove_var("RUST_LOG");- let result = f();- match prior {- Some(v) => std::env::set_var("RUST_LOG", v),- None => std::env::remove_var("RUST_LOG"),- }- result- }-- #[test]- fn level_tag_covers_all_levels() {- assert_eq!(level_tag(&Level::ERROR), "ERR");- assert_eq!(level_tag(&Level::WARN), "WRN");- assert_eq!(level_tag(&Level::INFO), "INF");- assert_eq!(level_tag(&Level::DEBUG), "DBG");- assert_eq!(level_tag(&Level::TRACE), "TRC");- }-- #[test]- fn short_target_strips_module_path() {- assert_eq!(short_target("openhuman_core::core::rpc"), "rpc");- // Non-namespaced target stays as-is.- assert_eq!(short_target("plain"), "plain");- }-- #[test]- fn seed_rust_log_global_uses_info_by_default() {- with_clean_rust_log(|| {- seed_rust_log(false, CliLogDefault::Global);- assert_eq!(std::env::var("RUST_LOG").unwrap(), "info");- });+use super::*;++/// Serialize tests that mutate `RUST_LOG` / `OPENHUMAN_LOG_FILE_CONSTRAINTS` —+/// Cargo runs unit tests in parallel threads in the same process, so+/// concurrent env-var writes would race.+static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());++/// Serialize tests that mutate the process-global `FILE_GUARD` static.+/// Without this, `shutdown_file_guard_takes_installed_guard` can race+/// any concurrent test that calls `init_for_embedded` (or that itself+/// stashes / takes the guard), making one of them observe a guard it+/// did not install. Mirror of the `SCHEDULE_LOCK` pattern in+/// `crates/openhuman-app/src/reset_reboot_schedule.rs::tests`.+#[cfg(feature = "file-logging")]+static FILE_GUARD_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());++fn with_clean_rust_log<R>(f: impl FnOnce() -> R) -> R {+ let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());+ let prior = std::env::var("RUST_LOG").ok();+ std::env::remove_var("RUST_LOG");+ let result = f();+ match prior {+ Some(v) => std::env::set_var("RUST_LOG", v),+ None => std::env::remove_var("RUST_LOG"),}-- #[test]- fn seed_rust_log_global_uses_debug_when_verbose() {- with_clean_rust_log(|| {- seed_rust_log(true, CliLogDefault::Global);- assert_eq!(std::env::var("RUST_LOG").unwrap(), "debug");- });- }-- #[test]- fn seed_rust_log_respects_existing_value() {- let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());- let prior = std::env::var("RUST_LOG").ok();- std::env::set_var("RUST_LOG", "warn");+ result+}++#[test]+fn level_tag_covers_all_levels() {+ assert_eq!(level_tag(&Level::ERROR), "ERR");+ assert_eq!(level_tag(&Level::WARN), "WRN");+ assert_eq!(level_tag(&Level::INFO), "INF");+ assert_eq!(level_tag(&Level::DEBUG), "DBG");+ assert_eq!(level_tag(&Level::TRACE), "TRC");+}++#[test]+fn short_target_strips_module_path() {+ assert_eq!(short_target("openhuman_core::core::rpc"), "rpc");+ // Non-namespaced target stays as-is.+ assert_eq!(short_target("plain"), "plain");+}++#[test]+fn seed_rust_log_global_uses_info_by_default() {+ with_clean_rust_log(|| {+ seed_rust_log(false, CliLogDefault::Global);+ assert_eq!(std::env::var("RUST_LOG").unwrap(), "info");+ });+}++#[test]+fn seed_rust_log_global_uses_debug_when_verbose() {+ with_clean_rust_log(|| {seed_rust_log(true, CliLogDefault::Global);- // Caller's existing setting must not be clobbered.- assert_eq!(std::env::var("RUST_LOG").unwrap(), "warn");- match prior {- Some(v) => std::env::set_var("RUST_LOG", v),- None => std::env::remove_var("RUST_LOG"),- }+ assert_eq!(std::env::var("RUST_LOG").unwrap(), "debug");+ });+}++#[test]+fn seed_rust_log_respects_existing_value() {+ let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());+ let prior = std::env::var("RUST_LOG").ok();+ std::env::set_var("RUST_LOG", "warn");+ seed_rust_log(true, CliLogDefault::Global);+ // Caller's existing setting must not be clobbered.+ assert_eq!(std::env::var("RUST_LOG").unwrap(), "warn");+ match prior {+ Some(v) => std::env::set_var("RUST_LOG", v),+ None => std::env::remove_var("RUST_LOG"),}-- #[test]- fn build_env_filter_returns_a_filter() {- // Smoke test: shouldn't panic and should produce *some* filter regardless of inputs.- let _ = build_env_filter(false, CliLogDefault::Global);- let _ = build_env_filter(true, CliLogDefault::Global);+}++#[test]+fn build_env_filter_returns_a_filter() {+ // Smoke test: shouldn't panic and should produce *some* filter regardless of inputs.+ let _ = build_env_filter(false, CliLogDefault::Global);+ let _ = build_env_filter(true, CliLogDefault::Global);+}++#[test]+fn parse_log_file_constraints_handles_csv_and_whitespace() {+ let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());+ let prior = std::env::var("OPENHUMAN_LOG_FILE_CONSTRAINTS").ok();+ std::env::set_var("OPENHUMAN_LOG_FILE_CONSTRAINTS", "rpc, , agent ,memory");+ let parsed = parse_log_file_constraints();+ assert_eq!(parsed, vec!["rpc", "agent", "memory"]);++ std::env::remove_var("OPENHUMAN_LOG_FILE_CONSTRAINTS");+ assert!(parse_log_file_constraints().is_empty());++ match prior {+ Some(v) => std::env::set_var("OPENHUMAN_LOG_FILE_CONSTRAINTS", v),+ None => std::env::remove_var("OPENHUMAN_LOG_FILE_CONSTRAINTS"),}-- #[test]- fn parse_log_file_constraints_handles_csv_and_whitespace() {- let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());- let prior = std::env::var("OPENHUMAN_LOG_FILE_CONSTRAINTS").ok();- std::env::set_var("OPENHUMAN_LOG_FILE_CONSTRAINTS", "rpc, , agent ,memory");- let parsed = parse_log_file_constraints();- assert_eq!(parsed, vec!["rpc", "agent", "memory"]);-- std::env::remove_var("OPENHUMAN_LOG_FILE_CONSTRAINTS");- assert!(parse_log_file_constraints().is_empty());-- match prior {- Some(v) => std::env::set_var("OPENHUMAN_LOG_FILE_CONSTRAINTS", v),- None => std::env::remove_var("OPENHUMAN_LOG_FILE_CONSTRAINTS"),- }- }-- #[test]- fn log_directory_is_none_before_init_for_embedded() {- // In a fresh `cargo test` process where no test has called- // `init_for_embedded`, `log_directory()` must return `None` so the- // shell-side `reveal_logs_folder` command can surface a clear- // error rather than launching against an empty path.- if LOG_DIR.get().is_none() {- assert!(log_directory().is_none());- }- }-- // Constructs a real `tracing_appender` appender, so it only exists when- // the crate does.- #[cfg(feature = "file-logging")]- #[test]- fn shutdown_file_guard_takes_installed_guard() {- let _g = FILE_GUARD_LOCK.lock().unwrap_or_else(|e| e.into_inner());-- // Simulate `init_for_embedded` having stashed a writer guard, then- // assert that `shutdown_file_guard` empties the slot and reports- // truthfully.- let dir = tempfile::tempdir().expect("tempdir for guard test");- let appender = tracing_appender::rolling::Builder::new()- .rotation(tracing_appender::rolling::Rotation::DAILY)- .filename_prefix("guard-test")- .filename_suffix("log")- .build(dir.path())- .expect("rolling appender for guard test");- let (_writer, guard) = tracing_appender::non_blocking(appender);- {- let mut slot = FILE_GUARD.lock().expect("file guard mutex poisoned");- // Save any pre-existing guard (a prior test in this process may- // have installed one) and restore it after the assertion runs.- let prior = slot.replace(guard);- drop(slot);-- assert!(- shutdown_file_guard(),- "expected shutdown_file_guard to take the installed guard"- );- assert!(- !shutdown_file_guard(),- "second call must be a no-op when the slot is already empty"- );-- // Restore the prior guard so unrelated tests that depend on- // `init_for_embedded` having installed one are not surprised.- if let Ok(mut slot) = FILE_GUARD.lock() {- *slot = prior;- }- }+}++#[test]+fn log_directory_is_none_before_init_for_embedded() {+ // In a fresh `cargo test` process where no test has called+ // `init_for_embedded`, `log_directory()` must return `None` so the+ // shell-side `reveal_logs_folder` command can surface a clear+ // error rather than launching against an empty path.+ if LOG_DIR.get().is_none() {+ assert!(log_directory().is_none());}+}++// Constructs a real `tracing_appender` appender, so it only exists when+// the crate does.+#[cfg(feature = "file-logging")]+#[test]+fn shutdown_file_guard_takes_installed_guard() {+ let _g = FILE_GUARD_LOCK.lock().unwrap_or_else(|e| e.into_inner());++ // Simulate `init_for_embedded` having stashed a writer guard, then+ // assert that `shutdown_file_guard` empties the slot and reports+ // truthfully.+ let dir = tempfile::tempdir().expect("tempdir for guard test");+ let appender = tracing_appender::rolling::Builder::new()+ .rotation(tracing_appender::rolling::Rotation::DAILY)+ .filename_prefix("guard-test")+ .filename_suffix("log")+ .build(dir.path())+ .expect("rolling appender for guard test");+ let (_writer, guard) = tracing_appender::non_blocking(appender);+ {+ let mut slot = FILE_GUARD.lock().expect("file guard mutex poisoned");+ // Save any pre-existing guard (a prior test in this process may+ // have installed one) and restore it after the assertion runs.+ let prior = slot.replace(guard);+ drop(slot);++ assert!(+ shutdown_file_guard(),+ "expected shutdown_file_guard to take the installed guard"+ );+ assert!(+ !shutdown_file_guard(),+ "second call must be a no-op when the slot is already empty"+ );- #[test]- fn tui_log_writer_keeps_a_bounded_ordered_ring() {- let buffer = std::sync::Arc::new(Mutex::new(VecDeque::new()));- let mut writer = TuiLogWriter {- buffer: buffer.clone(),- pending: Vec::new(),- };- for index in 0..=TUI_LOG_CAPACITY {- writeln!(writer, "line-{index}").expect("write log line");- writer.flush().expect("flush log line");+ // Restore the prior guard so unrelated tests that depend on+ // `init_for_embedded` having installed one are not surprised.+ if let Ok(mut slot) = FILE_GUARD.lock() {+ *slot = prior;}- let lines = buffer.lock().expect("buffer lock");- assert_eq!(lines.len(), TUI_LOG_CAPACITY);- assert_eq!(lines.front().map(String::as_str), Some("line-1"));- let expected_last = format!("line-{TUI_LOG_CAPACITY}");- assert_eq!(- lines.back().map(String::as_str),- Some(expected_last.as_str())- );}-- #[test]- fn tui_log_writer_caps_individual_lines() {- let buffer = std::sync::Arc::new(Mutex::new(VecDeque::new()));- let mut writer = TuiLogWriter {- buffer: buffer.clone(),- pending: Vec::new(),- };- writeln!(writer, "{}", "x".repeat(TUI_LOG_LINE_MAX_CHARS + 50)).expect("write long line");- writer.flush().expect("flush long line");- let lines = buffer.lock().expect("buffer lock");- assert_eq!(- lines.front().map(|line| line.chars().count()),- Some(TUI_LOG_LINE_MAX_CHARS)- );+}++#[test]+fn tui_log_writer_keeps_a_bounded_ordered_ring() {+ let buffer = std::sync::Arc::new(Mutex::new(VecDeque::new()));+ let mut writer = TuiLogWriter {+ buffer: buffer.clone(),+ pending: Vec::new(),+ };+ for index in 0..=TUI_LOG_CAPACITY {+ writeln!(writer, "line-{index}").expect("write log line");+ writer.flush().expect("flush log line");}+ let lines = buffer.lock().expect("buffer lock");+ assert_eq!(lines.len(), TUI_LOG_CAPACITY);+ assert_eq!(lines.front().map(String::as_str), Some("line-1"));+ let expected_last = format!("line-{TUI_LOG_CAPACITY}");+ assert_eq!(+ lines.back().map(String::as_str),+ Some(expected_last.as_str())+ );+}++#[test]+fn tui_log_writer_caps_individual_lines() {+ let buffer = std::sync::Arc::new(Mutex::new(VecDeque::new()));+ let mut writer = TuiLogWriter {+ buffer: buffer.clone(),+ pending: Vec::new(),+ };+ writeln!(writer, "{}", "x".repeat(TUI_LOG_LINE_MAX_CHARS + 50)).expect("write long line");+ writer.flush().expect("flush long line");+ let lines = buffer.lock().expect("buffer lock");+ assert_eq!(+ lines.front().map(|line| line.chars().count()),+ Some(TUI_LOG_LINE_MAX_CHARS)+ );+}diff --git a/crates/openhuman-core/src/core/memory_cli.rs b/crates/openhuman-core/src/core/memory_cli.rsindex 4f2dcfff58..6af9d41b07 100644--- a/crates/openhuman-core/src/core/memory_cli.rs+++ b/crates/openhuman-core/src/core/memory_cli.rs@@ -629,4 +629,3 @@ fn print_memory_help() {#[cfg(test)]#[path = "memory_cli_tests.rs"]mod tests;-diff --git a/crates/openhuman-core/src/core/memory_cli_tests.rs b/crates/openhuman-core/src/core/memory_cli_tests.rsindex 7a733aaf6b..ceffffc472 100644--- a/crates/openhuman-core/src/core/memory_cli_tests.rs+++ b/crates/openhuman-core/src/core/memory_cli_tests.rs@@ -1,190 +1,190 @@- use super::*;- use crate::core::cli_capability::{capability_verdict, CAPABILITY_UNAVAILABLE_PREFIX};- use crate::core::subsystem::DriverClass;- use tinymemory_api::capabilities::{Capabilities, Capability};+use super::*;+use crate::core::cli_capability::{capability_verdict, CAPABILITY_UNAVAILABLE_PREFIX};+use crate::core::subsystem::DriverClass;+use tinymemory_api::capabilities::{Capabilities, Capability};- /// Drift guard: a renamed controller function must break here rather than- /// silently un-gate a subcommand (`required_capability` would start- /// returning `None` for it).- #[test]- fn memory_cli_subcommands_mirror_real_controllers() {- for (sub, function) in SUBCOMMAND_CONTROLLER {- assert!(- crate::core::all::rpc_method_from_parts("memory", function).is_some(),- "`openhuman memory {sub}` maps to memory.{function}, which is not registered"- );- }+/// Drift guard: a renamed controller function must break here rather than+/// silently un-gate a subcommand (`required_capability` would start+/// returning `None` for it).+#[test]+fn memory_cli_subcommands_mirror_real_controllers() {+ for (sub, function) in SUBCOMMAND_CONTROLLER {+ assert!(+ crate::core::all::rpc_method_from_parts("memory", function).is_some(),+ "`openhuman memory {sub}` maps to memory.{function}, which is not registered"+ );}+}- /// Adding a subcommand without recording a capability decision fails here.- #[test]- fn every_dispatched_subcommand_is_in_the_controller_table() {- for sub in [- "ingest",- "docs",- "list",- "graph",- "graph-query",- "query",- "namespaces",- "ns",- "clear",- ] {- assert!(- SUBCOMMAND_CONTROLLER.iter().any(|(s, _)| *s == sub),- "`openhuman memory {sub}` is dispatched but has no controller mapping"- );- }+/// Adding a subcommand without recording a capability decision fails here.+#[test]+fn every_dispatched_subcommand_is_in_the_controller_table() {+ for sub in [+ "ingest",+ "docs",+ "list",+ "graph",+ "graph-query",+ "query",+ "namespaces",+ "ns",+ "clear",+ ] {+ assert!(+ SUBCOMMAND_CONTROLLER.iter().any(|(s, _)| *s == sub),+ "`openhuman memory {sub}` is dispatched but has no controller mapping"+ );}+}- #[test]- fn ingest_and_graph_are_the_gated_subcommands() {- assert_eq!(required_capability("ingest"), Some(Capability::Ingest));- assert_eq!(required_capability("graph"), Some(Capability::Graph));- assert_eq!(required_capability("graph-query"), Some(Capability::Graph));- // Core/recall share the Core gate so a null driver can remove the- // complete driver-backed memory surface.- for sub in ["docs", "list", "query", "namespaces", "ns", "clear"] {- assert_eq!(- required_capability(sub),- Some(Capability::Core),- "{sub} must use Core"- );- }+#[test]+fn ingest_and_graph_are_the_gated_subcommands() {+ assert_eq!(required_capability("ingest"), Some(Capability::Ingest));+ assert_eq!(required_capability("graph"), Some(Capability::Graph));+ assert_eq!(required_capability("graph-query"), Some(Capability::Graph));+ // Core/recall share the Core gate so a null driver can remove the+ // complete driver-backed memory surface.+ for sub in ["docs", "list", "query", "namespaces", "ns", "clear"] {+ assert_eq!(+ required_capability(sub),+ Some(Capability::Core),+ "{sub} must use Core"+ );}+}- /// A real typo must never be reported as a capability fact.- #[test]- fn unknown_memory_subcommand_still_reports_unknown_subcommand() {- let err = run_memory_command(&["not_a_subcommand".to_string()])- .expect_err("an unknown subcommand must error");- let msg = err.to_string();- assert!(msg.contains("unknown memory subcommand"), "{msg}");- assert!(!msg.contains(CAPABILITY_UNAVAILABLE_PREFIX), "{msg}");- assert_eq!(required_capability("not_a_subcommand"), None);+/// A real typo must never be reported as a capability fact.+#[test]+fn unknown_memory_subcommand_still_reports_unknown_subcommand() {+ let err = run_memory_command(&["not_a_subcommand".to_string()])+ .expect_err("an unknown subcommand must error");+ let msg = err.to_string();+ assert!(msg.contains("unknown memory subcommand"), "{msg}");+ assert!(!msg.contains(CAPABILITY_UNAVAILABLE_PREFIX), "{msg}");+ assert_eq!(required_capability("not_a_subcommand"), None);+}++/// `Capabilities::mandatory()` is exactly what the `null` driver advertises;+/// the set is used directly rather than through `binding::for_workspace` so+/// this file stays off the memory-guard bypass allowlist (that scanner does+/// not strip inline `#[cfg(test)]` modules). The binding-level equivalence+/// is pinned in `cli_capability_tests.rs`.+#[test]+fn gated_subcommand_reports_the_driver_and_capability() {+ let err = capability_verdict(+ "null",+ Capabilities::mandatory(),+ required_capability("ingest"),+ "openhuman memory ingest",+ )+ .expect_err("the null driver does not advertise `ingest`");+ let msg = err.to_string();+ assert!(msg.contains("null"), "{msg}");+ assert!(msg.contains("ingest"), "{msg}");+ assert!(!msg.contains("unknown memory subcommand"), "{msg}");+}++/// The default embedded driver advertises every family, so nothing changes.+#[test]+fn default_embedded_driver_gates_nothing() {+ for (sub, _) in SUBCOMMAND_CONTROLLER {+ assert!(+ capability_verdict(+ "tinycortex",+ Capabilities::all(),+ required_capability(sub),+ "openhuman memory <sub>",+ )+ .is_ok(),+ "`openhuman memory {sub}` must stay available under the default driver"+ );}+}- /// `Capabilities::mandatory()` is exactly what the `null` driver advertises;- /// the set is used directly rather than through `binding::for_workspace` so- /// this file stays off the memory-guard bypass allowlist (that scanner does- /// not strip inline `#[cfg(test)]` modules). The binding-level equivalence- /// is pinned in `cli_capability_tests.rs`.- #[test]- fn gated_subcommand_reports_the_driver_and_capability() {- let err = capability_verdict(+/// The subcommands still resolved through [`create_memory_client`], and so+/// still subject to the legacy-client gate. The rest reach the bound driver+/// through the contract, where "not the embedded engine" is not a refusal+/// reason — see [`create_memory_binding`].+const LEGACY_ENGINE_SUBCOMMANDS: &[&str] = &["ingest", "query"];++/// Every legacy subcommand — gated or not — must be rejected under a null+/// binding: they operate on the embedded store directly, and the null+/// driver is not that engine. This is the regression the reviewer flagged:+/// `openhuman memory clear` used to open the embedded DB even with+/// `driver = "null"` (and now does not open it at all).+#[test]+fn null_driver_rejects_every_legacy_subcommand() {+ for sub in LEGACY_ENGINE_SUBCOMMANDS {+ let err = crate::core::cli_capability::legacy_client_verdict("null",- Capabilities::mandatory(),- required_capability("ingest"),- "openhuman memory ingest",+ DriverClass::Null,+ &format!("openhuman memory {sub}"),)- .expect_err("the null driver does not advertise `ingest`");+ .expect_err("a null binding must reject legacy subcommands");let msg = err.to_string();assert!(msg.contains("null"), "{msg}");- assert!(msg.contains("ingest"), "{msg}");- assert!(!msg.contains("unknown memory subcommand"), "{msg}");- }-- /// The default embedded driver advertises every family, so nothing changes.- #[test]- fn default_embedded_driver_gates_nothing() {- for (sub, _) in SUBCOMMAND_CONTROLLER {- assert!(- capability_verdict(- "tinycortex",- Capabilities::all(),- required_capability(sub),- "openhuman memory <sub>",- )- .is_ok(),- "`openhuman memory {sub}` must stay available under the default driver"- );- }- }-- /// The subcommands still resolved through [`create_memory_client`], and so- /// still subject to the legacy-client gate. The rest reach the bound driver- /// through the contract, where "not the embedded engine" is not a refusal- /// reason — see [`create_memory_binding`].- const LEGACY_ENGINE_SUBCOMMANDS: &[&str] = &["ingest", "query"];-- /// Every legacy subcommand — gated or not — must be rejected under a null- /// binding: they operate on the embedded store directly, and the null- /// driver is not that engine. This is the regression the reviewer flagged:- /// `openhuman memory clear` used to open the embedded DB even with- /// `driver = "null"` (and now does not open it at all).- #[test]- fn null_driver_rejects_every_legacy_subcommand() {- for sub in LEGACY_ENGINE_SUBCOMMANDS {- let err = crate::core::cli_capability::legacy_client_verdict(- "null",- DriverClass::Null,- &format!("openhuman memory {sub}"),- )- .expect_err("a null binding must reject legacy subcommands");- let msg = err.to_string();- assert!(msg.contains("null"), "{msg}");- assert!(- msg.contains("local store"),- "refusal must explain that these subcommands read the local store: {msg}"- );- }- }-- /// Both local-store classes may serve the legacy subcommands.- ///- /// `Module` matters more than `Embedded` now: `binding::admit` refuses- /// `Embedded` outright, so the built-in driver binds as `Module` and a gate- /// that accepted only `Embedded` refused every subcommand in the field.- #[test]- fn local_store_drivers_serve_every_legacy_subcommand() {- for (driver, class) in [- ("tinycortex", DriverClass::Embedded),- ("tinymemory", DriverClass::Module),- ] {- for sub in LEGACY_ENGINE_SUBCOMMANDS {- assert!(- crate::core::cli_capability::legacy_client_verdict(- driver,- class,- &format!("openhuman memory {sub}"),- )- .is_ok(),- "`openhuman memory {sub}` must stay available under {driver} ({class:?})"- );- }- }+ assert!(+ msg.contains("local store"),+ "refusal must explain that these subcommands read the local store: {msg}"+ );}+}- /// A driver that answers from somewhere else must still be refused —- /// reading the local store there would answer from the wrong place.- #[test]- fn external_driver_still_rejects_every_legacy_subcommand() {+/// Both local-store classes may serve the legacy subcommands.+///+/// `Module` matters more than `Embedded` now: `binding::admit` refuses+/// `Embedded` outright, so the built-in driver binds as `Module` and a gate+/// that accepted only `Embedded` refused every subcommand in the field.+#[test]+fn local_store_drivers_serve_every_legacy_subcommand() {+ for (driver, class) in [+ ("tinycortex", DriverClass::Embedded),+ ("tinymemory", DriverClass::Module),+ ] {for sub in LEGACY_ENGINE_SUBCOMMANDS {assert!(crate::core::cli_capability::legacy_client_verdict(- "supermemory",- DriverClass::External,+ driver,+ class,&format!("openhuman memory {sub}"),)- .is_err(),- "`openhuman memory {sub}` must stay refused under a remote driver"+ .is_ok(),+ "`openhuman memory {sub}` must stay available under {driver} ({class:?})");}}+}- /// The legacy-client diagnostic must not leak credentials or endpoints.- #[test]- fn legacy_message_never_contains_a_credential_or_endpoint() {- use crate::core::subsystem::DriverClass;- let msg = crate::core::cli_capability::legacy_client_unavailable_message(- "supermemory",- DriverClass::External,- "openhuman memory clear",- );- assert!(!msg.contains("keychain:"), "{msg}");- assert!(!msg.contains("api.supermemory.ai"), "{msg}");+/// A driver that answers from somewhere else must still be refused —+/// reading the local store there would answer from the wrong place.+#[test]+fn external_driver_still_rejects_every_legacy_subcommand() {+ for sub in LEGACY_ENGINE_SUBCOMMANDS {assert!(- msg.starts_with(crate::core::cli_capability::LEGACY_CLIENT_UNAVAILABLE_PREFIX),- "{msg}"+ crate::core::cli_capability::legacy_client_verdict(+ "supermemory",+ DriverClass::External,+ &format!("openhuman memory {sub}"),+ )+ .is_err(),+ "`openhuman memory {sub}` must stay refused under a remote driver");}+}++/// The legacy-client diagnostic must not leak credentials or endpoints.+#[test]+fn legacy_message_never_contains_a_credential_or_endpoint() {+ use crate::core::subsystem::DriverClass;+ let msg = crate::core::cli_capability::legacy_client_unavailable_message(+ "supermemory",+ DriverClass::External,+ "openhuman memory clear",+ );+ assert!(!msg.contains("keychain:"), "{msg}");+ assert!(!msg.contains("api.supermemory.ai"), "{msg}");+ assert!(+ msg.starts_with(crate::core::cli_capability::LEGACY_CLIENT_UNAVAILABLE_PREFIX),+ "{msg}"+ );+}diff --git a/crates/openhuman-core/src/core/mod.rs b/crates/openhuman-core/src/core/mod.rsindex 679283fa3e..012408af7f 100644--- a/crates/openhuman-core/src/core/mod.rs+++ b/crates/openhuman-core/src/core/mod.rs@@ -128,4 +128,3 @@ pub enum TypeSchema {#[cfg(test)]#[path = "core_mod_tests.rs"]mod tests;-diff --git a/crates/openhuman-core/src/core/observability.rs b/crates/openhuman-core/src/core/observability.rsindex 47226f9e0e..6acd22a1b5 100644--- a/crates/openhuman-core/src/core/observability.rs+++ b/crates/openhuman-core/src/core/observability.rs@@ -3709,7 +3709,6 @@ fn parse_version(version: &str) -> Option<(u32, u32)> {Some((major, minor))}-#[cfg(test)]#[path = "observability_tests.rs"]mod tests;diff --git a/crates/openhuman-core/src/core/observability_tests.rs b/crates/openhuman-core/src/core/observability_tests.rsindex 47873de5b7..1b178a496c 100644--- a/crates/openhuman-core/src/core/observability_tests.rs+++ b/crates/openhuman-core/src/core/observability_tests.rs@@ -3,8 +3,7 @@ use super::*;#[cfg(feature = "crash-reporting")]fn event_with_tags(pairs: &[(&str, &str)]) -> sentry::protocol::Event<'static> {let mut event = sentry::protocol::Event::default();- let mut tags: std::collections::BTreeMap<String, String> =- std::collections::BTreeMap::new();+ let mut tags: std::collections::BTreeMap<String, String> = std::collections::BTreeMap::new();for (k, v) in pairs {tags.insert((*k).to_string(), (*v).to_string());}@@ -27,8 +26,7 @@ fn channel_message_404_event(method: &str) -> sentry::protocol::Event<'static> {event.tags.insert("status".into(), "404".into());event.tags.insert("method".into(), method.into());event.message = Some(- "PATCH /channels/telegram/messages/1103 failed (404); response_body_len=172"- .to_string(),+ "PATCH /channels/telegram/messages/1103 failed (404); response_body_len=172".to_string(),);event}@@ -70,7 +68,6 @@ fn event_with_exception_value(value: &str) -> sentry::protocol::Event<'static> {event}-#[path = "observability_tests_part_01.rs"]mod part_01;#[path = "observability_tests_part_02.rs"]diff --git a/crates/openhuman-core/src/core/observability_tests_part_01.rs b/crates/openhuman-core/src/core/observability_tests_part_01.rsindex 469fc75e6f..acbb25c38c 100644--- a/crates/openhuman-core/src/core/observability_tests_part_01.rs+++ b/crates/openhuman-core/src/core/observability_tests_part_01.rs@@ -537,8 +537,7 @@ fn does_not_classify_embedding_json_403_as_edge_block() {// A non-embed HTML 403 from some unrelated path must not be silenced by// this embed-scoped matcher.- let non_embed_html_403 =- "page fetch failed (403 Forbidden): <!doctype html><title>403</title>";+ let non_embed_html_403 = "page fetch failed (403 Forbidden): <!doctype html><title>403</title>";assert_eq!(expected_error_kind(non_embed_html_403),None,@@ -701,4 +700,3 @@ fn does_not_classify_unrelated_embedding_400s() {None);}-diff --git a/crates/openhuman-core/src/core/observability_tests_part_02.rs b/crates/openhuman-core/src/core/observability_tests_part_02.rsindex 5238e0afbe..62c7596b4e 100644--- a/crates/openhuman-core/src/core/observability_tests_part_02.rs+++ b/crates/openhuman-core/src/core/observability_tests_part_02.rs@@ -28,17 +28,13 @@ fn does_not_classify_unrelated_ollama_errors_as_user_config() {// Parse-failure on the response — real bug in either the server// or our deserializer, must still reach Sentry.assert_eq!(- expected_error_kind(- "ollama embed response parse failed: invalid type: expected sequence"- ),+ expected_error_kind("ollama embed response parse failed: invalid type: expected sequence"),None);// Dimension mismatch — real bug (model dims don't match what we// recorded), must still reach Sentry.assert_eq!(- expected_error_kind(- "ollama embed dimension mismatch at index 0: expected 768, got 1024"- ),+ expected_error_kind("ollama embed dimension mismatch at index 0: expected 768, got 1024"),None);// Unrelated `invalid model name` outside Ollama embed call —@@ -693,4 +689,3 @@ fn does_not_demote_config_read_notfound_or_unkeyed_failures() {Some(ExpectedErrorKind::ConfigReadIoFailure),);}-diff --git a/crates/openhuman-core/src/core/observability_tests_part_03.rs b/crates/openhuman-core/src/core/observability_tests_part_03.rsindex 0c833a2000..641cb479f7 100644--- a/crates/openhuman-core/src/core/observability_tests_part_03.rs+++ b/crates/openhuman-core/src/core/observability_tests_part_03.rs@@ -102,8 +102,7 @@ fn classifies_network_unreachable_errors() {#[test]fn custom_openai_ollama_timeout_fallback_chain_is_network_unreachable() {- let chain =- "custom_openai chat completions transport error: error sending request for url \+ let chain = "custom_openai chat completions transport error: error sending request for url \(http://localhost:11434/v1/chat/completions): operation timed out \(responses fallback failed: custom_openai API error (404 Not Found): \{\"error\":\"not found\"})";@@ -522,9 +521,7 @@ fn classifies_socket_transient_http_errors() {// socket shape so a future regression in `is_transient_upstream_http_message`// surfaces here, not behind another classifier.assert_eq!(- expected_error_kind(- "WebSocket connect: HTTP error: 502: upstream returned bad gateway"- ),+ expected_error_kind("WebSocket connect: HTTP error: 502: upstream returned bad gateway"),Some(ExpectedErrorKind::TransientUpstreamHttp));@@ -667,4 +664,3 @@ fn tool_execute_backend_401_invalid_token_does_not_hard_report() {reaches Sentry as a hard error");}-diff --git a/crates/openhuman-core/src/core/observability_tests_part_04.rs b/crates/openhuman-core/src/core/observability_tests_part_04.rsindex 071c7b53e6..62ab1b39ae 100644--- a/crates/openhuman-core/src/core/observability_tests_part_04.rs+++ b/crates/openhuman-core/src/core/observability_tests_part_04.rs@@ -657,4 +657,3 @@ fn classifies_list_models_404_as_provider_user_state() {);}}-diff --git a/crates/openhuman-core/src/core/observability_tests_part_05.rs b/crates/openhuman-core/src/core/observability_tests_part_05.rsindex 9c3679a5ab..b636458873 100644--- a/crates/openhuman-core/src/core/observability_tests_part_05.rs+++ b/crates/openhuman-core/src/core/observability_tests_part_05.rs@@ -40,8 +40,7 @@ fn couples_list_models_404_source_shape_to_classifier() {// anchor is the formatted prefix, not a bare `404` substring, so it// does NOT mis-fire on a 500 whose body merely relays an upstream// 404 (see `does_not_classify_non_404_list_models_failures_as_user_state`).- let prefixed =- "[inference::ops] list_models:error: provider returned 404: 404 page not found";+ let prefixed = "[inference::ops] list_models:error: provider returned 404: 404 page not found";assert_eq!(expected_error_kind(prefixed),Some(ExpectedErrorKind::ProviderUserState),@@ -687,4 +686,3 @@ fn skills_install_fetch_filter_keeps_server_and_wrong_shape_failures() {);}}-diff --git a/crates/openhuman-core/src/core/observability_tests_part_06.rs b/crates/openhuman-core/src/core/observability_tests_part_06.rsindex 87f7cb0989..a1083a23b0 100644--- a/crates/openhuman-core/src/core/observability_tests_part_06.rs+++ b/crates/openhuman-core/src/core/observability_tests_part_06.rs@@ -686,4 +686,3 @@ fn session_expired_before_send_stays_domain_scoped() {"non-core domains must not be filtered as backend session expiry");}-diff --git a/crates/openhuman-core/src/core/observability_tests_part_07.rs b/crates/openhuman-core/src/core/observability_tests_part_07.rsindex 8a7809e19c..ae5c5c9771 100644--- a/crates/openhuman-core/src/core/observability_tests_part_07.rs+++ b/crates/openhuman-core/src/core/observability_tests_part_07.rs@@ -688,4 +688,3 @@ fn auth_get_me_opaque_filter_tolerates_surrounding_whitespace() {"trimmed equality must still match the opaque shape");}-diff --git a/crates/openhuman-core/src/core/observability_tests_part_08.rs b/crates/openhuman-core/src/core/observability_tests_part_08.rsindex c9ea960f0d..08e425aeaf 100644--- a/crates/openhuman-core/src/core/observability_tests_part_08.rs+++ b/crates/openhuman-core/src/core/observability_tests_part_08.rs@@ -95,4 +95,3 @@ fn auth_get_me_opaque_filter_ignores_empty_and_unrelated() {"substring match must NOT trigger — strict equality only");}-diff --git a/crates/openhuman-core/src/core/rpc_log.rs b/crates/openhuman-core/src/core/rpc_log.rsindex 6093081332..a068151da1 100644--- a/crates/openhuman-core/src/core/rpc_log.rs+++ b/crates/openhuman-core/src/core/rpc_log.rs@@ -86,4 +86,3 @@ fn is_sensitive_key(key: &str) -> bool {#[cfg(test)]#[path = "rpc_log_tests.rs"]mod tests;-diff --git a/crates/openhuman-core/src/core/rpc_log_tests.rs b/crates/openhuman-core/src/core/rpc_log_tests.rsindex 3c4329c4ae..2b884f15a9 100644--- a/crates/openhuman-core/src/core/rpc_log_tests.rs+++ b/crates/openhuman-core/src/core/rpc_log_tests.rs@@ -1,20 +1,20 @@- use super::*;- use serde_json::json;+use super::*;+use serde_json::json;- #[test]- fn test_summarize_rpc_result() {- assert_eq!(- summarize_rpc_result(&json!({"b": 2, "a": 1})),- "object(keys=a,b)"- );- assert_eq!(summarize_rpc_result(&json!({})), "object(keys=)");- assert_eq!(summarize_rpc_result(&json!([1, 2, 3])), "array(len=3)");- assert_eq!(summarize_rpc_result(&json!([])), "array(len=0)");- assert_eq!(summarize_rpc_result(&json!("hello")), "string(len=5)");- assert_eq!(summarize_rpc_result(&json!("")), "string(len=0)");- assert_eq!(summarize_rpc_result(&json!(true)), "bool(true)");- assert_eq!(summarize_rpc_result(&json!(false)), "bool(false)");- assert_eq!(summarize_rpc_result(&json!(42)), "number(42)");- assert_eq!(summarize_rpc_result(&json!(3.14)), "number(3.14)");- assert_eq!(summarize_rpc_result(&json!(null)), "null");- }+#[test]+fn test_summarize_rpc_result() {+ assert_eq!(+ summarize_rpc_result(&json!({"b": 2, "a": 1})),+ "object(keys=a,b)"+ );+ assert_eq!(summarize_rpc_result(&json!({})), "object(keys=)");+ assert_eq!(summarize_rpc_result(&json!([1, 2, 3])), "array(len=3)");+ assert_eq!(summarize_rpc_result(&json!([])), "array(len=0)");+ assert_eq!(summarize_rpc_result(&json!("hello")), "string(len=5)");+ assert_eq!(summarize_rpc_result(&json!("")), "string(len=0)");+ assert_eq!(summarize_rpc_result(&json!(true)), "bool(true)");+ assert_eq!(summarize_rpc_result(&json!(false)), "bool(false)");+ assert_eq!(summarize_rpc_result(&json!(42)), "number(42)");+ assert_eq!(summarize_rpc_result(&json!(3.14)), "number(3.14)");+ assert_eq!(summarize_rpc_result(&json!(null)), "null");+}diff --git a/crates/openhuman-core/src/core/runtime/builder.rs b/crates/openhuman-core/src/core/runtime/builder.rsindex 16154a8d8f..23708c4fe5 100644--- a/crates/openhuman-core/src/core/runtime/builder.rs+++ b/crates/openhuman-core/src/core/runtime/builder.rs@@ -945,4 +945,3 @@ impl CoreRuntime {#[cfg(test)]#[path = "builder_tests.rs"]mod tests;-diff --git a/crates/openhuman-core/src/core/runtime/builder_tests.rs b/crates/openhuman-core/src/core/runtime/builder_tests.rsindex 558a1cbc6d..8af49c17b9 100644--- a/crates/openhuman-core/src/core/runtime/builder_tests.rs+++ b/crates/openhuman-core/src/core/runtime/builder_tests.rs@@ -1,180 +1,180 @@- use super::{DomainSet, ServiceSet};- use crate::core::all::DomainGroup;-- #[test]- fn domain_set_presets_have_expected_flags() {- // full() = every family on (byte-identical registration).- let full = DomainSet::full();- for group in [- DomainGroup::Agent,- DomainGroup::Memory,- DomainGroup::Threads,- DomainGroup::Config,- DomainGroup::Security,- DomainGroup::Flows,- DomainGroup::Skills,- DomainGroup::Mcp,- DomainGroup::Channels,- DomainGroup::Web3,- DomainGroup::Voice,- DomainGroup::Media,- DomainGroup::Medulla,- DomainGroup::Integrations,- DomainGroup::Platform,- ] {- assert!(full.allows(group), "full() must allow {group:?}");- }-- // harness() = exactly agent/memory/threads/config/security on; all gate- // families AND platform off.- let harness = DomainSet::harness();- for on in [- DomainGroup::Agent,- DomainGroup::Memory,- DomainGroup::Threads,- DomainGroup::Config,- DomainGroup::Security,- ] {- assert!(harness.allows(on), "harness() must allow {on:?}");- }- for off in [- DomainGroup::Flows,- DomainGroup::Skills,- DomainGroup::Mcp,- DomainGroup::Channels,- DomainGroup::Web3,- DomainGroup::Voice,- DomainGroup::Media,- DomainGroup::Medulla,- DomainGroup::Platform,- ] {- assert!(!harness.allows(off), "harness() must NOT allow {off:?}");- }-- // none() = every family off.- let none = DomainSet::none();- for group in [- DomainGroup::Agent,- DomainGroup::Memory,- DomainGroup::Threads,- DomainGroup::Config,- DomainGroup::Security,- DomainGroup::Flows,- DomainGroup::Skills,- DomainGroup::Mcp,- DomainGroup::Channels,- DomainGroup::Web3,- DomainGroup::Voice,- DomainGroup::Media,- DomainGroup::Medulla,- DomainGroup::Platform,- ] {- assert!(!none.allows(group), "none() must NOT allow {group:?}");- }-- // Spot-check the field/group wiring is not transposed.- assert!(DomainSet::harness().allows(DomainGroup::Memory));- assert!(!DomainSet::harness().allows(DomainGroup::Web3));+use super::{DomainSet, ServiceSet};+use crate::core::all::DomainGroup;++#[test]+fn domain_set_presets_have_expected_flags() {+ // full() = every family on (byte-identical registration).+ let full = DomainSet::full();+ for group in [+ DomainGroup::Agent,+ DomainGroup::Memory,+ DomainGroup::Threads,+ DomainGroup::Config,+ DomainGroup::Security,+ DomainGroup::Flows,+ DomainGroup::Skills,+ DomainGroup::Mcp,+ DomainGroup::Channels,+ DomainGroup::Web3,+ DomainGroup::Voice,+ DomainGroup::Media,+ DomainGroup::Medulla,+ DomainGroup::Integrations,+ DomainGroup::Platform,+ ] {+ assert!(full.allows(group), "full() must allow {group:?}");}- #[test]- fn embedded_domain_set_enables_the_host_families() {- let set = DomainSet::embedded();-- for on in [- DomainGroup::Agent,- DomainGroup::Memory,- DomainGroup::Threads,- DomainGroup::Config,- DomainGroup::Security,- DomainGroup::Medulla,- DomainGroup::Platform,- ] {- assert!(set.allows(on), "embedded() must allow {on:?}");- }-- for off in [- DomainGroup::Mcp,- DomainGroup::Web3,- DomainGroup::Voice,- DomainGroup::Media,- ] {- assert!(!set.allows(off), "embedded() must NOT allow {off:?}");- }+ // harness() = exactly agent/memory/threads/config/security on; all gate+ // families AND platform off.+ let harness = DomainSet::harness();+ for on in [+ DomainGroup::Agent,+ DomainGroup::Memory,+ DomainGroup::Threads,+ DomainGroup::Config,+ DomainGroup::Security,+ ] {+ assert!(harness.allows(on), "harness() must allow {on:?}");}-- #[test]- fn embedded_keeps_flows_on_for_workflow_boot_reconcile() {- // Not incidental: `medulla_workflows` runs on the tinyflows engine and- // boot reconciliation keys off `ctx.domains().flows`, not a ServiceSet- // flag. Turning this off silently strands orphaned runs.- assert!(DomainSet::embedded().allows(DomainGroup::Flows));- }-- #[test]- fn embedded_keeps_channels_on_for_web_chat() {- // `channel.web_chat` is tagged DomainGroup::Channels and the TUI drives- // chat turns through it. This is precisely why embedded() is not- // built on harness(), which leaves channels off.- assert!(DomainSet::embedded().allows(DomainGroup::Channels));+ for off in [+ DomainGroup::Flows,+ DomainGroup::Skills,+ DomainGroup::Mcp,+ DomainGroup::Channels,+ DomainGroup::Web3,+ DomainGroup::Voice,+ DomainGroup::Media,+ DomainGroup::Medulla,+ DomainGroup::Platform,+ ] {+ assert!(!harness.allows(off), "harness() must NOT allow {off:?}");}- #[test]- fn embedded_is_not_harness_plus_medulla() {- // Guards the most tempting future "simplification": deriving this- // preset from harness(), which leaves the supporting Platform,- // Channels, and Integrations families off.- let harness = DomainSet::harness();- let tui = DomainSet::embedded();-- assert!(!harness.allows(DomainGroup::Platform));- assert!(tui.allows(DomainGroup::Platform));- assert!(!harness.allows(DomainGroup::Channels));- assert!(tui.allows(DomainGroup::Channels));- assert!(!harness.allows(DomainGroup::Integrations));- assert!(tui.allows(DomainGroup::Integrations));+ // none() = every family off.+ let none = DomainSet::none();+ for group in [+ DomainGroup::Agent,+ DomainGroup::Memory,+ DomainGroup::Threads,+ DomainGroup::Config,+ DomainGroup::Security,+ DomainGroup::Flows,+ DomainGroup::Skills,+ DomainGroup::Mcp,+ DomainGroup::Channels,+ DomainGroup::Web3,+ DomainGroup::Voice,+ DomainGroup::Media,+ DomainGroup::Medulla,+ DomainGroup::Platform,+ ] {+ assert!(!none.allows(group), "none() must NOT allow {group:?}");}- #[test]- fn embedded_service_set_binds_no_transport() {- // The whole point of the typed facade: the host talks to the core- // in-process, so no port, no bearer handshake, no loopback listener.- let services = ServiceSet::embedded();-- assert!(!services.rpc_http, "embedded() must not bind HTTP");- assert!(!services.socketio, "embedded() must not mount Socket.IO");-- // But a long-lived operator session still wants background work.- assert!(services.cron);- assert!(services.heartbeat);- assert!(services.memory_queue);- assert!(services.harness_init);- assert!(services.memory_sync);+ // Spot-check the field/group wiring is not transposed.+ assert!(DomainSet::harness().allows(DomainGroup::Memory));+ assert!(!DomainSet::harness().allows(DomainGroup::Web3));+}++#[test]+fn embedded_domain_set_enables_the_host_families() {+ let set = DomainSet::embedded();++ for on in [+ DomainGroup::Agent,+ DomainGroup::Memory,+ DomainGroup::Threads,+ DomainGroup::Config,+ DomainGroup::Security,+ DomainGroup::Medulla,+ DomainGroup::Platform,+ ] {+ assert!(set.allows(on), "embedded() must allow {on:?}");}- #[test]- fn boot_jobs_are_independent_from_runtime_service_flags() {- let mut custom = ServiceSet::none();- custom.rpc_http = true;- custom.heartbeat = true;- custom.update_scheduler = true;- assert!(!custom.memory_queue);- assert!(!custom.harness_init);- assert!(!custom.skill_catalog_refresh);- assert!(!custom.mcp_boot);- assert!(!custom.integrations);- assert!(!custom.memory_sync);-- let desktop = ServiceSet::desktop();- assert!(desktop.memory_queue);- assert!(desktop.harness_init);- assert!(desktop.skill_catalog_refresh);- assert!(desktop.mcp_boot);- assert!(desktop.integrations);- assert!(desktop.memory_sync);-- // headless_api() runs no bootstrap jobs either.- let headless = ServiceSet::headless_api();- assert!(!headless.integrations);- assert!(!headless.memory_sync);+ for off in [+ DomainGroup::Mcp,+ DomainGroup::Web3,+ DomainGroup::Voice,+ DomainGroup::Media,+ ] {+ assert!(!set.allows(off), "embedded() must NOT allow {off:?}");}+}++#[test]+fn embedded_keeps_flows_on_for_workflow_boot_reconcile() {+ // Not incidental: `medulla_workflows` runs on the tinyflows engine and+ // boot reconciliation keys off `ctx.domains().flows`, not a ServiceSet+ // flag. Turning this off silently strands orphaned runs.+ assert!(DomainSet::embedded().allows(DomainGroup::Flows));+}++#[test]+fn embedded_keeps_channels_on_for_web_chat() {+ // `channel.web_chat` is tagged DomainGroup::Channels and the TUI drives+ // chat turns through it. This is precisely why embedded() is not+ // built on harness(), which leaves channels off.+ assert!(DomainSet::embedded().allows(DomainGroup::Channels));+}++#[test]+fn embedded_is_not_harness_plus_medulla() {+ // Guards the most tempting future "simplification": deriving this+ // preset from harness(), which leaves the supporting Platform,+ // Channels, and Integrations families off.+ let harness = DomainSet::harness();+ let tui = DomainSet::embedded();++ assert!(!harness.allows(DomainGroup::Platform));+ assert!(tui.allows(DomainGroup::Platform));+ assert!(!harness.allows(DomainGroup::Channels));+ assert!(tui.allows(DomainGroup::Channels));+ assert!(!harness.allows(DomainGroup::Integrations));+ assert!(tui.allows(DomainGroup::Integrations));+}++#[test]+fn embedded_service_set_binds_no_transport() {+ // The whole point of the typed facade: the host talks to the core+ // in-process, so no port, no bearer handshake, no loopback listener.+ let services = ServiceSet::embedded();++ assert!(!services.rpc_http, "embedded() must not bind HTTP");+ assert!(!services.socketio, "embedded() must not mount Socket.IO");++ // But a long-lived operator session still wants background work.+ assert!(services.cron);+ assert!(services.heartbeat);+ assert!(services.memory_queue);+ assert!(services.harness_init);+ assert!(services.memory_sync);+}++#[test]+fn boot_jobs_are_independent_from_runtime_service_flags() {+ let mut custom = ServiceSet::none();+ custom.rpc_http = true;+ custom.heartbeat = true;+ custom.update_scheduler = true;+ assert!(!custom.memory_queue);+ assert!(!custom.harness_init);+ assert!(!custom.skill_catalog_refresh);+ assert!(!custom.mcp_boot);+ assert!(!custom.integrations);+ assert!(!custom.memory_sync);++ let desktop = ServiceSet::desktop();+ assert!(desktop.memory_queue);+ assert!(desktop.harness_init);+ assert!(desktop.skill_catalog_refresh);+ assert!(desktop.mcp_boot);+ assert!(desktop.integrations);+ assert!(desktop.memory_sync);++ // headless_api() runs no bootstrap jobs either.+ let headless = ServiceSet::headless_api();+ assert!(!headless.integrations);+ assert!(!headless.memory_sync);+}diff --git a/crates/openhuman-core/src/core/runtime/context.rs b/crates/openhuman-core/src/core/runtime/context.rsindex 3abd50475c..2177936e4e 100644--- a/crates/openhuman-core/src/core/runtime/context.rs+++ b/crates/openhuman-core/src/core/runtime/context.rs@@ -790,4 +790,3 @@ pub async fn init_stores(cfg: &crate::config::Config, domains: crate::core::runt#[cfg(test)]#[path = "context_tests.rs"]mod tests;-diff --git a/crates/openhuman-core/src/core/runtime/context_tests.rs b/crates/openhuman-core/src/core/runtime/context_tests.rsindex 4df8ad6817..a5f27fc9db 100644--- a/crates/openhuman-core/src/core/runtime/context_tests.rs+++ b/crates/openhuman-core/src/core/runtime/context_tests.rs@@ -1,441 +1,440 @@- use super::*;- use std::path::PathBuf;-- fn ctx(dir: &str) -> Arc<CoreContext> {- Arc::new(CoreContext {- host_kind: HostKind::Cli,- workspace_binding: RwLock::new(WorkspaceBinding {- workspace_dir: Some(PathBuf::from(dir)),- memory_subsystem: Default::default(),- }),- domains: crate::core::runtime::DomainSet::full(),- tool_groups: Default::default(),- embedder_config: None,- })- }-- // The ambient-scope primitive is the mechanism Phase 3 multi-tenant- // isolation is built on: a dispatch scoped to context A must see A's state,- // not the process default or another tenant's. These assert the primitive- // directly (independent of the process DEFAULT_CONTEXT global, since- // `current()` inside a scope resolves the scoped value).-- // ---- embedder-supplied config (the library-embedding seam) ---------------- //- // `CoreBuilder::config(..)` is only half of the story, and the half that is- // easy to get wrong. Setting the config at boot does NOT reach RPC handlers:- // they call `load_config_with_timeout()` per dispatch, which re-runs- // `Config::load_or_init()` and re-resolves the process-global workspace. The- // context has to carry it, and the loader has to prefer it, or an embedder- // configures boot and watches its turns run somewhere else entirely.-- fn ctx_with_config(config: crate::config::Config) -> Arc<CoreContext> {- Arc::new(CoreContext {- host_kind: HostKind::Cli,- workspace_binding: RwLock::new(WorkspaceBinding {- workspace_dir: Some(config.workspace_dir.clone()),- memory_subsystem: Default::default(),- }),- domains: crate::core::runtime::DomainSet::full(),- tool_groups: Default::default(),- embedder_config: Some(config),- })- }-- #[test]- fn a_context_without_an_embedder_config_reports_none() {- // The default for every host that lets the core discover its own- // config, which is all of them but a library embedder.- assert!(ctx("/tmp/ws").embedder_config().is_none());- }-- #[test]- fn an_embedder_config_is_readable_from_the_context() {- let mut config = crate::config::Config::default();- config.workspace_dir = PathBuf::from("/tmp/embedder-ws");- config.default_model = Some("embedder-model".into());-- let ctx = ctx_with_config(config);- let read = ctx.embedder_config().expect("supplied config is readable");- assert_eq!(read.workspace_dir, PathBuf::from("/tmp/embedder-ws"));- assert_eq!(read.default_model.as_deref(), Some("embedder-model"));- }-- #[tokio::test]- async fn the_current_dispatch_sees_the_scoped_embedder_config() {- // This is the read path `load_config_with_timeout` uses. If it resolved- // to the process default instead of the scoped context, a second- // embedder in the same process would silently serve the first's config.- let mut config = crate::config::Config::default();- config.workspace_dir = PathBuf::from("/tmp/scoped-ws");- config.default_model = Some("scoped-model".into());-- let scoped = CoreContext::scope(ctx_with_config(config), async {- CoreContext::current_embedder_config()- })- .await;-- let scoped = scoped.expect("a scoped embedder config is visible to the dispatch");- assert_eq!(scoped.default_model.as_deref(), Some("scoped-model"));- assert_eq!(scoped.workspace_dir, PathBuf::from("/tmp/scoped-ws"));- }-- // ---- store-init gating (#4796 DoD item 3) --------------------------------- // `init_stores` side-effects on process globals with no init-state probe, so- // the gating is proven via the pure `StoreInitPlan` the registrar consumes.-- #[test]- fn store_init_plan_full_initializes_every_store() {- let plan = StoreInitPlan::for_domains(crate::core::runtime::DomainSet::full());- assert_eq!(- plan,- StoreInitPlan {- memory: true,- agent_attachments: true,- skills_prune: true,- },- "full() must initialize every workspace-bound store"- );- }-- #[test]- fn store_init_plan_none_initializes_nothing() {- let plan = StoreInitPlan::for_domains(crate::core::runtime::DomainSet::none());- assert_eq!(- plan,- StoreInitPlan {- memory: false,- agent_attachments: false,- skills_prune: false,- },- "none() must leave every workspace-bound store uninitialized"- );- }-- #[test]- fn store_init_plan_harness_gates_by_owning_group() {- let plan = StoreInitPlan::for_domains(crate::core::runtime::DomainSet::harness());- // harness() = agent + memory + threads + config + security.- assert!(plan.memory, "harness keeps the memory binding (Memory)");- assert!(- plan.agent_attachments,- "harness keeps agent attachments sidecar (Agent)"- );- // Skills is NOT in harness → its store work stays off.- assert!(- !plan.skills_prune,- "harness must skip skills legacy-prune (Skills)"- );- }-- #[tokio::test]- async fn scope_sets_current_context() {- let a = ctx("/tmp/ctx-a");- let seen = CoreContext::scope(a, async {- CoreContext::current().map(|c| c.workspace_dir().unwrap())+use super::*;+use std::path::PathBuf;++fn ctx(dir: &str) -> Arc<CoreContext> {+ Arc::new(CoreContext {+ host_kind: HostKind::Cli,+ workspace_binding: RwLock::new(WorkspaceBinding {+ workspace_dir: Some(PathBuf::from(dir)),+ memory_subsystem: Default::default(),+ }),+ domains: crate::core::runtime::DomainSet::full(),+ tool_groups: Default::default(),+ embedder_config: None,+ })+}++// The ambient-scope primitive is the mechanism Phase 3 multi-tenant+// isolation is built on: a dispatch scoped to context A must see A's state,+// not the process default or another tenant's. These assert the primitive+// directly (independent of the process DEFAULT_CONTEXT global, since+// `current()` inside a scope resolves the scoped value).++// ---- embedder-supplied config (the library-embedding seam) ---------------+//+// `CoreBuilder::config(..)` is only half of the story, and the half that is+// easy to get wrong. Setting the config at boot does NOT reach RPC handlers:+// they call `load_config_with_timeout()` per dispatch, which re-runs+// `Config::load_or_init()` and re-resolves the process-global workspace. The+// context has to carry it, and the loader has to prefer it, or an embedder+// configures boot and watches its turns run somewhere else entirely.++fn ctx_with_config(config: crate::config::Config) -> Arc<CoreContext> {+ Arc::new(CoreContext {+ host_kind: HostKind::Cli,+ workspace_binding: RwLock::new(WorkspaceBinding {+ workspace_dir: Some(config.workspace_dir.clone()),+ memory_subsystem: Default::default(),+ }),+ domains: crate::core::runtime::DomainSet::full(),+ tool_groups: Default::default(),+ embedder_config: Some(config),+ })+}++#[test]+fn a_context_without_an_embedder_config_reports_none() {+ // The default for every host that lets the core discover its own+ // config, which is all of them but a library embedder.+ assert!(ctx("/tmp/ws").embedder_config().is_none());+}++#[test]+fn an_embedder_config_is_readable_from_the_context() {+ let mut config = crate::config::Config::default();+ config.workspace_dir = PathBuf::from("/tmp/embedder-ws");+ config.default_model = Some("embedder-model".into());++ let ctx = ctx_with_config(config);+ let read = ctx.embedder_config().expect("supplied config is readable");+ assert_eq!(read.workspace_dir, PathBuf::from("/tmp/embedder-ws"));+ assert_eq!(read.default_model.as_deref(), Some("embedder-model"));+}++#[tokio::test]+async fn the_current_dispatch_sees_the_scoped_embedder_config() {+ // This is the read path `load_config_with_timeout` uses. If it resolved+ // to the process default instead of the scoped context, a second+ // embedder in the same process would silently serve the first's config.+ let mut config = crate::config::Config::default();+ config.workspace_dir = PathBuf::from("/tmp/scoped-ws");+ config.default_model = Some("scoped-model".into());++ let scoped = CoreContext::scope(ctx_with_config(config), async {+ CoreContext::current_embedder_config()+ })+ .await;++ let scoped = scoped.expect("a scoped embedder config is visible to the dispatch");+ assert_eq!(scoped.default_model.as_deref(), Some("scoped-model"));+ assert_eq!(scoped.workspace_dir, PathBuf::from("/tmp/scoped-ws"));+}++// ---- store-init gating (#4796 DoD item 3) --------------------------------+// `init_stores` side-effects on process globals with no init-state probe, so+// the gating is proven via the pure `StoreInitPlan` the registrar consumes.++#[test]+fn store_init_plan_full_initializes_every_store() {+ let plan = StoreInitPlan::for_domains(crate::core::runtime::DomainSet::full());+ assert_eq!(+ plan,+ StoreInitPlan {+ memory: true,+ agent_attachments: true,+ skills_prune: true,+ },+ "full() must initialize every workspace-bound store"+ );+}++#[test]+fn store_init_plan_none_initializes_nothing() {+ let plan = StoreInitPlan::for_domains(crate::core::runtime::DomainSet::none());+ assert_eq!(+ plan,+ StoreInitPlan {+ memory: false,+ agent_attachments: false,+ skills_prune: false,+ },+ "none() must leave every workspace-bound store uninitialized"+ );+}++#[test]+fn store_init_plan_harness_gates_by_owning_group() {+ let plan = StoreInitPlan::for_domains(crate::core::runtime::DomainSet::harness());+ // harness() = agent + memory + threads + config + security.+ assert!(plan.memory, "harness keeps the memory binding (Memory)");+ assert!(+ plan.agent_attachments,+ "harness keeps agent attachments sidecar (Agent)"+ );+ // Skills is NOT in harness → its store work stays off.+ assert!(+ !plan.skills_prune,+ "harness must skip skills legacy-prune (Skills)"+ );+}++#[tokio::test]+async fn scope_sets_current_context() {+ let a = ctx("/tmp/ctx-a");+ let seen = CoreContext::scope(a, async {+ CoreContext::current().map(|c| c.workspace_dir().unwrap())+ })+ .await;+ assert_eq!(seen, Some(PathBuf::from("/tmp/ctx-a")));+}++#[tokio::test]+async fn propagate_carries_scoped_context_into_spawned_task() {+ let a = ctx("/tmp/ctx-propagated");+ let seen = CoreContext::scope(a, async {+ tokio::spawn(CoreContext::propagate(async {+ CoreContext::current().unwrap().workspace_dir().unwrap()+ }))+ .await+ .unwrap()+ })+ .await;+ assert_eq!(seen, PathBuf::from("/tmp/ctx-propagated"));+}++#[tokio::test]+async fn scoped_context_exposes_its_domain_set() {+ // The ambient `current().domains()` must reflect the scoped context's+ // DomainSet — this is the seam the registry filter reads (#4796).+ let harness = crate::core::runtime::DomainSet::harness();+ let ctx = CoreContext::for_test(harness, Some(PathBuf::from("/tmp/ctx-domains")), None);+ let seen = CoreContext::scope(ctx, async { CoreContext::current().map(|c| c.domains()) }).await;+ assert_eq!(seen, Some(harness));+ assert!(seen.unwrap().allows(crate::core::all::DomainGroup::Memory));+ assert!(!seen.unwrap().allows(crate::core::all::DomainGroup::Web3));+}++#[tokio::test]+async fn nested_scope_overrides_then_restores() {+ let a = ctx("/tmp/ctx-a");+ let b = ctx("/tmp/ctx-b");+ let (inner, outer) = CoreContext::scope(a, async {+ let inner = CoreContext::scope(b, async {+ CoreContext::current().unwrap().workspace_dir().unwrap()}).await;- assert_eq!(seen, Some(PathBuf::from("/tmp/ctx-a")));- }-- #[tokio::test]- async fn propagate_carries_scoped_context_into_spawned_task() {- let a = ctx("/tmp/ctx-propagated");- let seen = CoreContext::scope(a, async {- tokio::spawn(CoreContext::propagate(async {- CoreContext::current().unwrap().workspace_dir().unwrap()- }))- .await- .unwrap()- })- .await;- assert_eq!(seen, PathBuf::from("/tmp/ctx-propagated"));- }-- #[tokio::test]- async fn scoped_context_exposes_its_domain_set() {- // The ambient `current().domains()` must reflect the scoped context's- // DomainSet — this is the seam the registry filter reads (#4796).- let harness = crate::core::runtime::DomainSet::harness();- let ctx = CoreContext::for_test(harness, Some(PathBuf::from("/tmp/ctx-domains")), None);- let seen =- CoreContext::scope(ctx, async { CoreContext::current().map(|c| c.domains()) }).await;- assert_eq!(seen, Some(harness));- assert!(seen.unwrap().allows(crate::core::all::DomainGroup::Memory));- assert!(!seen.unwrap().allows(crate::core::all::DomainGroup::Web3));- }-- #[tokio::test]- async fn nested_scope_overrides_then_restores() {- let a = ctx("/tmp/ctx-a");- let b = ctx("/tmp/ctx-b");- let (inner, outer) = CoreContext::scope(a, async {- let inner = CoreContext::scope(b, async {- CoreContext::current().unwrap().workspace_dir().unwrap()- })- .await;- let outer = CoreContext::current().unwrap().workspace_dir().unwrap();- (inner, outer)- })- .await;- // Inner dispatch sees tenant B; the outer scope is restored to A after.- assert_eq!(inner, PathBuf::from("/tmp/ctx-b"));- assert_eq!(outer, PathBuf::from("/tmp/ctx-a"));- }-- // The Phase 3 exit criterion, at the store level: two contexts over distinct- // workspaces resolve isolated per-domain stores, and one context always- // The three people-based context tests that stood here are gone with- // `CoreContext::people()`. They proved per-context workspace isolation- // using the people store as the example, and that property is proved- // unchanged by `memory_binding_is_isolated_per_context_workspace` and- // `rebind_workspace_updates_context_memory_binding` below — which is what- // people now resolves through. The third,- // `people_rpc_uses_scoped_context_store`, asserted that a scoped- // `people_resolve` wrote workspace A and not B by reading both stores- // directly; there is no second reader to check against any more, and the- // isolation it tested is the binding's.-- #[test]- fn degraded_context_rejects_workspace_bound_stores() {- let ctx = CoreContext {- host_kind: HostKind::Cli,- workspace_binding: RwLock::new(WorkspaceBinding {- workspace_dir: None,- memory_subsystem: Default::default(),- }),- domains: crate::core::runtime::DomainSet::full(),- tool_groups: Default::default(),- embedder_config: None,- };-- // `workspace_dir()` is the gate every workspace-bound store goes- // through, so it is asserted directly. This used to go through- // `CoreContext::people()`, which was simply the first such store; it- // resolves through the memory binding now and no longer exists.- let err = match ctx.workspace_dir() {- Ok(_) => panic!("degraded context unexpectedly resolved a workspace"),- Err(err) => err,- };- assert!(- err.contains("workspace unavailable"),- "unexpected error: {err}"- );- }-- // ---- memory driver binding (M2b) ------------------------------------------ fn untrusted_external_memory_cfg() -> crate::config::schema::MemorySubsystemConfig {- use crate::config::schema::{MemoryDriverConfig, MemorySubsystemConfig};- let mut cfg = MemorySubsystemConfig {- driver: "supermemory".into(),- ..Default::default()- };- cfg.drivers.insert(- "supermemory".into(),- MemoryDriverConfig {- class: Some("external".into()),- ..Default::default()- },- );- cfg- }-- /// Same proof as `people_store_is_isolated_per_context_workspace`, one layer- /// up: the memory binding is per-workspace, not per-process.- #[test]- fn memory_binding_is_isolated_per_context_workspace() {- let dir_a = tempfile::tempdir().unwrap();- let dir_b = tempfile::tempdir().unwrap();- let a = Arc::new(CoreContext {- host_kind: HostKind::Cli,- workspace_binding: RwLock::new(WorkspaceBinding {- workspace_dir: Some(dir_a.path().to_path_buf()),- memory_subsystem: Default::default(),- }),- domains: crate::core::runtime::DomainSet::full(),- tool_groups: Default::default(),- embedder_config: None,- });- let b = Arc::new(CoreContext {- host_kind: HostKind::Cli,- workspace_binding: RwLock::new(WorkspaceBinding {- workspace_dir: Some(dir_b.path().to_path_buf()),- memory_subsystem: Default::default(),- }),- domains: crate::core::runtime::DomainSet::full(),- tool_groups: Default::default(),- embedder_config: None,- });-- let bind_a = a.memory_binding().expect("bind workspace A");- let bind_b = b.memory_binding().expect("bind workspace B");- assert!(!Arc::ptr_eq(&bind_a, &bind_b));-- let bind_a_again = a.memory_binding().expect("re-resolve workspace A");- assert!(Arc::ptr_eq(&bind_a, &bind_a_again));- }-- /// The per-workspace rebinding requirement, proven without any explicit- /// "rebind memory" call: switching the active user re-points- /// `workspace_dir`, and the accessor keys on that.- #[test]- fn rebind_workspace_updates_context_memory_binding() {- let dir_a = tempfile::tempdir().unwrap();- let dir_b = tempfile::tempdir().unwrap();- let ctx = CoreContext {- host_kind: HostKind::Cli,- workspace_binding: RwLock::new(WorkspaceBinding {- workspace_dir: Some(dir_a.path().to_path_buf()),- memory_subsystem: Default::default(),- }),- domains: crate::core::runtime::DomainSet::full(),- tool_groups: Default::default(),- embedder_config: None,- };-- let bind_a = ctx.memory_binding().expect("bind workspace A");- ctx.rebind_workspace(dir_b.path(), Default::default())- .expect("rebind context workspace");-- assert_eq!(ctx.workspace_dir().unwrap(), dir_b.path());- let bind_b = ctx.memory_binding().expect("bind workspace B");- assert!(!Arc::ptr_eq(&bind_a, &bind_b));- }-- /// The subsystem-config refresh half of the rebind requirement: a rebind- /// that passes a `[subsystems.memory] driver = "null"` config must make the- /// accessor report the null driver, not the default embedded one captured- /// before the user switch.- #[test]- fn rebind_workspace_refreshes_memory_subsystem_config() {- let dir_a = tempfile::tempdir().unwrap();- let ctx = CoreContext {- host_kind: HostKind::Cli,- workspace_binding: RwLock::new(WorkspaceBinding {- workspace_dir: Some(dir_a.path().to_path_buf()),- memory_subsystem: Default::default(),- }),- domains: crate::core::runtime::DomainSet::full(),- tool_groups: Default::default(),- embedder_config: None,- };-- let bind_a = ctx.memory_binding().expect("bind workspace A");- let expected = if cfg!(feature = "modules") {- crate::core::subsystem::DriverClass::Module- } else {- crate::core::subsystem::DriverClass::Null- };- assert_eq!(bind_a.class(), expected);-- let null_cfg = crate::config::schema::MemorySubsystemConfig {- driver: "null".to_string(),+ let outer = CoreContext::current().unwrap().workspace_dir().unwrap();+ (inner, outer)+ })+ .await;+ // Inner dispatch sees tenant B; the outer scope is restored to A after.+ assert_eq!(inner, PathBuf::from("/tmp/ctx-b"));+ assert_eq!(outer, PathBuf::from("/tmp/ctx-a"));+}++// The Phase 3 exit criterion, at the store level: two contexts over distinct+// workspaces resolve isolated per-domain stores, and one context always+// The three people-based context tests that stood here are gone with+// `CoreContext::people()`. They proved per-context workspace isolation+// using the people store as the example, and that property is proved+// unchanged by `memory_binding_is_isolated_per_context_workspace` and+// `rebind_workspace_updates_context_memory_binding` below — which is what+// people now resolves through. The third,+// `people_rpc_uses_scoped_context_store`, asserted that a scoped+// `people_resolve` wrote workspace A and not B by reading both stores+// directly; there is no second reader to check against any more, and the+// isolation it tested is the binding's.++#[test]+fn degraded_context_rejects_workspace_bound_stores() {+ let ctx = CoreContext {+ host_kind: HostKind::Cli,+ workspace_binding: RwLock::new(WorkspaceBinding {+ workspace_dir: None,+ memory_subsystem: Default::default(),+ }),+ domains: crate::core::runtime::DomainSet::full(),+ tool_groups: Default::default(),+ embedder_config: None,+ };++ // `workspace_dir()` is the gate every workspace-bound store goes+ // through, so it is asserted directly. This used to go through+ // `CoreContext::people()`, which was simply the first such store; it+ // resolves through the memory binding now and no longer exists.+ let err = match ctx.workspace_dir() {+ Ok(_) => panic!("degraded context unexpectedly resolved a workspace"),+ Err(err) => err,+ };+ assert!(+ err.contains("workspace unavailable"),+ "unexpected error: {err}"+ );+}++// ---- memory driver binding (M2b) ----------------------------------------++fn untrusted_external_memory_cfg() -> crate::config::schema::MemorySubsystemConfig {+ use crate::config::schema::{MemoryDriverConfig, MemorySubsystemConfig};+ let mut cfg = MemorySubsystemConfig {+ driver: "supermemory".into(),+ ..Default::default()+ };+ cfg.drivers.insert(+ "supermemory".into(),+ MemoryDriverConfig {+ class: Some("external".into()),..Default::default()- };- // This is the dangerous case: changing only the memory config for an- // already-bound workspace must replace the complete snapshot, so the- // binding cache sees the new (workspace, config) pair.- ctx.rebind_workspace(dir_a.path(), null_cfg)- .expect("rebind context subsystem config");-- let bind_b = ctx.memory_binding().expect("bind workspace B");- assert_eq!(bind_b.class(), crate::core::subsystem::DriverClass::Null);- }-- /// `memory::global`'s clear-on-failed-rebind property, preserved- /// structurally: a workspace whose configured driver is refused resolves to- /// the fallback, never to another workspace's driver.- #[test]- fn failed_bind_never_returns_previous_workspace_binding() {- let dir_a = tempfile::tempdir().unwrap();- let dir_b = tempfile::tempdir().unwrap();- let a = CoreContext {- host_kind: HostKind::Cli,- workspace_binding: RwLock::new(WorkspaceBinding {- workspace_dir: Some(dir_a.path().to_path_buf()),- memory_subsystem: Default::default(),- }),- domains: crate::core::runtime::DomainSet::full(),- tool_groups: Default::default(),- embedder_config: None,- };- let b = CoreContext {- host_kind: HostKind::Cli,- workspace_binding: RwLock::new(WorkspaceBinding {- workspace_dir: Some(dir_b.path().to_path_buf()),- memory_subsystem: untrusted_external_memory_cfg(),- }),- domains: crate::core::runtime::DomainSet::full(),- tool_groups: Default::default(),- embedder_config: None,- };-- let bind_a = a.memory_binding().expect("bind workspace A");- assert_eq!(bind_a.driver_id(), "tinymemory");- assert!(bind_a.fallback().is_none());-- let bind_b = b.memory_binding().expect("workspace B falls back");- assert_eq!(- bind_b.driver_id(),- "null",- "a refused driver must fall back, not inherit another workspace's"- );- let fallback = bind_b.fallback().expect("fallback provenance recorded");- assert_eq!(fallback.configured_driver, "supermemory");- assert!(!Arc::ptr_eq(&bind_a, &bind_b));- }-- /// The single most important default in this step: no binding ⇒ the FULL- /// capability set, mirroring `core::all::group_allowed` with no context.- #[test]- fn memory_capabilities_defaults_open_without_a_workspace() {- let ctx = CoreContext {- host_kind: HostKind::Cli,- workspace_binding: RwLock::new(WorkspaceBinding {- workspace_dir: None,- memory_subsystem: Default::default(),- }),- domains: crate::core::runtime::DomainSet::full(),- tool_groups: Default::default(),- embedder_config: None,- };- assert!(ctx.memory_binding().is_err(), "no workspace ⇒ no binding");- assert_eq!(- ctx.memory_capabilities(),- tinymemory_api::capabilities::Capabilities::all(),- "a context with no binding must not deny any capability"- );- }-- /// The no-context arm of `current_memory_capabilities`. Asserted through- /// the value the fallback branch yields rather than by calling it with an- /// empty `DEFAULT_CONTEXT`: that global is process-wide and another test in- /// the same binary may have set it, which would make a bare- /// `assert_eq!(current_memory_capabilities(), all())` order-dependently- /// flaky.- #[test]- fn current_memory_capabilities_defaults_open_without_a_context() {- assert_eq!(- crate::memory::binding::unbound_default_capabilities(),- tinymemory_api::capabilities::Capabilities::all()- );- // And when a context *is* ambient, the call resolves through it rather- // than erroring.- let ctx = CoreContext::for_test(crate::core::runtime::DomainSet::full(), None, None);- assert_eq!(- ctx.memory_capabilities(),- tinymemory_api::capabilities::Capabilities::all()- );- }-- /// The DomainSet axis and the capability axis are independent (kernel.md- /// §3.7's three axes): a narrowed `DomainSet` must not narrow capabilities.- #[test]- fn capabilities_are_open_under_a_harness_domain_set() {- let ctx = CoreContext::for_test(crate::core::runtime::DomainSet::harness(), None, None);- assert_eq!(- ctx.memory_capabilities(),- tinymemory_api::capabilities::Capabilities::all()- );- }+ },+ );+ cfg+}++/// Same proof as `people_store_is_isolated_per_context_workspace`, one layer+/// up: the memory binding is per-workspace, not per-process.+#[test]+fn memory_binding_is_isolated_per_context_workspace() {+ let dir_a = tempfile::tempdir().unwrap();+ let dir_b = tempfile::tempdir().unwrap();+ let a = Arc::new(CoreContext {+ host_kind: HostKind::Cli,+ workspace_binding: RwLock::new(WorkspaceBinding {+ workspace_dir: Some(dir_a.path().to_path_buf()),+ memory_subsystem: Default::default(),+ }),+ domains: crate::core::runtime::DomainSet::full(),+ tool_groups: Default::default(),+ embedder_config: None,+ });+ let b = Arc::new(CoreContext {+ host_kind: HostKind::Cli,+ workspace_binding: RwLock::new(WorkspaceBinding {+ workspace_dir: Some(dir_b.path().to_path_buf()),+ memory_subsystem: Default::default(),+ }),+ domains: crate::core::runtime::DomainSet::full(),+ tool_groups: Default::default(),+ embedder_config: None,+ });++ let bind_a = a.memory_binding().expect("bind workspace A");+ let bind_b = b.memory_binding().expect("bind workspace B");+ assert!(!Arc::ptr_eq(&bind_a, &bind_b));++ let bind_a_again = a.memory_binding().expect("re-resolve workspace A");+ assert!(Arc::ptr_eq(&bind_a, &bind_a_again));+}++/// The per-workspace rebinding requirement, proven without any explicit+/// "rebind memory" call: switching the active user re-points+/// `workspace_dir`, and the accessor keys on that.+#[test]+fn rebind_workspace_updates_context_memory_binding() {+ let dir_a = tempfile::tempdir().unwrap();+ let dir_b = tempfile::tempdir().unwrap();+ let ctx = CoreContext {+ host_kind: HostKind::Cli,+ workspace_binding: RwLock::new(WorkspaceBinding {+ workspace_dir: Some(dir_a.path().to_path_buf()),+ memory_subsystem: Default::default(),+ }),+ domains: crate::core::runtime::DomainSet::full(),+ tool_groups: Default::default(),+ embedder_config: None,+ };++ let bind_a = ctx.memory_binding().expect("bind workspace A");+ ctx.rebind_workspace(dir_b.path(), Default::default())+ .expect("rebind context workspace");++ assert_eq!(ctx.workspace_dir().unwrap(), dir_b.path());+ let bind_b = ctx.memory_binding().expect("bind workspace B");+ assert!(!Arc::ptr_eq(&bind_a, &bind_b));+}++/// The subsystem-config refresh half of the rebind requirement: a rebind+/// that passes a `[subsystems.memory] driver = "null"` config must make the+/// accessor report the null driver, not the default embedded one captured+/// before the user switch.+#[test]+fn rebind_workspace_refreshes_memory_subsystem_config() {+ let dir_a = tempfile::tempdir().unwrap();+ let ctx = CoreContext {+ host_kind: HostKind::Cli,+ workspace_binding: RwLock::new(WorkspaceBinding {+ workspace_dir: Some(dir_a.path().to_path_buf()),+ memory_subsystem: Default::default(),+ }),+ domains: crate::core::runtime::DomainSet::full(),+ tool_groups: Default::default(),+ embedder_config: None,+ };++ let bind_a = ctx.memory_binding().expect("bind workspace A");+ let expected = if cfg!(feature = "modules") {+ crate::core::subsystem::DriverClass::Module+ } else {+ crate::core::subsystem::DriverClass::Null+ };+ assert_eq!(bind_a.class(), expected);++ let null_cfg = crate::config::schema::MemorySubsystemConfig {+ driver: "null".to_string(),+ ..Default::default()+ };+ // This is the dangerous case: changing only the memory config for an+ // already-bound workspace must replace the complete snapshot, so the+ // binding cache sees the new (workspace, config) pair.+ ctx.rebind_workspace(dir_a.path(), null_cfg)+ .expect("rebind context subsystem config");++ let bind_b = ctx.memory_binding().expect("bind workspace B");+ assert_eq!(bind_b.class(), crate::core::subsystem::DriverClass::Null);+}++/// `memory::global`'s clear-on-failed-rebind property, preserved+/// structurally: a workspace whose configured driver is refused resolves to+/// the fallback, never to another workspace's driver.+#[test]+fn failed_bind_never_returns_previous_workspace_binding() {+ let dir_a = tempfile::tempdir().unwrap();+ let dir_b = tempfile::tempdir().unwrap();+ let a = CoreContext {+ host_kind: HostKind::Cli,+ workspace_binding: RwLock::new(WorkspaceBinding {+ workspace_dir: Some(dir_a.path().to_path_buf()),+ memory_subsystem: Default::default(),+ }),+ domains: crate::core::runtime::DomainSet::full(),+ tool_groups: Default::default(),+ embedder_config: None,+ };+ let b = CoreContext {+ host_kind: HostKind::Cli,+ workspace_binding: RwLock::new(WorkspaceBinding {+ workspace_dir: Some(dir_b.path().to_path_buf()),+ memory_subsystem: untrusted_external_memory_cfg(),+ }),+ domains: crate::core::runtime::DomainSet::full(),+ tool_groups: Default::default(),+ embedder_config: None,+ };++ let bind_a = a.memory_binding().expect("bind workspace A");+ assert_eq!(bind_a.driver_id(), "tinymemory");+ assert!(bind_a.fallback().is_none());++ let bind_b = b.memory_binding().expect("workspace B falls back");+ assert_eq!(+ bind_b.driver_id(),+ "null",+ "a refused driver must fall back, not inherit another workspace's"+ );+ let fallback = bind_b.fallback().expect("fallback provenance recorded");+ assert_eq!(fallback.configured_driver, "supermemory");+ assert!(!Arc::ptr_eq(&bind_a, &bind_b));+}++/// The single most important default in this step: no binding ⇒ the FULL+/// capability set, mirroring `core::all::group_allowed` with no context.+#[test]+fn memory_capabilities_defaults_open_without_a_workspace() {+ let ctx = CoreContext {+ host_kind: HostKind::Cli,+ workspace_binding: RwLock::new(WorkspaceBinding {+ workspace_dir: None,+ memory_subsystem: Default::default(),+ }),+ domains: crate::core::runtime::DomainSet::full(),+ tool_groups: Default::default(),+ embedder_config: None,+ };+ assert!(ctx.memory_binding().is_err(), "no workspace ⇒ no binding");+ assert_eq!(+ ctx.memory_capabilities(),+ tinymemory_api::capabilities::Capabilities::all(),+ "a context with no binding must not deny any capability"+ );+}++/// The no-context arm of `current_memory_capabilities`. Asserted through+/// the value the fallback branch yields rather than by calling it with an+/// empty `DEFAULT_CONTEXT`: that global is process-wide and another test in+/// the same binary may have set it, which would make a bare+/// `assert_eq!(current_memory_capabilities(), all())` order-dependently+/// flaky.+#[test]+fn current_memory_capabilities_defaults_open_without_a_context() {+ assert_eq!(+ crate::memory::binding::unbound_default_capabilities(),+ tinymemory_api::capabilities::Capabilities::all()+ );+ // And when a context *is* ambient, the call resolves through it rather+ // than erroring.+ let ctx = CoreContext::for_test(crate::core::runtime::DomainSet::full(), None, None);+ assert_eq!(+ ctx.memory_capabilities(),+ tinymemory_api::capabilities::Capabilities::all()+ );+}++/// The DomainSet axis and the capability axis are independent (kernel.md+/// §3.7's three axes): a narrowed `DomainSet` must not narrow capabilities.+#[test]+fn capabilities_are_open_under_a_harness_domain_set() {+ let ctx = CoreContext::for_test(crate::core::runtime::DomainSet::harness(), None, None);+ assert_eq!(+ ctx.memory_capabilities(),+ tinymemory_api::capabilities::Capabilities::all()+ );+}diff --git a/crates/openhuman-core/src/core/runtime/services.rs b/crates/openhuman-core/src/core/runtime/services.rsindex 0a465d3f65..082bbcdb62 100644--- a/crates/openhuman-core/src/core/runtime/services.rs+++ b/crates/openhuman-core/src/core/runtime/services.rs@@ -562,4 +562,3 @@ pub fn spawn_socket_auto_connect(#[cfg(test)]#[path = "services_tests.rs"]mod tests;-diff --git a/crates/openhuman-core/src/core/runtime/services_tests.rs b/crates/openhuman-core/src/core/runtime/services_tests.rsindex 051b76136d..08aba93a26 100644--- a/crates/openhuman-core/src/core/runtime/services_tests.rs+++ b/crates/openhuman-core/src/core/runtime/services_tests.rs@@ -1,119 +1,119 @@- use super::*;+use super::*;- #[tokio::test]- async fn legacy_migrations_run_for_each_workspace() {- let tmp = tempfile::tempdir().unwrap();- let mut first = Config::default();- first.workspace_dir = tmp.path().join("first");- let mut second = Config::default();- second.workspace_dir = tmp.path().join("second");+#[tokio::test]+async fn legacy_migrations_run_for_each_workspace() {+ let tmp = tempfile::tempdir().unwrap();+ let mut first = Config::default();+ first.workspace_dir = tmp.path().join("first");+ let mut second = Config::default();+ second.workspace_dir = tmp.path().join("second");- for config in [first, second] {- run_legacy_migrations(&config).await;- }+ for config in [first, second] {+ run_legacy_migrations(&config).await;}+}- /// desktop() must enable every bootstrap job — proves the un-bundling kept- /// the desktop job set byte-identical.- #[test]- fn desktop_plan_enables_every_job() {- let plan = bootstrap_job_plan(&ServiceSet::desktop());- assert_eq!(- plan,- BootstrapJobPlan {- memory_queue: true,- composio_integration_sync: true,- workspace_memory_sync: true,- proactive_task_pollers: true,- module_preload: true,- }- );- }+/// desktop() must enable every bootstrap job — proves the un-bundling kept+/// the desktop job set byte-identical.+#[test]+fn desktop_plan_enables_every_job() {+ let plan = bootstrap_job_plan(&ServiceSet::desktop());+ assert_eq!(+ plan,+ BootstrapJobPlan {+ memory_queue: true,+ composio_integration_sync: true,+ workspace_memory_sync: true,+ proactive_task_pollers: true,+ module_preload: true,+ }+ );+}- /// none() / headless_api() run no bootstrap job at all.- #[test]- fn job_free_presets_enable_nothing() {- let empty = BootstrapJobPlan {- memory_queue: false,- composio_integration_sync: false,- workspace_memory_sync: false,- proactive_task_pollers: false,- module_preload: false,- };- assert_eq!(bootstrap_job_plan(&ServiceSet::none()), empty);- assert_eq!(bootstrap_job_plan(&ServiceSet::headless_api()), empty);- }+/// none() / headless_api() run no bootstrap job at all.+#[test]+fn job_free_presets_enable_nothing() {+ let empty = BootstrapJobPlan {+ memory_queue: false,+ composio_integration_sync: false,+ workspace_memory_sync: false,+ proactive_task_pollers: false,+ module_preload: false,+ };+ assert_eq!(bootstrap_job_plan(&ServiceSet::none()), empty);+ assert_eq!(bootstrap_job_plan(&ServiceSet::headless_api()), empty);+}- /// From none(), flipping exactly one concern flag enables exactly its job- /// and nothing else.- #[test]- fn each_concern_flag_enables_exactly_its_job() {- let mut integrations = ServiceSet::none();- integrations.integrations = true;- let plan = bootstrap_job_plan(&integrations);- assert!(plan.composio_integration_sync);- assert!(!plan.workspace_memory_sync);- assert!(!plan.memory_queue);- assert!(!plan.proactive_task_pollers);+/// From none(), flipping exactly one concern flag enables exactly its job+/// and nothing else.+#[test]+fn each_concern_flag_enables_exactly_its_job() {+ let mut integrations = ServiceSet::none();+ integrations.integrations = true;+ let plan = bootstrap_job_plan(&integrations);+ assert!(plan.composio_integration_sync);+ assert!(!plan.workspace_memory_sync);+ assert!(!plan.memory_queue);+ assert!(!plan.proactive_task_pollers);- let mut memory_sync = ServiceSet::none();- memory_sync.memory_sync = true;- let plan = bootstrap_job_plan(&memory_sync);- assert!(plan.workspace_memory_sync);- assert!(!plan.composio_integration_sync);- assert!(!plan.module_preload);+ let mut memory_sync = ServiceSet::none();+ memory_sync.memory_sync = true;+ let plan = bootstrap_job_plan(&memory_sync);+ assert!(plan.workspace_memory_sync);+ assert!(!plan.composio_integration_sync);+ assert!(!plan.module_preload);- // The module preload is memory background work: it follows the queue- // flag and no other.- let mut memory_queue = ServiceSet::none();- memory_queue.memory_queue = true;- let plan = bootstrap_job_plan(&memory_queue);- assert!(plan.module_preload);- assert!(plan.memory_queue);- assert!(!plan.workspace_memory_sync);- assert!(!plan.composio_integration_sync);- assert!(!plan.proactive_task_pollers);- }+ // The module preload is memory background work: it follows the queue+ // flag and no other.+ let mut memory_queue = ServiceSet::none();+ memory_queue.memory_queue = true;+ let plan = bootstrap_job_plan(&memory_queue);+ assert!(plan.module_preload);+ assert!(plan.memory_queue);+ assert!(!plan.workspace_memory_sync);+ assert!(!plan.composio_integration_sync);+ assert!(!plan.proactive_task_pollers);+}- /// From desktop(), disabling exactly one concern flag disables only its job.- #[test]- fn disabling_one_concern_disables_only_its_job() {- let mut services = ServiceSet::desktop();- services.integrations = false;- let plan = bootstrap_job_plan(&services);- assert!(!plan.composio_integration_sync);- assert!(plan.workspace_memory_sync);- assert!(plan.memory_queue);- assert!(plan.proactive_task_pollers);+/// From desktop(), disabling exactly one concern flag disables only its job.+#[test]+fn disabling_one_concern_disables_only_its_job() {+ let mut services = ServiceSet::desktop();+ services.integrations = false;+ let plan = bootstrap_job_plan(&services);+ assert!(!plan.composio_integration_sync);+ assert!(plan.workspace_memory_sync);+ assert!(plan.memory_queue);+ assert!(plan.proactive_task_pollers);- let mut services = ServiceSet::desktop();- services.memory_sync = false;- let plan = bootstrap_job_plan(&services);- assert!(!plan.workspace_memory_sync);- assert!(plan.composio_integration_sync);- }+ let mut services = ServiceSet::desktop();+ services.memory_sync = false;+ let plan = bootstrap_job_plan(&services);+ assert!(!plan.workspace_memory_sync);+ assert!(plan.composio_integration_sync);+}- /// The #5028 regression: `channels` gates NO bootstrap job. Turning channels- /// on by itself must enable zero sync jobs, and turning channels off while- /// the new flags stay on must lose nothing.- #[test]- fn channels_flag_gates_no_bootstrap_job() {- // channels=true alone → zero sync jobs.- let mut channels_only = ServiceSet::none();- channels_only.channels = true;- let plan = bootstrap_job_plan(&channels_only);- assert_eq!(- plan,- bootstrap_job_plan(&ServiceSet::none()),- "channels alone must enable no bootstrap job"- );+/// The #5028 regression: `channels` gates NO bootstrap job. Turning channels+/// on by itself must enable zero sync jobs, and turning channels off while+/// the new flags stay on must lose nothing.+#[test]+fn channels_flag_gates_no_bootstrap_job() {+ // channels=true alone → zero sync jobs.+ let mut channels_only = ServiceSet::none();+ channels_only.channels = true;+ let plan = bootstrap_job_plan(&channels_only);+ assert_eq!(+ plan,+ bootstrap_job_plan(&ServiceSet::none()),+ "channels alone must enable no bootstrap job"+ );- // channels=false with every new flag on → identical to desktop's plan.- let mut channels_off = ServiceSet::desktop();- channels_off.channels = false;- assert_eq!(- bootstrap_job_plan(&channels_off),- bootstrap_job_plan(&ServiceSet::desktop()),- "dropping channels must not drop any bootstrap job"- );- }+ // channels=false with every new flag on → identical to desktop's plan.+ let mut channels_off = ServiceSet::desktop();+ channels_off.channels = false;+ assert_eq!(+ bootstrap_job_plan(&channels_off),+ bootstrap_job_plan(&ServiceSet::desktop()),+ "dropping channels must not drop any bootstrap job"+ );+}diff --git a/crates/openhuman-core/src/core/sentry_transport.rs b/crates/openhuman-core/src/core/sentry_transport.rsindex 5952a0dbe7..030d02653f 100644--- a/crates/openhuman-core/src/core/sentry_transport.rs+++ b/crates/openhuman-core/src/core/sentry_transport.rs@@ -162,4 +162,3 @@ pub fn factory(options: &ClientOptions) -> Arc<dyn Transport> {#[cfg(test)]#[path = "sentry_transport_tests.rs"]mod tests;-diff --git a/crates/openhuman-core/src/core/sentry_transport_tests.rs b/crates/openhuman-core/src/core/sentry_transport_tests.rsindex 0c77871ef8..21a4fffd8c 100644--- a/crates/openhuman-core/src/core/sentry_transport_tests.rs+++ b/crates/openhuman-core/src/core/sentry_transport_tests.rs@@ -1,69 +1,69 @@- use super::*;- use std::io::{Read, Write};- use std::net::TcpListener;+use super::*;+use std::io::{Read, Write};+use std::net::TcpListener;- fn event_envelope(message: &str) -> Envelope {- let mut envelope = Envelope::new();- envelope.add_item(sentry::protocol::Event {- message: Some(message.to_owned()),- ..Default::default()- });- envelope- }+fn event_envelope(message: &str) -> Envelope {+ let mut envelope = Envelope::new();+ envelope.add_item(sentry::protocol::Event {+ message: Some(message.to_owned()),+ ..Default::default()+ });+ envelope+}- #[test]- fn sends_authenticated_envelope_and_applies_category_rate_limit() {- let listener = TcpListener::bind("127.0.0.1:0").unwrap();- let address = listener.local_addr().unwrap();- let request = std::thread::spawn(move || {- let (mut stream, _) = listener.accept().unwrap();- stream- .set_read_timeout(Some(Duration::from_secs(2)))- .unwrap();- let mut bytes = Vec::new();- let mut buffer = [0; 4096];- loop {- let read = stream.read(&mut buffer).unwrap();- bytes.extend_from_slice(&buffer[..read]);- if read < buffer.len() {- break;- }+#[test]+fn sends_authenticated_envelope_and_applies_category_rate_limit() {+ let listener = TcpListener::bind("127.0.0.1:0").unwrap();+ let address = listener.local_addr().unwrap();+ let request = std::thread::spawn(move || {+ let (mut stream, _) = listener.accept().unwrap();+ stream+ .set_read_timeout(Some(Duration::from_secs(2)))+ .unwrap();+ let mut bytes = Vec::new();+ let mut buffer = [0; 4096];+ loop {+ let read = stream.read(&mut buffer).unwrap();+ bytes.extend_from_slice(&buffer[..read]);+ if read < buffer.len() {+ break;}- stream+ }+ stream.write_all(b"HTTP/1.1 200 OK\r\nX-Sentry-Rate-Limits: 60:error:project\r\nContent-Length: 0\r\n\r\n",).unwrap();- String::from_utf8(bytes).unwrap()- });- let options = ClientOptions {- dsn: Some(format!("http://public@{address}/1").parse().unwrap()),- ..Default::default()- };- let transport = SharedReqwestTransport::new(&options);- transport.send_envelope(event_envelope("first"));- assert!(transport.flush(Duration::from_secs(3)));- transport.send_envelope(event_envelope("rate-limited"));- assert!(transport.flush(Duration::from_secs(3)));+ String::from_utf8(bytes).unwrap()+ });+ let options = ClientOptions {+ dsn: Some(format!("http://public@{address}/1").parse().unwrap()),+ ..Default::default()+ };+ let transport = SharedReqwestTransport::new(&options);+ transport.send_envelope(event_envelope("first"));+ assert!(transport.flush(Duration::from_secs(3)));+ transport.send_envelope(event_envelope("rate-limited"));+ assert!(transport.flush(Duration::from_secs(3)));- let request = request.join().unwrap();- assert!(request.contains("POST /api/1/envelope/ HTTP/1.1"));- assert!(request.contains("x-sentry-auth: Sentry"));- assert!(request.contains("\"message\":\"first\""));- assert!(!request.contains("rate-limited"));- }+ let request = request.join().unwrap();+ assert!(request.contains("POST /api/1/envelope/ HTTP/1.1"));+ assert!(request.contains("x-sentry-auth: Sentry"));+ assert!(request.contains("\"message\":\"first\""));+ assert!(!request.contains("rate-limited"));+}- #[test]- fn send_failure_does_not_prevent_flush() {- let listener = TcpListener::bind("127.0.0.1:0").unwrap();- let address = listener.local_addr().unwrap();- drop(listener);- let options = ClientOptions {- dsn: Some(format!("http://public@{address}/1").parse().unwrap()),- ..Default::default()- };- let transport = SharedReqwestTransport::new(&options);- transport.send_envelope(event_envelope("unreachable"));- assert!(transport.flush(Duration::from_secs(3)));- assert!(transport.shutdown(Duration::from_secs(3)));- }+#[test]+fn send_failure_does_not_prevent_flush() {+ let listener = TcpListener::bind("127.0.0.1:0").unwrap();+ let address = listener.local_addr().unwrap();+ drop(listener);+ let options = ClientOptions {+ dsn: Some(format!("http://public@{address}/1").parse().unwrap()),+ ..Default::default()+ };+ let transport = SharedReqwestTransport::new(&options);+ transport.send_envelope(event_envelope("unreachable"));+ assert!(transport.flush(Duration::from_secs(3)));+ assert!(transport.shutdown(Duration::from_secs(3)));+}diff --git a/crates/openhuman-core/src/platform/socket/ws_loop/connect.rs b/crates/openhuman-core/src/platform/socket/ws_loop/connect.rsindex 7fbaa583d7..b544a21d9c 100644--- a/crates/openhuman-core/src/platform/socket/ws_loop/connect.rs+++ b/crates/openhuman-core/src/platform/socket/ws_loop/connect.rs@@ -19,8 +19,8 @@ use crate::api::models::socket::ConnectionStatus;use crate::util::utf8_safe_prefix_at_byte_boundary;use super::dispatch::handle_eio_message;-use super::manager::{emit_state_change, SharedState};-use super::types::{ConnectionOutcome, WsStream};+use crate::platform::socket::manager::{emit_state_change, SharedState};+use crate::platform::socket::types::{ConnectionOutcome, WsStream};/// Maximum HTTP redirect hops to follow during a single WebSocket connect attempt.///diff --git a/crates/openhuman-core/src/platform/socket/ws_loop/dispatch.rs b/crates/openhuman-core/src/platform/socket/ws_loop/dispatch.rsindex b668a407d9..126ecfb8b9 100644--- a/crates/openhuman-core/src/platform/socket/ws_loop/dispatch.rs+++ b/crates/openhuman-core/src/platform/socket/ws_loop/dispatch.rs@@ -7,8 +7,8 @@ use tokio::sync::mpsc;use crate::util::utf8_safe_prefix_at_byte_boundary;-use super::event_handlers::{handle_sio_event, parse_sio_event};-use super::manager::SharedState;+use crate::platform::socket::event_handlers::{handle_sio_event, parse_sio_event};+use crate::platform::socket::manager::SharedState;/// Handle an incoming Engine.IO text message by its type prefix.pub(super) fn handle_eio_message(diff --git a/crates/openhuman-core/src/platform/socket/ws_loop/reconnect.rs b/crates/openhuman-core/src/platform/socket/ws_loop/reconnect.rsindex b432f12f4c..0c39135c96 100644--- a/crates/openhuman-core/src/platform/socket/ws_loop/reconnect.rs+++ b/crates/openhuman-core/src/platform/socket/ws_loop/reconnect.rs@@ -11,9 +11,9 @@ use tokio::time::Duration;use crate::api::models::socket::ConnectionStatus;use super::connect::run_connection;-use super::manager::{emit_state_change, SharedState};-use super::token_provider::{is_invalid_token_error, TokenProvider};-use super::types::ConnectionOutcome;+use crate::platform::socket::manager::{emit_state_change, SharedState};+use crate::platform::socket::token_provider::{is_invalid_token_error, TokenProvider};+use crate::platform::socket::types::ConnectionOutcome;/// Number of consecutive `ConnectionOutcome::Failed` attempts at which the/// loop fires exactly one `error`-level log (and therefore one Sentry event).diff --git a/crates/openhuman-core/src/security/credentials/ops/session_lifecycle.rs b/crates/openhuman-core/src/security/credentials/ops/session_lifecycle.rsdeleted file mode 100644index 3f2369c7dd..0000000000--- a/crates/openhuman-core/src/security/credentials/ops/session_lifecycle.rs+++ /dev/null@@ -1,896 +0,0 @@-//! Login-gated background services, session store/clear, and session state-//! lookups.--use serde_json::{json, Value};-use std::time::Duration;--use crate::api::config::effective_backend_api_url;-use crate::api::jwt::{decode_jwt_exp, get_session_token};-use crate::api::rest::{user_id_from_profile_payload, BackendOAuthClient};-use crate::config::Config;-use crate::rpc::RpcOutcome;-use crate::security::credentials::session_support::{- build_session_state, is_local_session_token, local_session_user_id, summarize_auth_profile,- LOCAL_SESSION_USER_ID,-};-use crate::security::keyring::SecretStore;--use crate::config::{- default_root_openhuman_dir, pre_login_user_dir, read_active_user_id, user_openhuman_dir,- write_active_user_id,-};-use crate::memory::conversations;-use crate::security::credentials::{AuthService, APP_SESSION_PROVIDER, DEFAULT_AUTH_PROFILE_NAME};--const AUTH_ME_STORE_RETRY_DELAY: Duration = Duration::from_millis(150);-const AUTH_ME_STORE_TRANSIENT_STATUSES: &[u16] = &[408, 429, 500, 502, 503, 504, 520];--/// Wall-clock budget for the store-time `GET /auth/me` validation (issue #5166).-///-/// The shared backend client allows a 120s request timeout + 15s connect timeout-/// (`api::rest`), but the desktop sign-in RPC that drives `auth_store_session`-/// gives up far sooner — `AUTH_STORE_TIMEOUT_MS` (25s) × `AUTH_STORE_RETRIES` in-/// `desktopDeepLinkListener.ts`. If the backend is reachable but slow, that 120s-/// ceiling lets `/auth/me` hang past the frontend's patience: the RPC times out-/// and bounces a genuinely-authenticated user back to sign-in *before* the-/// deferred-validation fallback in `store_session_inner` ever gets a chance to-/// fire (the exact `auth_me_timeout` bounce in Sentry `TAURI-REACT-1V`).-///-/// Capping store-time validation well under the frontend budget makes a slow-/// backend fail *fast* into the caller-authorized pending-session path (for a-/// live-`exp` JWT), so the user lands in the app with deferred revalidation-/// instead of being bounced. Overridable via `OPENHUMAN_AUTH_ME_STORE_TIMEOUT_MS`-/// for ops tuning and tests.-pub(crate) const AUTH_ME_STORE_VALIDATION_BUDGET: Duration = Duration::from_secs(12);-pub(crate) const AUTH_ME_STORE_VALIDATION_BUDGET_ENV: &str = "OPENHUMAN_AUTH_ME_STORE_TIMEOUT_MS";--/// Whether this dispatch is running under an embedder-hosted core (the library-/// `Harness`) rather than the desktop shell or CLI.-///-/// An embedder supplies its own scoped [`Config`] via `CoreBuilder::config`,-/// so its `auth_store_session` must keep activation and credential state under-/// that config's path and never touch the operator's global-/// `~/.openhuman/active_user.toml` / `users/` tree.-fn is_embedder_host() -> bool {- crate::core::runtime::context::CoreContext::current_embedder_config().is_some()-}--/// Start all login-gated background services (local AI and voice). Called both-/// from the initial boot path (when an existing-/// session is detected) and from `store_session()` on fresh login.-pub async fn start_login_gated_services(config: &Config) {- // These login-gated services are mutually independent — the ONLY ordering- // constraint is voice-server → standalone-dictation-listener (they contend- // for the single rdev global listener on macOS). Previously each was- // `.await`ed in series, so their cold-start costs SUMMED: the local-AI- // bootstrap (Ollama/embeddings) + the Windows WASAPI microphone init- // (a synchronous readiness handshake in `always_on::spawn_capture_thread`)- // stacked into the ~10s stall users hit before hotkeys/commands were usable- // — worst on Windows (#3490). Worse,- // the hotkey/command registration (steps 2–3) sat- // *after* the local-AI bootstrap in the series, so commands could not- // register until Ollama finished warming.- //- // Run them concurrently on independent tasks instead: readiness is bounded- // by the slowest single service rather than their sum, and command- // registration no longer waits behind local-AI warm-up. Each task logs its- // own elapsed time so a future regression can be attributed to one stage; a- // panic in one service is logged on join and never aborts the others.-- // Unit tests must not launch the real login-gated background services: they- // include detached, long-lived continuous audio capture that outlives the- // test that spawned it and interleaves with the- // shared process state (HOME / active_user.toml) of the parallel `cargo- // test` run. Once startup became concurrent (#3490) that interleaving made- // the session-isolation tests order-dependent. `cfg!(test)` is compiled out- // of every production/release build, so this gate never affects shipped- // behavior; the one test that verifies this function's concurrency opts back- // in via `OPENHUMAN_RUN_LOGIN_GATED_SERVICES_IN_TEST`.- if cfg!(test) && std::env::var_os("OPENHUMAN_RUN_LOGIN_GATED_SERVICES_IN_TEST").is_none() {- log::debug!("[services] login-gated services skipped under unit test");- return;- }-- let started = std::time::Instant::now();- // (service label, task) pairs so a panic surfaced on join is attributed to- // the specific stage rather than an anonymous "a service failed".- let mut tasks: Vec<(&'static str, tokio::task::JoinHandle<()>)> = Vec::new();-- // 1. Local AI (Ollama, embeddings) — the heaviest single warm-up,- // so keeping it off the critical path for the others is the biggest win.- {- let config = config.clone();- tasks.push((- "local_ai",- tokio::spawn(async move {- if config.local_ai.runtime_enabled {- let step = std::time::Instant::now();- log::debug!("[services] local AI bootstrap starting");- crate::inference::local::global(&config)- .bootstrap(&config)- .await;- log::debug!(- "[services] local AI bootstrapped after login ({} ms)",- step.elapsed().as_millis()- );- } else {- log::debug!("[services] local AI disabled — skipping bootstrap");- }- }),- ));- }-- // 2+3. Voice hotkey services — the user-facing command registration. The- // embedded voice server owns the single rdev listener; the standalone- // dictation listener only starts when the server is NOT auto-starting,- // so keep these two ordered *relative to each other* (but concurrent- // with everything else).- {- let config = config.clone();- tasks.push((- "voice_hotkey",- tokio::spawn(async move {- let step = std::time::Instant::now();- crate::voice::server::start_if_enabled(&config).await;- if !config.voice_server.auto_start {- crate::voice::dictation_listener::start_if_enabled(&config).await;- }- log::debug!(- "[services] voice hotkey services registered ({} ms)",- step.elapsed().as_millis()- );- }),- ));- }-- // 3b. Always-on listening (Phase 2): continuous mic + VAD → STT → agent.- // Its cold WASAPI init (`always_on::spawn_capture_thread`) is the- // Windows-specific blocker; it now runs the blocking capture-readiness- // handshake on the blocking pool (see `always_on::start_if_enabled`), so- // on its own task it neither stalls an async worker nor the hotkey /- // command registration above.- {- let config = config.clone();- tasks.push((- "always_on",- tokio::spawn(async move {- let step = std::time::Instant::now();- crate::voice::always_on::start_if_enabled(&config).await;- log::debug!(- "[services] always-on listening started ({} ms)",- step.elapsed().as_millis()- );- }),- ));- }-- let total = tasks.len();- let mut failed = 0usize;- for (name, task) in tasks {- if let Err(err) = task.await {- failed += 1;- log::warn!("[services] login-gated service '{name}' panicked during startup: {err}");- }- }- let elapsed_ms = started.elapsed().as_millis();- if failed == 0 {- log::info!(- "[services] all {total} login-gated services started concurrently ({elapsed_ms} ms)"- );- } else {- log::warn!(- "[services] {failed}/{total} login-gated services failed to start ({elapsed_ms} ms)"- );- }-}--/// Stop all login-gated background services. Called from `clear_session()`-/// on logout so orphan processes don't consume resources.-pub async fn stop_login_gated_services(config: &Config) {- // 2. Voice server- if let Some(server) = crate::voice::server::try_global_server() {- server.stop().await;- log::info!("[services] voice server stopped on logout");- }-- // 4. Local AI — reset state to idle. We don't kill the Ollama process- // (it may be serving other clients or mid-download), but we clear- // the internal state so it re-bootstraps on next login.- if config.local_ai.runtime_enabled {- let service = crate::inference::local::global(config);- service.reset_to_idle(config);- log::info!("[services] local AI reset to idle on logout");- }-- // 5. Dictation listener — abort the hotkey forwarder task so it doesn't- // accumulate duplicate rdev listeners across logout → login cycles.- crate::voice::dictation_listener::stop();-- // 6. Always-on listening — disable the runtime gate so the mic capture loop- // stops transcribing/delivering after logout (no audio processed while- // logged out). Symmetric with start_login_gated_services step 3b.- crate::voice::always_on::stop();-- log::info!("[services] all login-gated services stopped");-}--pub(crate) fn secret_store_for_config(config: &Config) -> SecretStore {- let data_dir = config- .config_path- .parent()- .map_or_else(|| std::path::PathBuf::from("."), std::path::PathBuf::from);- SecretStore::new(&data_dir, true)-}--pub async fn encrypt_secret(- config: &Config,- plaintext: &str,-) -> Result<RpcOutcome<String>, String> {- let store = secret_store_for_config(config);- let ciphertext = store.encrypt(plaintext).map_err(|e| e.to_string())?;- Ok(RpcOutcome::single_log(ciphertext, "secret encrypted"))-}--pub async fn decrypt_secret(- config: &Config,- ciphertext: &str,-) -> Result<RpcOutcome<String>, String> {- let store = secret_store_for_config(config);- let plaintext = store.decrypt(ciphertext).map_err(|e| e.to_string())?;- Ok(RpcOutcome::single_log(plaintext, "secret decrypted"))-}--pub async fn store_session(- config: &Config,- token: &str,- user_id: Option<String>,- user: Option<serde_json::Value>,-) -> Result<RpcOutcome<super::super::responses::AuthProfileSummary>, String> {- store_session_inner(config, token, user_id, user, false).await-}--/// Store a session from a callback flow that already exchanged a backend-/// login token. Generic callers should use `store_session`, which requires-/// immediate `/auth/me` proof before persisting remote JWTs.-pub async fn store_session_with_deferred_validation(- config: &Config,- token: &str,- user_id: Option<String>,- user: Option<serde_json::Value>,-) -> Result<RpcOutcome<super::super::responses::AuthProfileSummary>, String> {- store_session_inner(config, token, user_id, user, true).await-}--async fn store_session_inner(- config: &Config,- token: &str,- user_id: Option<String>,- user: Option<serde_json::Value>,- allow_pending_backend_validation: bool,-) -> Result<RpcOutcome<super::super::responses::AuthProfileSummary>, String> {- let trimmed_token = token.trim();- if trimmed_token.is_empty() {- return Err("token is required".to_string());- }-- let api_url = effective_backend_api_url(&config.api_url);- let local_session = is_local_session_token(trimmed_token);- let local_user_id = local_session.then(local_session_user_id);- let mut session_validation_logs = Vec::new();- let settings = if local_session {- sanitize_stored_session_user(user.clone())- .map(|value| {- normalize_local_session_user(- value,- local_user_id.as_deref().unwrap_or(LOCAL_SESSION_USER_ID),- )- })- .ok_or_else(|| "local session requires a user payload".to_string())?- } else {- let client = BackendOAuthClient::new(&api_url).map_err(|e| e.to_string())?;- match fetch_current_user_for_session_store(&client, trimmed_token).await {- Ok(fetched_user) => {- session_validation_logs.push(format!(- "session JWT verified via GET /auth/me on {}",- api_url.trim_end_matches('/')- ));- fetched_user- }- Err(reason) => {- // This is the store-time validation gate: if it fails the profile- // is NEVER persisted, so the user bounces straight back to the- // signin page after a "successful" OAuth. Timeouts/gateway 5xx are- // otherwise dropped by the Sentry transient classifier, so log an- // explicit, grep-friendly WARN to the app log regardless.- if !auth_me_store_failure_is_transient(&reason) {- tracing::warn!(- domain = "credentials",- operation = "store_session",- "[credentials][auth-store] GET /auth/me validation FAILED on {} — session NOT persisted; user will bounce to signin: {reason}",- api_url.trim_end_matches('/')- );- return Err(format!(- "Session validation failed (GET /auth/me): {reason}"- ));- }-- if !allow_pending_backend_validation {- tracing::warn!(- domain = "credentials",- operation = "store_session",- "[credentials][auth-store] GET /auth/me transient validation failed on {} — session NOT persisted; backend proof required before storing remote JWT: {reason}",- api_url.trim_end_matches('/')- );- return Err(format!(- "Session validation failed (GET /auth/me): {reason}"- ));- }-- let Some(exp) = jwt_exp_live_at(trimmed_token, chrono::Utc::now()) else {- tracing::warn!(- domain = "credentials",- operation = "store_session",- "[credentials][auth-store] GET /auth/me transient validation failed on {} but JWT has no live local exp — session NOT persisted: {reason}",- api_url.trim_end_matches('/')- );- return Err(format!(- "Session validation failed (GET /auth/me): {reason}"- ));- };-- tracing::warn!(- domain = "credentials",- operation = "store_session",- exp = %exp,- "[credentials][auth-store] GET /auth/me transient validation failed on {} — persisting caller-authorized pending session for backend revalidation: {reason}",- api_url.trim_end_matches('/')- );- session_validation_logs.push(format!(- "session JWT accepted with deferred GET /auth/me validation on {} after transient failure",- api_url.trim_end_matches('/')- ));- fallback_session_user_for_deferred_validation()- }- }- };-- let mut metadata = std::collections::HashMap::new();- if let Some(uid) = if local_session {- local_user_id.clone()- } else {- user_id- .and_then(|v| {- let t = v.trim().to_string();- (!t.is_empty()).then_some(t)- })- .or_else(|| user_id_from_profile_payload(&settings))- } {- metadata.insert("user_id".to_string(), uid);- }- let pending_backend_validation = settings- .as_object()- .and_then(|map| map.get("pendingBackendValidation"))- .and_then(Value::as_bool)- .unwrap_or(false);- let user_for_store = if local_session || pending_backend_validation {- settings.clone()- } else {- sanitize_stored_session_user(user).unwrap_or(settings)- };- metadata.insert("user_json".to_string(), user_for_store.to_string());-- // Record the JWT `exp` so `require_live_session_token` can reject an expired- // token locally instead of firing a doomed backend 401 (#3297 RCA — the- // TAURI-RUST-8WY/8WZ flood). Local offline sessions aren't JWTs and carry no- // `exp`; `decode_jwt_exp` returns None for them and the key is simply omitted- // (presence-only check + the `flatten_authed_error` 401 net still apply).- if !local_session {- match decode_jwt_exp(trimmed_token) {- Some(exp) => {- metadata.insert(- crate::security::credentials::session_support::SESSION_EXPIRES_AT_META- .to_string(),- exp.to_rfc3339(),- );- tracing::info!(- domain = "credentials",- operation = "store_session",- "[credentials] recorded app-session expiry exp={exp} for local precheck"- );- }- None => tracing::debug!(- domain = "credentials",- operation = "store_session",- "[credentials] app-session token has no decodable `exp`; local expiry precheck disabled (falls back to 401 net)"- ),- }- }-- // Determine user_id so we can scope the openhuman directory to this user.- let resolved_user_id = metadata.get("user_id").cloned();- if pending_backend_validation && resolved_user_id.is_none() && !is_embedder_host() {- if let Ok(root_dir) = default_root_openhuman_dir() {- if let Some(active_user_id) = read_active_user_id(&root_dir) {- let active_user_dir = user_openhuman_dir(&root_dir, &active_user_id);- if config.config_path.parent() == Some(active_user_dir.as_path()) {- tracing::warn!(- domain = "credentials",- operation = "store_session",- active_user_id = %active_user_id,- "[credentials][auth-store] unresolved pending session would replace active user's app-session; session NOT persisted"- );- return Err(- "Session validation failed (GET /auth/me): backend user id required before replacing the active session"- .to_string(),- );- }- }- }- }-- // If we know the user_id, activate the user-scoped directory BEFORE storing- // the auth profile so that credentials land in the correct place.- let mut logs = if local_session {- vec!["local session accepted without backend validation".to_string()]- } else {- session_validation_logs- };-- // An embedder host (the harness) keeps session state under its own- // `config_path` scope and must never touch the operator's global- // `~/.openhuman/active_user.toml` or `users/` tree. Writing it would change- // which user the operator's real install believes is active purely by- // virtue of running a library call — the exact global side effect an- // ephemeral harness exists to avoid. The scoped auth profile is still- // stored below; only the global activation is skipped.- let operator_user_activation = !is_embedder_host();-- if let Some(ref uid) = resolved_user_id- .as_ref()- .filter(|_| operator_user_activation)- {- if let Ok(root_dir) = default_root_openhuman_dir() {- // Snapshot before we overwrite `active_user.toml` so we can tell- // first activation from signed-out vs an in-place account switch.- let previous_active = read_active_user_id(&root_dir);- let user_dir = user_openhuman_dir(&root_dir, uid);- if let Err(e) = std::fs::create_dir_all(&user_dir) {- tracing::warn!(- user_id = %uid,- error = %e,- "failed to create user directory"- );- } else if let Err(e) = write_active_user_id(&root_dir, uid) {- tracing::warn!(- user_id = %uid,- error = %e,- "failed to write active_user.toml"- );- } else {- logs.push(format!("user directory activated for {uid}"));- tracing::info!(- user_id = %uid,- user_dir = %user_dir.display(),- "User-scoped directory activated"- );- // Onboarding and other pre-auth flows write threads under the- // `users/local/workspace` tree. After the first successful login- // there was no previous `active_user.toml`, wipe that anonymous- // conversation store so a fresh account never inherits demo or- // scratch threads from the pre-login bucket (#1157).- //- // This shares `memory::conversations`' process-wide mutex with- // `list_threads` / `purge_threads` on any workspace, so purge and- // concurrent thread RPC in this process cannot interleave.- if previous_active.is_none() {- let pre_ws = pre_login_user_dir(&root_dir).join("workspace");- let pre_ws_log = pre_ws.display().to_string();- match conversations::purge_threads(pre_ws) {- Ok(stats) => {- tracing::info!(- pre_login_workspace = %pre_ws_log,- threads = stats.thread_count,- messages = stats.message_count,- "[credentials] purged pre-login conversation threads after first session activation"- );- logs.push(format!(- "purged pre-login conversation history (threads={}, messages={})",- stats.thread_count, stats.message_count- ));- }- Err(e) => {- tracing::debug!(- error = %e,- pre_login_workspace = %pre_ws_log,- "[credentials] pre-login conversation purge skipped (non-fatal)"- );- }- }- }- }- }- }-- // Reload config so it picks up the newly activated user directory.- // This ensures auth-profiles.json, encryption key, etc. are written- // to the user-scoped location.- let effective_config = if resolved_user_id.is_some() {- match crate::config::load_config_with_timeout().await {- Ok(c) => c,- Err(_) => config.clone(),- }- } else {- config.clone()- };-- if let Err(error) = crate::cron::seed::prune_retired_jobs(&effective_config) {- tracing::warn!(- error = %error,- "[credentials] failed to prune retired cron jobs after user workspace activation"- );- }-- if local_session {- match crate::config::ops::set_onboarding_completed(false).await {- Ok(_) => logs.push("onboarding left incomplete for local session setup".to_string()),- Err(error) => logs.push(format!(- "onboarding setup warning for local session: {error}"- )),- }- }-- let auth = AuthService::from_config(&effective_config);- let profile = auth- .store_provider_token(- APP_SESSION_PROVIDER,- DEFAULT_AUTH_PROFILE_NAME,- trimmed_token,- metadata,- true,- )- .map_err(|e| e.to_string())?;-- logs.push("session stored".to_string());-- // ── No explicit memory re-point here any more (#5560) ──────────────────- //- // This site used to call `tinymemory_core::global::init(...)` before the- // context rebind below. That was load-bearing for the *engine singleton*: a- // single process-global slot that keeps writing into the pre-login- // workspace until something re-points it, which is why it needed its own- // call at every login / logout / revalidation site.- //- // `memory::binding` is a workspace-keyed cache, not a slot, and- // `CoreContext::memory_binding`'s own docs already state the consequence:- // "there is **no** explicit 'rebind the memory driver' call at the login /- // logout / revalidation sites the way `memory::global::init` needs one: the- // accessor keys on the workspace dir and the subsystem config, both of- // which those sites already re-point." The `rebind_default_workspace` call- // immediately below re-points both, so memory follows it by construction.- //- // The binding is resolved lazily on the next memory call rather than warmed- // here. Warming it would mean naming `binding::for_workspace` at a site- // that never touches memory content, which the memory-guard bypass ratchet- // is right to treat as reach-through.- match crate::core::runtime::context::CoreContext::rebind_default_workspace(- &effective_config.workspace_dir,- effective_config.subsystems.memory.clone(),- ) {- Ok(_) => logs.push(format!(- "core context bound to workspace {}",- effective_config.workspace_dir.display()- )),- Err(e) => {- tracing::warn!(error = %e, "[credentials] failed to rebind core context after login");- logs.push(format!("core context bind warning: {e}"));- }- }- // No people-store rebind here any more: people is served by the bound- // memory driver, and `rebind_default_workspace` above already moved that- // binding to the per-user workspace. Seeding a host-side global as well- // opened the engine's database a second time in this process (#4378 fixed- // the workspace it pointed at; the module port removes the second reader).- crate::memory::conversations::register_conversation_persistence_subscriber(- effective_config.workspace_dir.clone(),- );- logs.push("conversation persistence bound to active workspace".to_string());-- // Start all login-gated services (voice and local AI).- // Uses the effective config so services see the user-scoped workspace- // directory.- start_login_gated_services(&effective_config).await;- logs.push("login-gated services started".to_string());-- // Clear the scheduler-gate signed-out override now that a fresh JWT is- // in place. Workers that were sleeping in the paused poll loop will- // pick this up at their next iteration and resume LLM-bound work.- crate::cron::scheduler_gate::set_signed_out(false);- tracing::debug!(- domain = "credentials",- operation = "store_session",- "[credentials][auth-store] scheduler gate cleared; ensuring re-embed backfill after login"- );- crate::memory::ops::maintenance::reembed_best_effort(&effective_config, "session stored").await;- logs.push("memory re-embed backfill checked after login".to_string());-- // Bind the Sentry scope to this user so background events that fire- // before the frontend's `app_state_snapshot` warms the user cache still- // carry `user.id` — issue #3135. The `before_send` filter is now a- // fallback for legacy cache-warming paths; setting scope here is the- // primary source.- if let Some(ref uid) = resolved_user_id {- crate::security::credentials::sentry_scope::bind(uid);- }-- Ok(RpcOutcome::new(summarize_auth_profile(&profile), logs))-}--/// Store-time `GET /auth/me` budget resolver. Reads the-/// `OPENHUMAN_AUTH_ME_STORE_TIMEOUT_MS` override (positive integer milliseconds),-/// otherwise the `AUTH_ME_STORE_VALIDATION_BUDGET` default.-pub(crate) fn auth_me_store_validation_budget() -> Duration {- std::env::var(AUTH_ME_STORE_VALIDATION_BUDGET_ENV)- .ok()- .and_then(|raw| raw.trim().parse::<u64>().ok())- .filter(|ms| *ms > 0)- .map(Duration::from_millis)- .unwrap_or(AUTH_ME_STORE_VALIDATION_BUDGET)-}--/// Validate the freshly minted session token against `GET /auth/me`, bounded by-/// `auth_me_store_validation_budget()`. On budget exhaustion returns a-/// transient-classified timeout error so `store_session_inner` routes a-/// live-`exp` JWT into the deferred-validation fallback rather than hanging until-/// the desktop sign-in RPC times out and bounces the user (issue #5166).-async fn fetch_current_user_for_session_store(- client: &BackendOAuthClient,- token: &str,-) -> Result<Value, String> {- let budget = auth_me_store_validation_budget();- match tokio::time::timeout(- budget,- fetch_current_user_for_session_store_inner(client, token),- )- .await- {- Ok(result) => result,- Err(_elapsed) => {- // Message must contain a `TRANSIENT_TRANSPORT_PHRASES` phrase- // ("timeout") so `auth_me_store_failure_is_transient` buckets it as- // transient and the deferred-validation path can take over.- let reason = format!(- "GET /auth/me validation timeout after {}ms (store-time budget exceeded)",- budget.as_millis()- );- tracing::warn!(- domain = "credentials",- operation = "fetch_current_user_for_session_store",- budget_ms = budget.as_millis() as u64,- "[credentials][auth-store] {reason}"- );- Err(reason)- }- }-}--async fn fetch_current_user_for_session_store_inner(- client: &BackendOAuthClient,- token: &str,-) -> Result<Value, String> {- match client.fetch_current_user(token).await {- Ok(user) => Ok(user),- Err(first) => {- let first_reason = format!("{first:#}");- if !auth_me_store_failure_is_transient(&first_reason) {- return Err(first_reason);- }-- tokio::time::sleep(AUTH_ME_STORE_RETRY_DELAY).await;- tracing::debug!(- domain = "credentials",- operation = "fetch_current_user_for_session_store",- reason = %first_reason,- "[credentials][auth-store] retrying GET /auth/me after transient failure"- );- client- .fetch_current_user(token)- .await- .map_err(|second| format!("{second:#}"))- }- }-}--pub(crate) fn auth_me_store_failure_is_transient(reason: &str) -> bool {- if let Some(status) = auth_me_failure_status(reason) {- return AUTH_ME_STORE_TRANSIENT_STATUSES.contains(&status);- }-- crate::core::observability::contains_transient_transport_phrase(reason)-}--fn auth_me_failure_status(reason: &str) -> Option<u16> {- let lower = reason.to_ascii_lowercase();- (100..600).find(|status| {- let status = status.to_string();- lower.contains(&format!("({status}"))- || lower.contains(&format!("http {status}"))- || lower.contains(&format!("status {status}"))- || lower.contains(&format!("status code {status}"))- })-}--fn jwt_exp_live_at(- token: &str,- now: chrono::DateTime<chrono::Utc>,-) -> Option<chrono::DateTime<chrono::Utc>> {- let exp = decode_jwt_exp(token)?;- (exp > now).then_some(exp)-}--fn fallback_session_user_for_deferred_validation() -> Value {- json!({ "pendingBackendValidation": true })-}--pub(crate) fn sanitize_stored_session_user(- user: Option<serde_json::Value>,-) -> Option<serde_json::Value> {- match user {- Some(serde_json::Value::Object(map)) if map.is_empty() => None,- Some(serde_json::Value::Null) => None,- other => other,- }-}--pub(crate) fn normalize_local_session_user(- user: serde_json::Value,- local_user_id: &str,-) -> serde_json::Value {- let mut map = match user {- serde_json::Value::Object(map) => map,- other => return other,- };- map.insert(- "id".to_string(),- serde_json::Value::String(local_user_id.to_string()),- );- map.insert(- "_id".to_string(),- serde_json::Value::String(local_user_id.to_string()),- );- serde_json::Value::Object(map)-}--pub async fn clear_session(config: &Config) -> Result<RpcOutcome<serde_json::Value>, String> {- let mut logs = Vec::new();- let removed = {- let _session_mutation_lock = crate::desktop::app_state::CURRENT_USER_SESSION_MUTATION_LOCK- .lock()- .await;- // Flip the scheduler-gate override first so any background worker that- // is mid-iteration (or wakes up while we tear down) stalls at its next- // `wait_for_capacity()` call instead of firing requests at a backend- // we're about to invalidate. Idempotent.- crate::cron::scheduler_gate::set_signed_out(true);-- // Invalidate before removing the profile so a pending revalidation cannot- // recreate it after logout has finished the removal.- crate::desktop::app_state::forget_current_user_caches();-- let auth = AuthService::from_config(config);- auth.remove_profile(APP_SESSION_PROVIDER, DEFAULT_AUTH_PROFILE_NAME)- .map_err(|e| e.to_string())?- };-- // The core process stays alive on logout. Tear down its authenticated- // Socket.IO transport and the user-pinned workflow bridge so neither can- // keep serving the signed-out account until a later reconnect.- if let Some(manager) = crate::platform::socket::global_socket_manager() {- if let Err(error) = manager.disconnect().await {- tracing::warn!(%error, "failed to disconnect backend socket on logout");- }- }- crate::platform::socket::medulla::workflows::clear_workflow_bridge();-- // Clear the active user marker so subsequent config loads fall back to the- // default (unauthenticated) openhuman directory.- if let Ok(root_dir) = default_root_openhuman_dir() {- if let Err(e) = crate::config::clear_active_user(&root_dir) {- tracing::warn!(error = %e, "failed to clear active_user.toml on logout");- }- }-- // Stop all login-gated services (voice and local AI) so- // they don't run as orphan processes after logout, consuming RAM/CPU with- // no user context to operate against.- stop_login_gated_services(config).await;-- // The process stays alive after desktop/TUI logout, so every process-global- // store must follow the now-active pre-login workspace. Without this, a- // signed-out caller can keep reading the previous account's context until- // the process restarts.- match crate::config::load_config_with_timeout().await {- Ok(signed_out_config) => {- let workspace = signed_out_config.workspace_dir.clone();- // No `memory::global::init` twin here either — see the login site.- // The context rebind below carries the signed-out workspace and its- // `[subsystems.memory]` block, and the memory binding is keyed on- // exactly that pair, so it follows without a second call.- if let Err(error) = crate::core::runtime::context::CoreContext::rebind_default_workspace(- &workspace,- signed_out_config.subsystems.memory.clone(),- ) {- tracing::warn!(%error, "failed to rebind core context after logout");- }- crate::memory::conversations::register_conversation_persistence_subscriber(- workspace.clone(),- );- logs.push(format!(- "process globals rebound to signed-out workspace {}",- workspace.display()- ));- }- Err(error) => {- tracing::warn!(%error, "failed to resolve signed-out workspace after logout");- logs.push(format!("signed-out workspace rebind warning: {error}"));- }- }-- // Drop the Sentry scope user so events surfaced during/after teardown- // (and before the next login) are no longer attributed to the- // signed-out account — issue #3135.- crate::security::credentials::sentry_scope::clear();-- logs.push("session cleared".to_string());- Ok(RpcOutcome::new(json!({ "removed": removed }), logs))-}--pub async fn auth_get_state(- config: &Config,-) -> Result<RpcOutcome<super::super::responses::AuthStateResponse>, String> {- let state = build_session_state(config)?;- Ok(RpcOutcome::single_log(state, "session state fetched"))-}--pub async fn auth_get_session_token_json(- config: &Config,-) -> Result<RpcOutcome<serde_json::Value>, String> {- let token = get_session_token(config)?;- Ok(RpcOutcome::single_log(- json!({ "token": token }),- "session token fetched",- ))-}--pub async fn auth_get_me(config: &Config) -> Result<RpcOutcome<serde_json::Value>, String> {- let api_url = effective_backend_api_url(&config.api_url);- let token = get_session_token(config)?.ok_or_else(|| "session JWT required".to_string())?;- let client = BackendOAuthClient::new(&api_url).map_err(|e| e.to_string())?;- let user = client- .fetch_current_user(&token)- .await- // `flatten_authed_error` maps the typed `BackendApiError::Unauthorized`- // onto the `SESSION_EXPIRED:` sentinel and falls through to `{e:#}` for- // everything else, so both properties this call site needs are kept:- //- // * Non-401s still render the full anyhow context chain, so the- // underlying reqwest transport error (timeout / connection reset /- // TLS / DNS) reaches `observability::is_transient_message_failure`.- // Bare `e.to_string()` renders only the top context layer- // ("GET /auth/me") and collapsed every transient transport failure- // into Sentry TAURI-RUST-10.- // * A 401 is recognised by `jsonrpc::is_session_expired_error`, which- // skips the Sentry report AND publishes `DomainEvent::SessionExpired`- // so `SessionExpiredSubscriber` clears the dead JWT.- //- // Until #5232 routed `fetch_current_user` through `authed_json`, a 401- // here surfaced as `"GET /auth/me failed (401 Unauthorized): …"`, which- // `is_session_expired_error` matched on its HTTP-verb prefix. The typed- // error renders as `"backend rejected session token on GET /auth/me"`,- // which matches neither classifier — so on 0.63.9 every lapsed session- // reported to Sentry as a code defect (TAURI-RUST-RYD) and, because the- // stale token was never cleared, re-fired the same 401 on the next- // revalidation: the forced sign-out loop in #5307.- .map_err(crate::api::flatten_authed_error)?;-- Ok(RpcOutcome::single_log(user, "current user fetched"))-}diff --git a/crates/openhuman-core/src/security/credentials/ops/session_query.rs b/crates/openhuman-core/src/security/credentials/ops/session_query.rsnew file mode 100644index 0000000000..9ce21b2aa7--- /dev/null+++ b/crates/openhuman-core/src/security/credentials/ops/session_query.rs@@ -0,0 +1,148 @@+//! Session teardown (`clear_session`) and read-only session state lookups.++use serde_json::json;++use crate::api::config::effective_backend_api_url;+use crate::api::jwt::get_session_token;+use crate::api::rest::BackendOAuthClient;+use crate::config::{default_root_openhuman_dir, Config};+use crate::rpc::RpcOutcome;+use crate::security::credentials::session_support::build_session_state;+use crate::security::credentials::{AuthService, APP_SESSION_PROVIDER, DEFAULT_AUTH_PROFILE_NAME};++use super::login_services::stop_login_gated_services;++pub async fn clear_session(config: &Config) -> Result<RpcOutcome<serde_json::Value>, String> {+ let mut logs = Vec::new();+ let removed = {+ let _session_mutation_lock = crate::desktop::app_state::CURRENT_USER_SESSION_MUTATION_LOCK+ .lock()+ .await;+ // Flip the scheduler-gate override first so any background worker that+ // is mid-iteration (or wakes up while we tear down) stalls at its next+ // `wait_for_capacity()` call instead of firing requests at a backend+ // we're about to invalidate. Idempotent.+ crate::cron::scheduler_gate::set_signed_out(true);++ // Invalidate before removing the profile so a pending revalidation cannot+ // recreate it after logout has finished the removal.+ crate::desktop::app_state::forget_current_user_caches();++ let auth = AuthService::from_config(config);+ auth.remove_profile(APP_SESSION_PROVIDER, DEFAULT_AUTH_PROFILE_NAME)+ .map_err(|e| e.to_string())?+ };++ // The core process stays alive on logout. Tear down its authenticated+ // Socket.IO transport and the user-pinned workflow bridge so neither can+ // keep serving the signed-out account until a later reconnect.+ if let Some(manager) = crate::platform::socket::global_socket_manager() {+ if let Err(error) = manager.disconnect().await {+ tracing::warn!(%error, "failed to disconnect backend socket on logout");+ }+ }+ crate::platform::socket::medulla::workflows::clear_workflow_bridge();++ // Clear the active user marker so subsequent config loads fall back to the+ // default (unauthenticated) openhuman directory.+ if let Ok(root_dir) = default_root_openhuman_dir() {+ if let Err(e) = crate::config::clear_active_user(&root_dir) {+ tracing::warn!(error = %e, "failed to clear active_user.toml on logout");+ }+ }++ // Stop all login-gated services (voice and local AI) so+ // they don't run as orphan processes after logout, consuming RAM/CPU with+ // no user context to operate against.+ stop_login_gated_services(config).await;++ // The process stays alive after desktop/TUI logout, so every process-global+ // store must follow the now-active pre-login workspace. Without this, a+ // signed-out caller can keep reading the previous account's context until+ // the process restarts.+ match crate::config::load_config_with_timeout().await {+ Ok(signed_out_config) => {+ let workspace = signed_out_config.workspace_dir.clone();+ // No `memory::global::init` twin here either — see the login site.+ // The context rebind below carries the signed-out workspace and its+ // `[subsystems.memory]` block, and the memory binding is keyed on+ // exactly that pair, so it follows without a second call.+ if let Err(error) = crate::core::runtime::context::CoreContext::rebind_default_workspace(+ &workspace,+ signed_out_config.subsystems.memory.clone(),+ ) {+ tracing::warn!(%error, "failed to rebind core context after logout");+ }+ crate::memory::conversations::register_conversation_persistence_subscriber(+ workspace.clone(),+ );+ logs.push(format!(+ "process globals rebound to signed-out workspace {}",+ workspace.display()+ ));+ }+ Err(error) => {+ tracing::warn!(%error, "failed to resolve signed-out workspace after logout");+ logs.push(format!("signed-out workspace rebind warning: {error}"));+ }+ }++ // Drop the Sentry scope user so events surfaced during/after teardown+ // (and before the next login) are no longer attributed to the+ // signed-out account — issue #3135.+ crate::security::credentials::sentry_scope::clear();++ logs.push("session cleared".to_string());+ Ok(RpcOutcome::new(json!({ "removed": removed }), logs))+}++pub async fn auth_get_state(+ config: &Config,+) -> Result<RpcOutcome<super::super::responses::AuthStateResponse>, String> {+ let state = build_session_state(config)?;+ Ok(RpcOutcome::single_log(state, "session state fetched"))+}++pub async fn auth_get_session_token_json(+ config: &Config,+) -> Result<RpcOutcome<serde_json::Value>, String> {+ let token = get_session_token(config)?;+ Ok(RpcOutcome::single_log(+ json!({ "token": token }),+ "session token fetched",+ ))+}++pub async fn auth_get_me(config: &Config) -> Result<RpcOutcome<serde_json::Value>, String> {+ let api_url = effective_backend_api_url(&config.api_url);+ let token = get_session_token(config)?.ok_or_else(|| "session JWT required".to_string())?;+ let client = BackendOAuthClient::new(&api_url).map_err(|e| e.to_string())?;+ let user = client+ .fetch_current_user(&token)+ .await+ // `flatten_authed_error` maps the typed `BackendApiError::Unauthorized`+ // onto the `SESSION_EXPIRED:` sentinel and falls through to `{e:#}` for+ // everything else, so both properties this call site needs are kept:+ //+ // * Non-401s still render the full anyhow context chain, so the+ // underlying reqwest transport error (timeout / connection reset /+ // TLS / DNS) reaches `observability::is_transient_message_failure`.+ // Bare `e.to_string()` renders only the top context layer+ // ("GET /auth/me") and collapsed every transient transport failure+ // into Sentry TAURI-RUST-10.+ // * A 401 is recognised by `jsonrpc::is_session_expired_error`, which+ // skips the Sentry report AND publishes `DomainEvent::SessionExpired`+ // so `SessionExpiredSubscriber` clears the dead JWT.+ //+ // Until #5232 routed `fetch_current_user` through `authed_json`, a 401+ // here surfaced as `"GET /auth/me failed (401 Unauthorized): …"`, which+ // `is_session_expired_error` matched on its HTTP-verb prefix. The typed+ // error renders as `"backend rejected session token on GET /auth/me"`,+ // which matches neither classifier — so on 0.63.9 every lapsed session+ // reported to Sentry as a code defect (TAURI-RUST-RYD) and, because the+ // stale token was never cleared, re-fired the same 401 on the next+ // revalidation: the forced sign-out loop in #5307.+ .map_err(crate::api::flatten_authed_error)?;++ Ok(RpcOutcome::single_log(user, "current user fetched"))+}