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 core module files
Steven Enamakel449b3f57b2df
diff --git a/crates/openhuman-core/src/core/core_mod_tests.rs b/crates/openhuman-core/src/core/core_mod_tests.rsnew file mode 100644index 0000000000..6e11bedf97--- /dev/null+++ b/crates/openhuman-core/src/core/core_mod_tests.rs@@ -0,0 +1,115 @@+ use super::*;++ 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_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 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 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 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);+ }diff --git a/crates/openhuman-core/src/core/http_server_status.rs b/crates/openhuman-core/src/core/http_server_status.rsindex 49e867689a..10f042958c 100644--- a/crates/openhuman-core/src/core/http_server_status.rs+++ b/crates/openhuman-core/src/core/http_server_status.rs@@ -25,30 +25,6 @@pub const HTTP_SERVER_COMPILED_IN: bool = cfg!(feature = "http-server");#[cfg(test)]-mod tests {- use super::HTTP_SERVER_COMPILED_IN;+#[path = "http_server_status_tests.rs"]+mod tests;- /// 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 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/http_server_status_tests.rs b/crates/openhuman-core/src/core/http_server_status_tests.rsnew file mode 100644index 0000000000..6fbe680623--- /dev/null+++ b/crates/openhuman-core/src/core/http_server_status_tests.rs@@ -0,0 +1,25 @@+ 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"));+ }++ /// 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);+ }diff --git a/crates/openhuman-core/src/core/legacy_aliases.rs b/crates/openhuman-core/src/core/legacy_aliases.rsindex 35d9d26b5f..25f26bfb8b 100644--- a/crates/openhuman-core/src/core/legacy_aliases.rs+++ b/crates/openhuman-core/src/core/legacy_aliases.rs@@ -226,462 +226,6 @@ pub fn resolve_legacy(method: &str) -> &str {}#[cfg(test)]-mod tests {- use super::*;- use std::collections::{BTreeMap, BTreeSet};- use std::fs;- use std::path::PathBuf;+#[path = "legacy_aliases_tests.rs"]+mod tests;- 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}",- );- }- }-- #[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(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".- 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!(- 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:?}"- );- }-}diff --git a/crates/openhuman-core/src/core/legacy_aliases_tests.rs b/crates/openhuman-core/src/core/legacy_aliases_tests.rsnew file mode 100644index 0000000000..3c9e278f24--- /dev/null+++ b/crates/openhuman-core/src/core/legacy_aliases_tests.rs@@ -0,0 +1,457 @@+ 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}",+ );+ }+ }++ #[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(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".+ 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!(+ 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:?}"+ );+ }diff --git a/crates/openhuman-core/src/core/log_redaction.rs b/crates/openhuman-core/src/core/log_redaction.rsindex 48522a6b40..5ad0a001f1 100644--- a/crates/openhuman-core/src/core/log_redaction.rs+++ b/crates/openhuman-core/src/core/log_redaction.rs@@ -63,45 +63,6 @@ pub fn scrub_secrets(input: &str) -> String {}#[cfg(test)]-mod tests {- use super::scrub_secrets;+#[path = "log_redaction_tests.rs"]+mod tests;- #[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_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_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);- }-}diff --git a/crates/openhuman-core/src/core/log_redaction_tests.rs b/crates/openhuman-core/src/core/log_redaction_tests.rsnew file mode 100644index 0000000000..ba0f2b05ee--- /dev/null+++ b/crates/openhuman-core/src/core/log_redaction_tests.rs@@ -0,0 +1,40 @@+ use super::scrub_secrets;++ #[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_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_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);+ }diff --git a/crates/openhuman-core/src/core/logging.rs b/crates/openhuman-core/src/core/logging.rsindex 43f64288d2..64a260c3c6 100644--- a/crates/openhuman-core/src/core/logging.rs+++ b/crates/openhuman-core/src/core/logging.rs@@ -650,192 +650,6 @@ where}#[cfg(test)]-mod tests {- 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");- });- }-- #[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");- 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"),- }- }+#[path = "logging_tests.rs"]+mod tests;- #[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 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 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/logging_tests.rs b/crates/openhuman-core/src/core/logging_tests.rsnew file mode 100644index 0000000000..d14edae157--- /dev/null+++ b/crates/openhuman-core/src/core/logging_tests.rs@@ -0,0 +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");+ });+ }++ #[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");+ 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 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 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 697554fb64..4f2dcfff58 100644--- a/crates/openhuman-core/src/core/memory_cli.rs+++ b/crates/openhuman-core/src/core/memory_cli.rs@@ -627,195 +627,6 @@ fn print_memory_help() {}#[cfg(test)]-mod tests {- 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"- );- }- }-- /// 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"- );- }- }-- /// 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"- );- }- }-- /// 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}"- );- }- }+#[path = "memory_cli_tests.rs"]+mod tests;- /// 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:?})"- );- }- }- }-- /// 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!(- 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/memory_cli_tests.rs b/crates/openhuman-core/src/core/memory_cli_tests.rsnew file mode 100644index 0000000000..7a733aaf6b--- /dev/null+++ b/crates/openhuman-core/src/core/memory_cli_tests.rs@@ -0,0 +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};++ /// 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"+ );+ }+ }++ #[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);+ }++ /// `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"+ );+ }+ }++ /// 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:?})"+ );+ }+ }+ }++ /// 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!(+ 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 f4cdbc9747..679283fa3e 100644--- a/crates/openhuman-core/src/core/mod.rs+++ b/crates/openhuman-core/src/core/mod.rs@@ -126,120 +126,6 @@ pub enum TypeSchema {}#[cfg(test)]-mod tests {- use super::*;+#[path = "core_mod_tests.rs"]+mod tests;- 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_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 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 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 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);- }-}diff --git a/crates/openhuman-core/src/core/rpc_log.rs b/crates/openhuman-core/src/core/rpc_log.rsindex 674c382ad5..6093081332 100644--- a/crates/openhuman-core/src/core/rpc_log.rs+++ b/crates/openhuman-core/src/core/rpc_log.rs@@ -84,25 +84,6 @@ fn is_sensitive_key(key: &str) -> bool {}#[cfg(test)]-mod tests {- use super::*;- use serde_json::json;+#[path = "rpc_log_tests.rs"]+mod tests;- #[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/rpc_log_tests.rs b/crates/openhuman-core/src/core/rpc_log_tests.rsnew file mode 100644index 0000000000..3c4329c4ae--- /dev/null+++ b/crates/openhuman-core/src/core/rpc_log_tests.rs@@ -0,0 +1,20 @@+ 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");+ }diff --git a/crates/openhuman-core/src/core/runtime/builder.rs b/crates/openhuman-core/src/core/runtime/builder.rsindex 383ed088c3..16154a8d8f 100644--- a/crates/openhuman-core/src/core/runtime/builder.rs+++ b/crates/openhuman-core/src/core/runtime/builder.rs@@ -943,185 +943,6 @@ impl CoreRuntime {}#[cfg(test)]-mod tests {- use super::{DomainSet, ServiceSet};- use crate::core::all::DomainGroup;+#[path = "builder_tests.rs"]+mod tests;- #[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));- }-- #[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:?}");- }- }-- #[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/builder_tests.rs b/crates/openhuman-core/src/core/runtime/builder_tests.rsnew file mode 100644index 0000000000..558a1cbc6d--- /dev/null+++ b/crates/openhuman-core/src/core/runtime/builder_tests.rs@@ -0,0 +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));+ }++ #[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:?}");+ }+ }++ #[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 6b2d65e67b..3abd50475c 100644--- a/crates/openhuman-core/src/core/runtime/context.rs+++ b/crates/openhuman-core/src/core/runtime/context.rs@@ -788,446 +788,6 @@ pub async fn init_stores(cfg: &crate::config::Config, domains: crate::core::runt}#[cfg(test)]-mod tests {- use super::*;- use std::path::PathBuf;+#[path = "context_tests.rs"]+mod tests;- 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;- 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(),- ..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/context_tests.rs b/crates/openhuman-core/src/core/runtime/context_tests.rsnew file mode 100644index 0000000000..4df8ad6817--- /dev/null+++ b/crates/openhuman-core/src/core/runtime/context_tests.rs@@ -0,0 +1,441 @@+ 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;+ 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(),+ ..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 fa24a47f02..0a465d3f65 100644--- a/crates/openhuman-core/src/core/runtime/services.rs+++ b/crates/openhuman-core/src/core/runtime/services.rs@@ -560,124 +560,6 @@ pub fn spawn_socket_auto_connect(}#[cfg(test)]-mod tests {- use super::*;+#[path = "services_tests.rs"]+mod tests;- #[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;- }- }-- /// 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);- }-- /// 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);-- // 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);-- 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"- );-- // 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/runtime/services_tests.rs b/crates/openhuman-core/src/core/runtime/services_tests.rsnew file mode 100644index 0000000000..051b76136d--- /dev/null+++ b/crates/openhuman-core/src/core/runtime/services_tests.rs@@ -0,0 +1,119 @@+ 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");++ 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,+ }+ );+ }++ /// 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);++ 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);+ }++ /// 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);+ }++ /// 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"+ );+ }diff --git a/crates/openhuman-core/src/core/sentry_transport.rs b/crates/openhuman-core/src/core/sentry_transport.rsindex 93b759c589..5952a0dbe7 100644--- a/crates/openhuman-core/src/core/sentry_transport.rs+++ b/crates/openhuman-core/src/core/sentry_transport.rs@@ -160,74 +160,6 @@ pub fn factory(options: &ClientOptions) -> Arc<dyn Transport> {}#[cfg(test)]-mod tests {- use super::*;- use std::io::{Read, Write};- use std::net::TcpListener;+#[path = "sentry_transport_tests.rs"]+mod tests;- 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;- }- }- 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)));-- 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)));- }-}diff --git a/crates/openhuman-core/src/core/sentry_transport_tests.rs b/crates/openhuman-core/src/core/sentry_transport_tests.rsnew file mode 100644index 0000000000..0c77871ef8--- /dev/null+++ b/crates/openhuman-core/src/core/sentry_transport_tests.rs@@ -0,0 +1,69 @@+ 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+ }++ #[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+ .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)));++ 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)));+ }diff --git a/crates/openhuman-core/src/desktop/app_state/ops/snapshot.rs b/crates/openhuman-core/src/desktop/app_state/ops/snapshot.rsindex 0c85a73cc9..2bd0d463a8 100644--- a/crates/openhuman-core/src/desktop/app_state/ops/snapshot.rs+++ b/crates/openhuman-core/src/desktop/app_state/ops/snapshot.rs@@ -4,7 +4,7 @@use super::current_user::{current_user_api_base, fetch_current_user_cached, note_current_user_timeout, CurrentUserFetchError};use super::current_user_fetch::sanitize_snapshot_user;-use super::current_user_generation::CURRENT_USER_SESSION_MUTATION_LOCK;+use super::current_user_generation::{current_user_generation, CURRENT_USER_SESSION_MUTATION_LOCK};use super::auth_timeout::auth_fetch_timeout;use super::pending_session::{clear_deferred_session_after_backend_rejection, clear_pending_backend_validation_flag,